用Python编写一个贪吃蛇游戏的系统
时间: 2024-12-27 18:30:43 浏览: 0
好的,下面是一个简单的Python贪吃蛇游戏的基本框架。我们将使用`pygame`库来创建图形界面。首先,需要安装`pygame`,可以使用pip进行安装:`pip install pygame`
```python
# 导入所需库
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小
screen_width = 600
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# 定义贪吃蛇的初始位置和尺寸
snake_pos = [(100, 100), (90, 100), (80, 100)]
snake_speed = 15
snake_direction = [0, 1] # 向下移动
# 定义食物的位置
food_pos = [random.randint(0, screen_width - 10), random.randint(0, screen_height - 10)]
# 游戏主循环
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 snake_direction != [0, -1]:
snake_direction = [-1, 0]
elif event.key == pygame.K_DOWN and snake_direction != [0, 1]:
snake_direction = [1, 0]
elif event.key == pygame.K_LEFT and snake_direction != [1, 0]:
snake_direction = [0, -1]
elif event.key == pygame.K_RIGHT and snake_direction != [-1, 0]:
snake_direction = [0, 1]
# 更新蛇的位置
new_head = [snake_pos[0][0] + snake_direction[0] * snake_speed,
snake_pos[0][1] + snake_direction[1] * snake_speed]
snake_pos.insert(0, new_head)
# 检查蛇头是否碰到了边界或自身
if snake_pos[0] in [(0, pos[1]) for pos in snake_pos[1:]] or \
snake_pos[0] in [(pos[0], screen_height) for pos in snake_pos[1:]]:
running = False
elif snake_pos[0] == food_pos:
# 食物位置更新为蛇头部之外的一个随机位置
food_pos = [random.randint(0, screen_width - 10), random.randint(0, screen_height - 10)]
# 增加蛇身长度
snake_pos.append(snake_pos[0])
# 绘制游戏元素
screen.fill(BLACK)
for pos in snake_pos:
pygame.draw.rect(screen, WHITE, pygame.Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(screen, RED, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
# 更新屏幕显示
pygame.display.flip()
# 游戏结束,关闭窗口
pygame.quit()
```
阅读全文