import pygame
import random
import sys
import os

# 解决字体初始化报错前置配置
os.environ['PYGAME_FREETYPE'] = '0'
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)
BLUE = (0, 0, 255)

# 蛇方块大小、速度
BLOCK_SIZE = 20
speed = 10

# 修复字体报错：不用SysFont(None)，改用默认渲染字体
try:
    font_score = pygame.font.Font(pygame.font.get_default_font(), 35)
    font_gameover = pygame.font.Font(pygame.font.get_default_font(), 60)
except:
    # 兜底极简文字绘制
    font_score = pygame.font.SysFont("simhei", 35, bold=True)
    font_gameover = pygame.font.SysFont("simhei", 60, bold=True)

# 绘制文字函数
def draw_text(text, color, x, y, font):
    text_surface = font.render(text, True, color)
    screen.blit(text_surface, (x, y))

# 游戏主逻辑
def game_loop():
    global speed
    game_over = False
    game_close = False

    # 蛇初始坐标
    x, y = WIDTH / 2, HEIGHT / 2
    x_change, y_change = 0, 0

    # 蛇身体列表
    snake_body = []
    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)
            draw_text("游戏结束！", RED, 160, 120, font_gameover)
            draw_text("按Q退出，按C重新开始", WHITE, 120, 200, font_score)
            draw_text(f"当前得分：{snake_length - 1}", GREEN, 200, 260, font_score)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:  # Q退出
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:  # 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 != BLOCK_SIZE:
                    x_change = -BLOCK_SIZE
                    y_change = 0
                elif event.key == pygame.K_RIGHT and x_change != -BLOCK_SIZE:
                    x_change = BLOCK_SIZE
                    y_change = 0
                elif event.key == pygame.K_UP and y_change != BLOCK_SIZE:
                    y_change = -BLOCK_SIZE
                    x_change = 0
                elif event.key == pygame.K_DOWN and y_change != -BLOCK_SIZE:
                    y_change = BLOCK_SIZE
                    x_change = 0

        # 撞墙判定
        if x < 0 or x >= WIDTH or y < 0 or y >= HEIGHT:
            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 = [x, y]
        snake_body.append(snake_head)

        # 控制身体长度，多余的删掉
        if len(snake_body) > snake_length:
            del snake_body[0]

        # 撞到自己身体判定
        for seg in snake_body[:-1]:
            if seg == snake_head:
                game_close = True

        # 绘制整条蛇
        for seg in snake_body:
            pygame.draw.rect(screen, GREEN, [seg[0], seg[1], BLOCK_SIZE, BLOCK_SIZE])
            # 白色描边更好看
            pygame.draw.rect(screen, WHITE, [seg[0], seg[1], BLOCK_SIZE, BLOCK_SIZE], 1)

        # 显示分数
        draw_text(f"得分：{snake_length - 1}", WHITE, 10, 10, font_score)
        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
            # 每吃5分加速
            if snake_length % 5 == 0:
                speed += 0.8

        clock.tick(speed)

    pygame.quit()
    sys.exit()

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