import pygame
import random
import sys

# 初始化 pygame
pygame.init()

# 游戏基础设置
WIDTH, HEIGHT = 600, 400
screen = 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)

# 蛇的单位大小 & 速度
BLOCK_SIZE = 20
SPEED = 10

# 时钟（控制帧率）
clock = pygame.time.Clock()

# 字体（显示分数）
font = pygame.font.SysFont(None, 40)

def show_score(score):
    """显示当前分数"""
    text = font.render(f"分数: {score}", True, WHITE)
    screen.blit(text, [0, 0])

def draw_snake(block_size, snake_list):
    """绘制蛇身"""
    for x_y in snake_list:
        pygame.draw.rect(screen, GREEN, [x_y[0], x_y[1], block_size, block_size])

def game_loop():
    """游戏主循环"""
    game_over = False
    game_close = False

    # 蛇初始位置
    x = WIDTH / 2
    y = HEIGHT / 2

    # 蛇移动变化量
    x_change = 0
    y_change = 0

    # 蛇身体列表
    snake_list = []
    snake_length = 1

    # 食物随机位置
    food_x = round(random.randrange(0, WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
    food_y = round(random.randrange(0, HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE

    while not game_over:
        # 游戏失败界面
        while game_close:
            screen.fill(BLACK)
            game_over_text = font.render("游戏结束！按 Q 退出，按 C 重新开始", True, RED)
            screen.blit(game_over_text, [30, HEIGHT/3])
            show_score(snake_length - 1)
            pygame.display.update()

            # 失败后按键处理
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        game_loop()
                if event.type == pygame.QUIT:
                    game_over = True
                    game_close = False

        # 按键控制方向
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT and x_change == 0:
                    x_change = -BLOCK_SIZE
                    y_change = 0
                elif event.key == pygame.K_RIGHT and x_change == 0:
                    x_change = BLOCK_SIZE
                    y_change = 0
                elif event.key == pygame.K_UP and y_change == 0:
                    y_change = -BLOCK_SIZE
                    x_change = 0
                elif event.key == pygame.K_DOWN and y_change == 0:
                    y_change = BLOCK_SIZE
                    x_change = 0

        # 撞墙判断
        if x >= WIDTH or x < 0 or y >= HEIGHT or y < 0:
            game_close = True

        # 更新蛇头位置
        x += x_change
        y += y_change
        screen.fill(BLACK)

        # 绘制食物
        pygame.draw.rect(screen, RED, [food_x, food_y, BLOCK_SIZE, BLOCK_SIZE])

        # 更新蛇身体
        snake_head = []
        snake_head.append(x)
        snake_head.append(y)
        snake_list.append(snake_head)

        # 保持蛇长度
        if len(snake_list) > snake_length:
            del snake_list[0]

        # 撞到自己
        for segment in snake_list[:-1]:
            if segment == snake_head:
                game_close = True

        # 绘制蛇
        draw_snake(BLOCK_SIZE, snake_list)
        show_score(snake_length - 1)

        pygame.display.update()

        # 吃到食物
        if x == food_x and y == food_y:
            food_x = round(random.randrange(0, WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
            food_y = round(random.randrange(0, HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
            snake_length += 1

        clock.tick(SPEED)

    pygame.quit()
    sys.exit()

# 启动游戏
if __name__ == "__main__":
    game_loop()