数据结构贪吃蛇完整代码
时间: 2024-06-05 12:04:47 浏览: 89
贪吃蛇是一个经典的游戏,它的实现需要用到一些基本的数据结构。下面是一个基于Python的贪吃蛇完整代码:
```
import pygame
import random
# 初始化pygame
pygame.init()
# 游戏界面大小
size = width, height = 640, 480
# 游戏界面背景颜色
bg = (255, 255, 255)
# 设置游戏界面大小、背景颜色和标题
screen = pygame.display.set_mode(size)
pygame.display.set_caption("贪吃蛇")
# 初始化蛇的位置和大小
snake = []
for i in range(5):
snake.append(pygame.Rect(20 * i, 20, 20, 20))
# 初始化蛇头、食物和移动方向
snake_head = snake[-1]
food = pygame.Rect(random.randint(0, width - 20), random.randint(0, height - 20), 20, 20)
direct = 'right'
# 设置游戏帧率
clock = pygame.time.Clock()
fps = 5
while True:
# 处理游戏退出事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 处理键盘事件
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and direct != 'right':
direct = 'left'
elif keys[pygame.K_RIGHT] and direct != 'left':
direct = 'right'
elif keys[pygame.K_UP] and direct != 'down':
direct = 'up'
elif keys[pygame.K_DOWN] and direct != 'up':
direct = 'down'
# 移动蛇头
if direct == 'left':
snake_head = snake[-1].move(-20, 0)
elif direct == 'right':
snake_head = snake[-1].move(20, 0)
elif direct == 'up':
snake_head = snake[-1].move(0, -20)
elif direct == 'down':
snake_head = snake[-1].move(0, 20)
# 判断是否吃到食物
if snake_head == food:
food = pygame.Rect(random.randint(0, width - 20), random.randint(0, height - 20), 20, 20)
fps += 1
else:
snake.pop(0)
# 判断游戏是否结束
if snake_head.left < 0 or snake_head.right > width or snake_head.top < 0 or snake_head.bottom > height or snake_head in snake[:-1]:
print('Game Over!')
pygame.quit()
exit()
# 添加蛇头
snake.append(snake_head)
# 绘制游戏界面
screen.fill(bg)
for s in snake:
pygame.draw.rect(screen, (0, 255, 0), s)
pygame.draw.rect(screen, (255, 0, 0), food)
pygame.display.update()
# 控制游戏帧率
clock.tick(fps)
```
阅读全文