import pygame
import sys
import random

# ---------- 初始化 ----------
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("🎿 滑雪模拟器")

# 颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED   = (255, 0, 0)
GREEN = (0, 200, 0)
BLUE  = (50, 150, 255)
BROWN = (139, 69, 19)
SNOW  = (240, 248, 255)
GRAY  = (100, 100, 100)
DARK_GRAY = (60, 60, 60)

clock = pygame.time.Clock()
FPS = 60

# ---------- 智能中文字体加载 ----------
def get_font(size, bold=False):
    """尝试加载系统中文字体，失败则返回默认字体"""
    # 常见中文字体名称（按优先级排序）
    font_names = [
        "SimHei",           # 黑体 (Windows)
        "Microsoft YaHei",  # 微软雅黑 (Windows)
        "SimSun",           # 宋体 (Windows)
        "FangSong",         # 仿宋 (Windows)
        "KaiTi",            # 楷体 (Windows)
        "STHeiti",          # 华文黑体 (macOS)
        "STKaiti",          # 华文楷体 (macOS)
        "Arial Unicode MS", # 通用 Unicode 字体
    ]
    for name in font_names:
        try:
            font = pygame.font.SysFont(name, size, bold=bold)
            # 测试是否能渲染中文字符
            test_surf = font.render("测试", True, BLACK)
            # 如果渲染成功（宽度>0），则返回该字体
            if test_surf.get_width() > 0:
                return font
        except:
            continue
    # 全部失败则使用默认字体（可能无法显示中文）
    return pygame.font.Font(None, size)

# 预定义字体对象
font_large = get_font(52)
font_medium = get_font(36)
font_small = get_font(28)
font_tiny = get_font(22)

# ---------- 辅助函数：显示文本 ----------
def draw_text(surface, text, font, color, x, y, center=True):
    text_surf = font.render(text, True, color)
    rect = text_surf.get_rect()
    if center:
        rect.center = (x, y)
    else:
        rect.topleft = (x, y)
    surface.blit(text_surf, rect)

# ---------- 游戏对象 ----------
class Player:
    def __init__(self, speed):
        self.width = 40
        self.height = 60
        self.x = WIDTH // 2 - self.width // 2
        self.y = HEIGHT - 150
        self.speed = speed
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)

    def move(self, direction):
        self.x += direction * self.speed
        if self.x < 0:
            self.x = 0
        elif self.x > WIDTH - self.width:
            self.x = WIDTH - self.width
        self.rect.x = self.x

    def draw(self, surface):
        pygame.draw.rect(surface, BLUE, (self.x+5, self.y+15, 30, 30))
        pygame.draw.circle(surface, (255, 200, 150), (self.x+20, self.y+10), 15)
        pygame.draw.polygon(surface, RED, [(self.x+8, self.y-5), (self.x+32, self.y-5), (self.x+20, self.y-20)])
        pygame.draw.line(surface, BLACK, (self.x+2, self.y+30), (self.x-10, self.y+50), 3)
        pygame.draw.line(surface, BLACK, (self.x+38, self.y+30), (self.x+50, self.y+50), 3)
        pygame.draw.rect(surface, BROWN, (self.x-5, self.y+50, 20, 8))
        pygame.draw.rect(surface, BROWN, (self.x+25, self.y+50, 20, 8))

class Obstacle:
    def __init__(self, speed_range):
        self.width = 30
        self.height = 40
        self.x = random.randint(0, WIDTH - self.width)
        self.y = -self.height
        self.speed = random.randint(*speed_range)
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)

    def update(self):
        self.y += self.speed
        self.rect.y = self.y

    def draw(self, surface):
        pygame.draw.polygon(surface, GREEN, [(self.x+15, self.y), (self.x, self.y+30), (self.x+30, self.y+30)])
        pygame.draw.rect(surface, BROWN, (self.x+12, self.y+30, 6, 10))

    def off_screen(self):
        return self.y > HEIGHT

# ---------- 游戏主循环 ----------
def game_loop(difficulty):
    if difficulty == "简单":
        player_speed = 5
        obstacle_speed_range = (3, 6)
        spawn_interval = (1.0, 1.8)
        score_multiplier = 1
        label = "简单"
    elif difficulty == "普通":
        player_speed = 6
        obstacle_speed_range = (4, 8)
        spawn_interval = (0.6, 1.2)
        score_multiplier = 2
        label = "普通"
    else:  # 困难
        player_speed = 7
        obstacle_speed_range = (10, 10)
        spawn_interval = (0.3, 0.8)
        score_multiplier = 10
        label = "困难"

    player = Player(player_speed)
    obstacles = []
    score = 0
    running = True
    game_over = False
    spawn_timer = 0

    while running:
        dt = clock.tick(FPS) / 1000.0

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r and game_over:
                    return game_loop(difficulty)
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                if event.key == pygame.K_m and game_over:
                    return main_menu()

        keys = pygame.key.get_pressed()
        if not game_over:
            if keys[pygame.K_LEFT] or keys[pygame.K_a]:
                player.move(-1)
            if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
                player.move(1)

            spawn_timer += dt
            if spawn_timer > random.uniform(*spawn_interval):
                obstacles.append(Obstacle(obstacle_speed_range))
                spawn_timer = 0

            for obs in obstacles[:]:
                obs.update()
                if obs.off_screen():
                    obstacles.remove(obs)
                    score += 1 * score_multiplier

            for obs in obstacles:
                if player.rect.colliderect(obs.rect):
                    game_over = True
                    break

        # ---- 绘制 ----
        screen.fill(SNOW)
        for i in range(0, WIDTH, 30):
            pygame.draw.line(screen, (200, 220, 240), (i, 0), (i, HEIGHT), 1)

        player.draw(screen)
        for obs in obstacles:
            obs.draw(screen)

        draw_text(screen, f"难度: {label}", font_small, DARK_GRAY, 10, 10, center=False)
        draw_text(screen, f"得分: {score}", font_medium, BLACK, 70, 40, center=False)

        if game_over:
            overlay = pygame.Surface((WIDTH, HEIGHT))
            overlay.set_alpha(150)
            overlay.fill(BLACK)
            screen.blit(overlay, (0, 0))
            draw_text(screen, "💥 游戏结束", font_large, RED, WIDTH//2, HEIGHT//2 - 80)
            draw_text(screen, f"最终得分: {score}", font_medium, WHITE, WIDTH//2, HEIGHT//2 - 20)
            draw_text(screen, "按 R 重新开始 (同难度)", font_small, WHITE, WIDTH//2, HEIGHT//2 + 40)
            draw_text(screen, "按 M 返回主菜单", font_small, WHITE, WIDTH//2, HEIGHT//2 + 80)

        pygame.display.flip()

# ---------- 主菜单 ----------
def main_menu():
    buttons = [
        {"label": "简单", "rect": pygame.Rect(WIDTH//2-100, 220, 200, 60), "difficulty": "简单"},
        {"label": "普通", "rect": pygame.Rect(WIDTH//2-100, 310, 200, 60), "difficulty": "普通"},
        {"label": "困难", "rect": pygame.Rect(WIDTH//2-100, 400, 200, 60), "difficulty": "困难"},
    ]

    while True:
        screen.fill(SNOW)
        draw_text(screen, "🎿 滑雪模拟器", font_large, BLUE, WIDTH//2, 120)
        draw_text(screen, "请选择难度", font_medium, BLACK, WIDTH//2, 180)

        mouse_pos = pygame.mouse.get_pos()
        for btn in buttons:
            color = (100, 200, 100) if btn["rect"].collidepoint(mouse_pos) else (60, 160, 60)
            pygame.draw.rect(screen, color, btn["rect"], border_radius=10)
            pygame.draw.rect(screen, BLACK, btn["rect"], width=3, border_radius=10)
            draw_text(screen, btn["label"], font_medium, WHITE, btn["rect"].centerx, btn["rect"].centery)

        draw_text(screen, "点击按钮选择难度  或  按 ESC 退出", font_small, GRAY, WIDTH//2, 520)

        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    for btn in buttons:
                        if btn["rect"].collidepoint(event.pos):
                            return game_loop(btn["difficulty"])

# ---------- 启动 ----------
if __name__ == "__main__":
    main_menu()