帮我写一个简单的贪吃蛇代码
时间: 2024-09-24 18:07:51 浏览: 37
unity实现简单贪吃蛇游戏
贪吃蛇是一个经典的电子游戏,下面是一个基本的Python实现,使用了pygame库:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口大小
screen_width = 400
screen_height = 400
game_window = pygame.display.set_mode((screen_width, screen_height))
# 定义颜色
snake_color = (0, 255, 0)
food_color = (255, 0, 0)
# 初始化蛇的位置和尺寸
snake_pos = [(screen_width // 2, screen_height // 2)]
snake_speed = 20
snake_length = 1
# 定义食物位置
food_pos = [random.randint(0, screen_width - 1), random.randint(0, screen_height - 1)]
# 游戏主循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# 移动蛇
new_head = snake_pos[-1]
head_x, head_y = new_head
dx, dy = (head_x + snake_speed, head_y) if head_x + snake_speed < screen_width else (-snake_speed, head_y)
snake_pos.insert(0, (dx, dy))
# 检查是否吃到食物
if food_pos == snake_pos[0]:
# 长大蛇身并生成新的食物
snake_length += 1
food_pos = [random.randint(0, screen_width - 1), random.randint(0, screen_height - 1)]
else:
# 如果蛇头超出边界或碰到自身身体,游戏结束
if not (0 <= head_x < screen_width and 0 <= head_y < screen_height) or snake_pos[0] in snake_pos[1:]:
pygame.quit()
quit()
# 绘制游戏界面
game_window.fill((0, 0, 0)) # 黑色背景
for pos in snake_pos:
pygame.draw.rect(game_window, snake_color, pygame.Rect(pos, (snake_speed, snake_speed)))
pygame.draw.rect(game_window, food_color, pygame.Rect(food_pos, (snake_speed, snake_speed)))
# 更新屏幕
pygame.display.update()
# 结束游戏
```
这个代码实现了蛇的基本移动、吃到食物增长和游戏结束的逻辑。玩家需要控制方向键让蛇前进,吃到食物才能增加长度。
阅读全文