import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏窗口设置
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Pygame 叶柯鑫贪吃蛇")
# 颜色定义
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
# 蛇身初始数据
snake_body = [(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)]
snake_direction = "RIGHT"
snake_speed = 10 # 移动步长(像素)
# 食物数据
food_position = (
random.randint(0, (WINDOW_WIDTH - 10) // 10) * 10,
random.randint(0, (WINDOW_HEIGHT - 10) // 10) * 10
)
# 得分与字体
score = 0
font = pygame.font.SysFont(None, 30)
# 时钟(控制帧率)
clock = pygame.time.Clock()
# 蛇移动函数
def move_snake():
global snake_body, snake_direction
head_x, head_y = snake_body[0]
# 根据方向更新蛇头坐标
if snake_direction == "UP":
new_head = (head_x, head_y - snake_speed)
elif snake_direction == "DOWN":
new_head = (head_x, head_y + snake_speed)
elif snake_direction == "LEFT":
new_head = (head_x - snake_speed, head_y)
else:
new_head = (head_x + snake_speed, head_y)
# 插入新蛇头
snake_body.insert(0, new_head)
# 检查是否吃到食物
global score, food_position
if new_head == food_position:
score += 10
# 重新生成食物
food_position = (
random.randint(0, (WINDOW_WIDTH - 10) // 10) * 10,
random.randint(0, (WINDOW_HEIGHT - 10) // 10) * 10
)
else:
# 未吃到食物,删除尾部保持长度
snake_body.pop()
# 碰撞检测函数
def check_collision():
head_x, head_y = snake_body[0]
# 边界碰撞
if (head_x < 0 or head_x >= WINDOW_WIDTH or
head_y < 0 or head_y >= WINDOW_HEIGHT):
return True
# 自身碰撞(蛇头与身体其他节)
for segment in snake_body[1:]:
if segment == (head_x, head_y):
return True
return False
# 绘制函数
def draw_objects():
screen.fill(BLACK)
# 绘制蛇身
for segment in snake_body:
pygame.draw.rect(screen, GREEN, (segment[0], segment[1], 10, 10))
# 绘制食物
pygame.draw.circle(screen, RED, (food_position[0] + 5, food_position[1] + 5), 5)
# 绘制得分
score_text = font.render(f"得分: {score}", True, WHITE)
screen.blit(score_text, (10, 10))
pygame.display.update()
# 主循环
game_over = False
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
# 方向控制(防止反向)
if event.key == pygame.K_UP and snake_direction != "DOWN":
snake_direction = "UP"
elif event.key == pygame.K_DOWN and snake_direction != "UP":
snake_direction = "DOWN"
elif event.key == pygame.K_LEFT and snake_direction != "RIGHT":
snake_direction = "LEFT"
elif event.key == pygame.K_RIGHT and snake_direction != "LEFT":
snake_direction = "RIGHT"
# 移动蛇
move_snake()
# 检测碰撞
if check_collision():
game_over = True
# 绘制画面
draw_objects()
# 控制帧率(每秒 10 帧,可调整速度)
clock.tick(10)
# 游戏结束提示
font_large = pygame.font.SysFont(None, 50)
game_over_text = font_large.render("游戏结束", True, RED)
screen.blit(game_over_text, (WINDOW_WIDTH // 2 - 100, WINDOW_HEIGHT // 2 - 25))
pygame.display.update()
pygame.time.wait(3000)
# 退出 Pygame
pygame.quit()
![]()