import pygame
import random
import os

# 初始化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

# ========== 修复字体部分，不再用SysFont(None,35) ==========
try:
    # 优先使用pygame自带字体
    font = pygame.font.Font(pygame.font.get_default_font(), 35)
except Exception:
    # 兜底方案
    font = pygame.font.Font(None, 35)


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


def draw_snake(block_size, snake_list):
    for pos in snake_list:
        pygame.draw.rect(screen, GREEN, [pos[0], pos[1], block_size, block_size])


def show_message(msg, color):
    mesg = font.render(msg, True, color)
    screen.blit(mesg, [WIDTH / 6, HEIGHT / 3])


def game_loop():
    game_over = False
    game_close = False

    # 蛇初始坐标
    x1 = WIDTH / 2
    y1 = HEIGHT / 2

    x1_change = 0
    y1_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

    clock = pygame.time.Clock()

    while not game_over:
        # 游戏结束弹窗界面
        while game_close:
            screen.fill(BLACK)
            show_message("游戏结束！Q退出 | C重新开始", RED)
            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 x1_change != BLOCK_SIZE:
                    x1_change = -BLOCK_SIZE
                    y1_change = 0
                elif event.key == pygame.K_RIGHT and x1_change != -BLOCK_SIZE:
                    x1_change = BLOCK_SIZE
                    y1_change = 0
                elif event.key == pygame.K_UP and y1_change != BLOCK_SIZE:
                    y1_change = -BLOCK_SIZE
                    x1_change = 0
                elif event.key == pygame.K_DOWN and y1_change != -BLOCK_SIZE:
                    y1_change = BLOCK_SIZE
                    x1_change = 0

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

        x1 += x1_change
        y1 += y1_change
        screen.fill(BLACK)

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

        snake_head = [x1, y1]
        snake_list.append(snake_head)

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

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

        draw_snake(BLOCK_SIZE, snake_list)
        show_score(snake_length - 1)

        pygame.display.update()

        # 吃到食物
        if x1 == food_x and y1 == 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()
    quit()


if __name__ == "__main__":
    game_loop()
