gene_x 0 like s 227 view s
Tags: python, game
贪吃蛇是一款经典的游戏,可以用Python的Pygame库来实现。以下是一个简单的贪吃蛇游戏实现:
首先,确保已经安装了Python和Pygame库。如果没有安装Pygame,请使用以下命令进行安装:
pip install pygame
创建一个新的Python文件(例如:snake.py),然后复制以下代码到文件中:
import sys
import pygame
import random
pygame.init()
# 游戏窗口设置
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('贪吃蛇')
# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
# 蛇和食物的大小
block_size = 20
# 初始化蛇的位置
snake = [(width // 2, height // 2)]
snake_speed = block_size
snake_direction = 'right'
# 初始化食物的位置
food = (random.randint(1, width // block_size - 1) * block_size, random.randint(1, height // block_size - 1) * block_size)
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 检测键盘方向键
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake_direction != 'down':
snake_direction = 'up'
elif event.key == pygame.K_DOWN and snake_direction != 'up':
snake_direction = 'down'
elif event.key == pygame.K_LEFT and snake_direction != 'right':
snake_direction = 'left'
elif event.key == pygame.K_RIGHT and snake_direction != 'left':
snake_direction = 'right'
x, y = snake[0]
if snake_direction == 'up':
y -= snake_speed
elif snake_direction == 'down':
y += snake_speed
elif snake_direction == 'left':
x -= snake_speed
elif snake_direction == 'right':
x += snake_speed
snake.insert(0, (x, y))
# 检测蛇是否吃到食物
if snake[0] == food:
food = (random.randint(1, width // block_size - 1) * block_size, random.randint(1, height // block_size - 1) * block_size)
else:
snake.pop()
# 检测蛇是否撞到边界或自身
if (x < 0 or x >= width or y < 0 or y >= height) or snake[0] in snake[1:]:
pygame.quit()
sys.exit()
screen.fill(black)
# 绘制蛇
for segment in snake:
pygame.draw.rect(screen, white, pygame.Rect(segment[0], segment[1], block_size, block_size))
# 绘制食物
pygame.draw.rect(screen, red, pygame.Rect(food[0], food[1], block_size, block_size))
pygame.display.flip()
# 设置游戏速度
clock.tick(4)
运行贪吃蛇游戏:
保存Python文件(例如:snake.py)。
运行以下命令启动游戏:
python3 snake.py
现在,你应该看到一个贪吃蛇游戏窗口。你可以使用方向键来控制蛇的移动。当蛇吃到红色的食物时,它会变长。如果蛇碰到屏幕边缘或者自己的身体,游戏就会结束。
点赞本文的读者
还没有人对此文章表态
没有评论
Co-Authorship Network Visualization in Python
Small RNA sequencing processing in the example of smallRNA_7
© 2023 XGenes.com Impressum