Python贪吃蛇小游戏代码
时间: 2024-08-02 09:00:39 浏览: 52
Python编写贪吃蛇小游戏的代码通常会包含基本的游戏结构、角色移动、食物生成以及碰撞检测等功能。这是一个简化的例子,不涉及复杂的图形库,仅用内置模块`pygame`和一些基本控制:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小
screen_width = 800
screen_height = 600
win = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇")
snake_speed = 15
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
# 初始化蛇的位置和方向
snake_pos = [(screen_width // 2, screen_height // 2), (screen_width // 2 - 10, screen_height // 2)]
snake_dir = [0, 1] # 向上
food_pos = None
food_spawned = False
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_dir != [0, -1]:
snake_dir = [-1, 0]
elif event.key == pygame.K_DOWN and snake_dir != [0, 1]:
snake_dir = [1, 0]
elif event.key == pygame.K_LEFT and snake_dir != [1, 0]:
snake_dir = [0, -1]
elif event.key == pygame.K_RIGHT and snake_dir != [-1, 0]:
snake_dir = [0, 1]
# 移动蛇
head = snake_pos
head += snake_dir * snake_speed
head += snake_dir * snake_speed
snake_pos.insert(0, head)
# 检查是否吃到食物
if not food_spawned:
food_pos = [random.randint(0, screen_width - 10), random.randint(0, screen_height - 10)]
food_spawned = True
else:
if head == food_pos:
food_pos = [random.randint(0, screen_width - 10), random.randint(0, screen_height - 10)]
snake_pos.append(snake_pos[-1]) # 增加新节点
del snake_pos[-2] # 删除尾巴
# 碰撞检测
if head in snake_pos[:-1] or head < 0 or head >= screen_width or head < 0 or head >= screen_height:
running = False
# 绘制游戏元素
win.fill(black)
for pos in snake_pos:
pygame.draw.rect(win, white, [pos, pos, 10, 10])
if food_spawned:
pygame.draw.rect(win, red, [food_pos, food_pos, 10, 10])
pygame.display.update()
# 清理并退出
pygame.quit()
```
相关问题--
1. 贪吃蛇游戏中如何处理玩家的输入?
2. 如何在游戏中实现蛇的移动和边界检测?
3. 如何创建和管理游戏中的食物?
阅读全文