下面是一个简单的Python贪吃蛇游戏的代码示例:
import pygame
import random
# 游戏窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# 蛇身尺寸
SNAKE_SIZE = 20
# 初始化pygame
pygame.init()
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
# 蛇头初始位置
snake_x = WINDOW_WIDTH // 2
snake_y = WINDOW_HEIGHT // 2
# 蛇身初始长度
snake_length = 1
snake_body = [[snake_x, snake_y]]
# 食物初始位置
food_x = random.randint(0, (WINDOW_WIDTH - SNAKE_SIZE) // SNAKE_SIZE) * SNAKE_SIZE
food_y = random.randint(0, (WINDOW_HEIGHT - SNAKE_SIZE) // SNAKE_SIZE) * SNAKE_SIZE
# 设置游戏时钟
clock = pygame.time.Clock()
# 游戏结束标志
game_over = False
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 获取按键输入
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
snake_y -= SNAKE_SIZE
elif keys[pygame.K_DOWN]:
snake_y += SNAKE_SIZE
elif keys[pygame.K_LEFT]:
snake_x -= SNAKE_SIZE
elif keys[pygame.K_RIGHT]:
snake_x += SNAKE_SIZE
# 判断是否吃到食物
if snake_x == food_x and snake_y == food_y:
snake_length += 1
food_x = random.randint(0, (WINDOW_WIDTH - SNAKE_SIZE) // SNAKE_SIZE) * SNAKE_SIZE
food_y = random.randint(0, (WINDOW_HEIGHT - SNAKE_SIZE) // SNAKE_SIZE) * SNAKE_SIZE
# 更新蛇身
snake_body.append([snake_x, snake_y])
if len(snake_body) > snake_length:
del snake_body[0]
# 判断游戏是否结束
if snake_x < 0 or snake_x >= WINDOW_WIDTH or snake_y < 0 or snake_y >= WINDOW_HEIGHT or [snake_x, snake_y] in snake_body[:-1]:
game_over = True
# 渲染游戏界面
window.fill((0, 0, 0))
for body_part in snake_body:
pygame.draw.rect(window, (0, 255, 0), (body_part[0], body_part[1], SNAKE_SIZE, SNAKE_SIZE))
pygame.draw.rect(window, (255, 0, 0), (food_x, food_y, SNAKE_SIZE, SNAKE_SIZE))
pygame.display.update()
# 控制游戏更新频率
clock.tick(10)
# 退出游戏
pygame.quit()
这只是一个简单的贪吃蛇游戏代码示例,你可以根据自己的需求进行修改和扩展。