用python帮我写一个贪吃蛇游戏
时间: 2023-07-04 21:22:57 浏览: 98
Python编写一个贪吃蛇游戏
好的,以下是一个简单的贪吃蛇游戏的Python代码,使用了Pygame库来实现图形化界面:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 游戏窗口大小
win_width = 500
win_height = 500
# 颜色定义
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
# 创建窗口
win = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("贪吃蛇游戏")
# 贪吃蛇头部
snake_head = pygame.Surface((10, 10))
snake_head.fill(green)
# 食物
food = pygame.Surface((10, 10))
food.fill(red)
# 初始位置
snake_pos = [(win_width / 2, win_height / 2)]
food_pos = (random.randint(0, win_width / 10 - 1) * 10, random.randint(0, win_height / 10 - 1) * 10)
# 贪吃蛇移动方向
direction = "right"
# 游戏主循环
while True:
# 处理退出事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# 检测按键事件
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and direction != "right":
direction = "left"
elif keys[pygame.K_RIGHT] and direction != "left":
direction = "right"
elif keys[pygame.K_UP] and direction != "down":
direction = "up"
elif keys[pygame.K_DOWN] and direction != "up":
direction = "down"
# 移动贪吃蛇
if direction == "left":
x = snake_pos[0][0] - 10
y = snake_pos[0][1]
elif direction == "right":
x = snake_pos[0][0] + 10
y = snake_pos[0][1]
elif direction == "up":
x = snake_pos[0][0]
y = snake_pos[0][1] - 10
elif direction == "down":
x = snake_pos[0][0]
y = snake_pos[0][1] + 10
# 判断是否撞墙
if x < 0 or x > win_width - 10 or y < 0 or y > win_height - 10:
pygame.quit()
quit()
# 判断是否吃到食物
if (x, y) == food_pos:
snake_pos.append((x, y))
food_pos = (random.randint(0, win_width / 10 - 1) * 10, random.randint(0, win_height / 10 - 1) * 10)
else:
snake_pos.insert(0, (x, y))
snake_pos.pop()
# 绘制游戏界面
win.fill(black)
win.blit(food, food_pos)
for pos in snake_pos:
win.blit(snake_head, pos)
pygame.display.update()
# 帧率控制
pygame.time.Clock().tick(15)
```
运行代码后,即可开始游戏。使用方向键控制贪吃蛇的移动方向,吃到食物后贪吃蛇会变长。如果贪吃蛇撞墙或撞到自己,游戏结束。
阅读全文