使用方向键 ↑↓←→ 控制移动
# -*- coding: utf-8 -*-
import pygame
import random
pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("贪吃蛇")
# 初始化蛇和食物
snake = [(300, 200), (290, 200), (280, 200)]
direction = 'RIGHT'
food = (random.randint(0, 58)*10, random.randint(0, 38)*10)
score = 0
# 游戏主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != 'DOWN':
direction = 'UP'
# ... 其他方向键处理
# 移动蛇
head = snake[0]
if direction == 'RIGHT': new_head = (head[0]+10, head[1])
elif direction == 'LEFT': new_head = (head[0]-10, head[1])
# ... 上下移动
snake.insert(0, new_head)
# 吃食物
if new_head == food:
score += 1
food = (random.randint(0, 58)*10, random.randint(0, 38)*10)
else:
snake.pop()
# 碰撞检测
if (new_head[0] < 0 or new_head[0] >= 600 or
new_head[1] < 0 or new_head[1] >= 400 or
new_head in snake[1:]):
print(f"游戏结束! 最终得分: {score}")
break
pygame.display.update()
pygame.time.delay(100)
pygame.quit()
pip install pygamepython snake.py