import pygame
import random
# 初始化Pygame
pygame.init()
# 游戏窗口设置
WIDTH, HEIGHT = 800, 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 蛇和食物的初始设置
SNAKE_SIZE = 20
snake = [(WIDTH//2, HEIGHT//2)]
snake_direction = (0, 0)
food = (random.randint(0, (WIDTH-SNAKE_SIZE)//SNAKE_SIZE)*SNAKE_SIZE,
random.randint(0, (HEIGHT-SNAKE_SIZE)//SNAKE_SIZE)*SNAKE_SIZE)
# 游戏主循环
clock = pygame.time.Clock()
running = True
game_over = False
while running:
clock.tick(30) # 控制游戏速度(每秒帧数)
# 处理事件(如按键)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN and not game_over:
if event.key == pygame.K_UP and snake_direction != (0, SNAKE_SIZE):
snake_direction = (0, -SNAKE_SIZE)
elif event.key == pygame.K_DOWN and snake_direction != (0, -SNAKE_SIZE):
snake_direction = (0, SNAKE_SIZE)
elif event.key == pygame.K_LEFT and snake_direction != (SNAKE_SIZE, 0):
snake_direction = (-SNAKE_SIZE, 0)
elif event.key == pygame.K_RIGHT and snake_direction != (-SNAKE_SIZE, 0):
snake_direction = (SNAKE_SIZE, 0)
if not game_over:
# 移动蛇头
new_head = (snake + snake_direction, snake + snake_direction)
snake.insert(0, new_head)
# 检测是否吃到食物
if snake == food:
food = (random.randint(0, (WIDTH-SNAKE_SIZE)//SNAKE_SIZE)*SNAKE_SIZE,
random.randint(0, (HEIGHT-SNAKE_SIZE)//SNAKE_SIZE)*SNAKE_SIZE)
else:
snake.pop()
# 碰撞检测
if (snake < 0 or snake >= WIDTH or
snake < 0 or snake >= HEIGHT or
snake in snake[1:]):
game_over = True
# 绘制画面
WIN.fill(BLACK)
# 绘制食物
pygame.draw.rect(WIN, RED, (food, food, SNAKE_SIZE, SNAKE_SIZE))
# 绘制蛇
for segment in snake:
pygame.draw.rect(WIN, GREEN, (segment, segment, SNAKE_SIZE, SNAKE_SIZE))
# 显示游戏结束提示
if game_over:
font = pygame.font.SysFont("arial", 50)
text = font.render("游戏结束!按R重新开始", True, WHITE)
WIN.blit(text, (WIDTH//2 - text.get_width()//2, HEIGHT//2 - text.get_height()//2))
keys = pygame.key.get_pressed()
if keys[pygame.K_r]:
snake = [(WIDTH//2, HEIGHT//2)]
snake_direction = (0, 0)
food = (random.randint(0, (WIDTH-SNAKE_SIZE)//SNAKE_SIZE)*S