使用Python编写简洁贪吃蛇游戏代码
时间: 2024-03-02 09:52:06 浏览: 62
好的,以下是一个简洁的贪吃蛇游戏代码:
```python
import pygame
import random
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义游戏窗口大小
width = 800
height = 600
# 初始化 Pygame
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('贪吃蛇')
# 定义蛇的初始位置和大小
snake_block = 10
snake_speed = 20
x1 = width / 2
y1 = height / 2
# 定义蛇的移动方向
x1_change = 0
y1_change = 0
# 生成食物的初始位置
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
# 定义字体
font_style = pygame.font.SysFont(None, 50)
# 定义得分函数
def message(msg, color):
mesg = font_style.render(msg, True, color)
screen.blit(mesg, [width / 6, height / 3])
# 游戏主循环
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
# 判断是否碰到边界
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_over = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
# 清空屏幕
screen.fill(black)
# 画出食物和蛇
pygame.draw.rect(screen, red, [foodx, foody, snake_block, snake_block])
pygame.draw.rect(screen, white, [x1, y1, snake_block, snake_block])
# 判断是否吃到了食物
if x1 == foodx and y1 == foody:
print('Yummy!!')
else:
pygame.display.update()
# 更新食物的位置
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
# 更新屏幕
pygame.display.update()
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 关闭 Pygame
pygame.quit()
quit()
```
这个代码使用 Pygame 模块来创建游戏窗口和处理游戏逻辑,实现了一个简单的贪吃蛇游戏。
阅读全文