import pygame
import time
import random
import sys
import os

# --- 初始化 ---
pygame.init()

# --- 颜色定义 ---
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (213, 50, 80)
GREEN = (0, 255, 0)
DARK_GREEN = (0, 200, 0)
BLUE = (50, 153, 213)
GRAY = (200, 200, 200)

# --- 屏幕设置 ---
DIS_WIDTH = 600
DIS_HEIGHT = 400
dis = pygame.display.set_mode((DIS_WIDTH, DIS_HEIGHT))
pygame.display.set_caption('Python 贪吃蛇 - 中文版')

clock = pygame.time.Clock()

# --- 蛇的参数 ---
SNAKE_BLOCK = 10
INITIAL_SPEED = 15

# --- 🇨🇳 中文字体设置 (关键步骤) ---
# 尝试加载常见的中文字体，确保跨平台兼容
def get_chinese_font(size):
    font_names = [
        'microsoftyahei',  # Windows: 微软雅黑
        'SimHei',          # Windows: 黑体
        'PingFang SC',     # Mac: 苹方
        'Heiti SC',        # Mac: 黑体-简
        'WenQuanYiMicroHei', # Linux: 文泉驿微米黑
        'Arial Unicode MS' # 备用
    ]
    
    for name in font_names:
        try:
            # 检查系统是否有该字体
            if name in pygame.font.get_fonts() or name in [f[0] for f in pygame.font.get_fonts()]:
                 return pygame.font.SysFont(name, size)
            # 尝试直接加载（有些系统不需要先在get_fonts里）
            font = pygame.font.SysFont(name, size)
            # 简单测试渲染一个中文字，看是否成功（防止返回空字体对象导致报错）
            test_surf = font.render("测", True, BLACK)
            if test_surf.get_width() > 0:
                return font
        except:
            continue
    
    # 如果以上都失败，回退到默认字体（可能无法显示中文，但程序不会崩）
    print("警告：未找到合适的中文字体，中文可能显示为方框。")
    return pygame.font.SysFont(None, size)

font_style = get_chinese_font(25)
score_font = get_chinese_font(35)
game_over_font = get_chinese_font(50)

def your_score(score):
    value = score_font.render("得分: " + str(score), True, BLACK)
    dis.blit(value, [10, 10])

def our_snake(snake_block, snake_list):
    for i, x in enumerate(snake_list):
        color = DARK_GREEN if i == len(snake_list) - 1 else GREEN
        pygame.draw.rect(dis, color, [x[0], x[1], snake_block, snake_block])

def message(msg, color, y_offset=0, font=None):
    if font is None:
        font = font_style
    mesg = font.render(msg, True, color)
    text_rect = mesg.get_rect(center=(DIS_WIDTH/2, DIS_HEIGHT/2 + y_offset))
    dis.blit(mesg, text_rect)

def gameLoop():
    game_over = False
    game_close = False

    x1 = DIS_WIDTH / 2
    y1 = DIS_HEIGHT / 2

    x1_change = 0
    y1_change = 0

    snake_List = []
    Length_of_snake = 1

    foodx = round(random.randrange(0, DIS_WIDTH - SNAKE_BLOCK) / 10.0) * 10.0
    foody = round(random.randrange(0, DIS_HEIGHT - SNAKE_BLOCK) / 10.0) * 10.0

    current_speed = INITIAL_SPEED

    while not game_over:

        while game_close == True:
            dis.fill(WHITE)
            # 显示中文大字
            message("游戏结束!", RED, -50, game_over_font)
            # 显示中文提示
            message("按 Q 退出 或 按 C 重玩", BLACK, 10)
            your_score(Length_of_snake - 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:
                        gameLoop()

        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 == 0:
                    x1_change = -SNAKE_BLOCK
                    y1_change = 0
                elif event.key == pygame.K_RIGHT and x1_change == 0:
                    x1_change = SNAKE_BLOCK
                    y1_change = 0
                elif event.key == pygame.K_UP and y1_change == 0:
                    y1_change = -SNAKE_BLOCK
                    x1_change = 0
                elif event.key == pygame.K_DOWN and y1_change == 0:
                    y1_change = SNAKE_BLOCK
                    x1_change = 0

        if x1 >= DIS_WIDTH or x1 < 0 or y1 >= DIS_HEIGHT or y1 < 0:
            game_close = True
        
        x1 += x1_change
        y1 += y1_change
        dis.fill(WHITE)
        
        pygame.draw.rect(dis, RED, [foodx, foody, SNAKE_BLOCK, SNAKE_BLOCK])
        
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        our_snake(SNAKE_BLOCK, snake_List)
        your_score(Length_of_snake - 1)

        pygame.display.update()

        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, DIS_WIDTH - SNAKE_BLOCK) / 10.0) * 10.0
            foody = round(random.randrange(0, DIS_HEIGHT - SNAKE_BLOCK) / 10.0) * 10.0
            Length_of_snake += 1
            current_speed += 0.5

        clock.tick(current_speed)

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    try:
        gameLoop()
    except Exception as e:
        print(f"发生错误: {e}")
        print("提示：如果是字体问题，请确保你的系统安装了中文字体（如微软雅黑）。")