贪吃蛇游戏
# 贪吃蛇游戏
import pygame, random
# 初始化游戏
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((800, 600))
# 设置游戏窗口标题
pygame.display.set_caption("贪吃蛇游戏")
# 设置游戏背景颜色
screen.fill((0, 0, 0))
# 设置游戏速度
speed = 5
# 设置贪吃蛇颜色
snake_color = (255, 255, 255)
# 设置食物颜色
food_color = (255, 0, 0)
# 设置障碍物颜色
obstacle_color = (255, 255, 255)
# 设置游戏字体
font = pygame.font.Font("simhei.ttf", 24)
# 定义贪吃蛇的移动方向
# 0 - 向上
# 1 - 向下
# 2 - 向左
# 3 - 向右
direction = 0
# 定义贪吃蛇的身体列表
snake_body = [[200, 200], [210, 200], [220, 200]]
# 定义障碍物列表
obstacles = []
# 定义游戏分数
score = 0
# 定义游戏结束标志
game_over = False
# 生成障碍物
for i in range(20):
obstacles.append([random.randint(0, 800), random.randint(0, 600)])
# 生成食物
food = [random.randint(0, 800), random.randint(0, 600)]
# 游戏主循环
while not game_over:
# 检查事件
for event in pygame.event.get():
# 检查是否退出游戏
if event.type == pygame.QUIT:
game_over = True
# 检查键盘事件
if event.type == pygame.KEYDOWN:
# 检查是否按下上下左右键
if event.key == pygame.K_UP and direction != 1:
direction = 0
elif event