[Python] 纯文本查看 复制代码
import pygame
import sys
import random
# 初始化pygame
pygame.init()
# 游戏常量
WIDTH, HEIGHT = 800, 600
GRID_SIZE = 20
GRID_WIDTH = WIDTH // GRID_SIZE
GRID_HEIGHT = HEIGHT // GRID_SIZE
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 方向常量
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
# 设置窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
# 时钟控制游戏速度
clock = pygame.time.Clock()
FPS = 10
class Snake:
def __init__(self):
# 初始化蛇的位置和方向
self.positions = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]
self.direction = RIGHT
self.next_direction = RIGHT
self.grow = False
def update(self):
# 更新蛇的方向
self.direction = self.next_direction
# 获取蛇头位置
head_x, head_y = self.positions[0]
# 计算新蛇头位置
dx, dy = self.direction
new_head = ((head_x + dx) % GRID_WIDTH, (head_y + dy) % GRID_HEIGHT)
# 在头部添加新位置
self.positions.insert(0, new_head)
# 如果没有吃到食物,移除尾部
if not self.grow:
self.positions.pop()
else:
self.grow = False
def change_direction(self, new_direction):
# 确保蛇不能直接反向移动
dx, dy = new_direction
current_dx, current_dy = self.direction
if (dx * -1, dy * -1) != self.direction:
self.next_direction = new_direction
def draw(self, surface):
# 绘制蛇的身体
for position in self.positions:
rect = pygame.Rect((position[0] * GRID_SIZE, position[1] * GRID_SIZE),
(GRID_SIZE, GRID_SIZE))
pygame.draw.rect(surface, GREEN, rect)
pygame.draw.rect(surface, BLACK, rect, 1)
# 绘制蛇头(不同颜色以区分)
head_rect = pygame.Rect((self.positions[0][0] * GRID_SIZE, self.positions[0][1] * GRID_SIZE),
(GRID_SIZE, GRID_SIZE))
pygame.draw.rect(surface, BLUE, head_rect)
pygame.draw.rect(surface, BLACK, head_rect, 1)
def check_collision(self):
# 检查是否撞到自己
head = self.positions[0]
return head in self.positions[1:]
class Food:
def __init__(self):
self.position = (0, 0)
self.randomize_position()
def randomize_position(self):
# 随机生成食物位置
self.position = (random.randint(0, GRID_WIDTH - 1),
random.randint(0, GRID_HEIGHT - 1))
def draw(self, surface):
# 绘制食物
rect = pygame.Rect((self.position[0] * GRID_SIZE, self.position[1] * GRID_SIZE),
(GRID_SIZE, GRID_SIZE))
pygame.draw.rect(surface, RED, rect)
pygame.draw.rect(surface, BLACK, rect, 1)
def main():
# 初始化游戏对象
snake = Snake()
food = Food()
score = 0
# 游戏主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
# 处理方向键控制
if event.key == pygame.K_UP:
snake.change_direction(UP)
elif event.key == pygame.K_DOWN:
snake.change_direction(DOWN)
elif event.key == pygame.K_LEFT:
snake.change_direction(LEFT)
elif event.key == pygame.K_RIGHT:
snake.change_direction(RIGHT)
elif event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
# 更新蛇的位置
snake.update()