编写一个python贪吃蛇游戏
时间: 2023-09-18 08:11:41 浏览: 42
以下是一个简单的Python贪吃蛇游戏的代码,使用了Pygame库:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 游戏窗口大小
screen_width = 480
screen_height = 480
# 创建游戏窗口
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
green = (0, 255, 0)
red = (255, 0, 0)
# 定义方向
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
# 蛇的初始位置和长度
snake_pos = [(screen_width // 2, screen_height // 2)]
snake_len = 1
# 食物的初始位置
food_pos = (random.randint(0, screen_width // 20) * 20, random.randint(0, screen_height // 20) * 20)
# 初始方向
direction = RIGHT
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != DOWN:
direction = UP
elif event.key == pygame.K_DOWN and direction != UP:
direction = DOWN
elif event.key == pygame.K_LEFT and direction != RIGHT:
direction = LEFT
elif event.key == pygame.K_RIGHT and direction != LEFT:
direction = RIGHT
# 移动蛇
new_head = (snake_pos[0][0], snake_pos[0][1])
if direction == UP:
new_head = (new_head[0], new_head[1] - 20)
elif direction == DOWN:
new_head = (new_head[0], new_head[1] + 20)
elif direction == LEFT:
new_head = (new_head[0] - 20, new_head[1])
elif direction == RIGHT:
new_head = (new_head[0] + 20, new_head[1])
# 判断是否吃到食物
if new_head == food_pos:
food_pos = (random.randint(0, screen_width // 20) * 20, random.randint(0, screen_height // 20) * 20)
snake_len += 1
else:
snake_pos.pop()
# 判断是否游戏结束
if new_head[0] < 0 or new_head[0] >= screen_width or new_head[1] < 0 or new_head[1] >= screen_height or new_head in snake_pos:
running = False
# 更新蛇的位置
snake_pos.insert(0, new_head)
# 绘制画面
screen.fill(black)
for pos in snake_pos:
pygame.draw.rect(screen, green, (pos[0], pos[1], 20, 20))
pygame.draw.rect(screen, red, (food_pos[0], food_pos[1], 20, 20))
pygame.display.update()
# 退出游戏
pygame.quit()
```
这个游戏存在一些问题,例如蛇碰到边界或者自己的身体就会游戏结束,不能够重新开始游戏等,可以根据需求进行修改和完善。