import pygame
import math
import random

# 初始化pygame
pygame.init()
pygame.font.init()  # 强制初始化字体模块
WIDTH, HEIGHT = 1000, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("First Person Ski Simulator")
clock = pygame.time.Clock()
FPS = 60

# 颜色定义
WHITE = (255, 255, 255)
SKY_BLUE = (135, 206, 235)
TREE_GREEN = (20, 80, 20)
TREE_TRUNK = (80, 50, 20)
GOLD = (255, 215, 0)
RED = (220, 30, 30)
BLACK = (0, 0, 0)

# 关卡配置
LEVEL_CONFIG = [
    {"speed": 3, "tree_count": 8, "coin_count": 5, "ai_count": 1, "name": "Level 1: Beginner"},
    {"speed": 4.5, "tree_count": 12, "coin_count": 7, "ai_count": 2, "name": "Level 2: Gentle Slope"},
    {"speed": 6, "tree_count": 16, "coin_count": 9, "ai_count": 2, "name": "Level 3: Forest Run"},
    {"speed": 7.5, "tree_count": 20, "coin_count": 11, "ai_count": 3, "name": "Level 4: High Speed"},
    {"speed": 9, "tree_count": 24, "coin_count": 13, "ai_count": 3, "name": "Level 5: Final Challenge"},
]

# 第一视角滑雪主类
class SkiGame:
    def __init__(self):
        self.level = 0
        self.score = 0
        self.total_coins = 0
        self.game_state = "menu"  # menu / playing / levelup / win
        self.player_yaw = 0  # 视角左右偏转
        self.max_yaw = 0.8
        self.yaw_speed = 0.04
        self.tree_list = []
        self.coin_list = []
        self.ai_list = []
        self.distance = 0
        self.goal_distance = 1200
        # 关键：使用font.Font(None, size)，不调用SysFont！绕开bug
        self.font_small = pygame.font.Font(None, 24)
        self.font_mid = pygame.font.Font(None, 30)
        self.font_big = pygame.font.Font(None, 48)
        self.font_huge = pygame.font.Font(None, 52)

    def reset_level(self):
        cfg = LEVEL_CONFIG[self.level]
        self.distance = 0
        self.player_yaw = 0
        self.tree_list = []
        self.coin_list = []
        self.ai_list = []
        # 生成树木
        for _ in range(cfg["tree_count"]):
            z = random.uniform(100, self.goal_distance)
            x = random.uniform(-12, 12)
            self.tree_list.append({"x": x, "z": z})
        # 生成金币
        for _ in range(cfg["coin_count"]):
            z = random.uniform(150, self.goal_distance - 100)
            x = random.uniform(-8, 8)
            self.coin_list.append({"x": x, "z": z, "collected": False})
        # 生成AI对手
        for i in range(cfg["ai_count"]):
            z = random.uniform(200, self.goal_distance - 200)
            x = random.uniform(-7, 7)
            ai_speed = cfg["speed"] * random.uniform(0.85, 1.15)
            self.ai_list.append({"x": x, "z": z, "speed": ai_speed, "dir": random.choice([-1, 1])})

    # 透视投影：3D坐标转屏幕2D坐标
    def project(self, x, z):
        fov = 3.2
        if z <= 0.1:
            return None
        scale = fov / z
        screen_x = WIDTH / 2 + x * scale * 120
        screen_y = HEIGHT / 2 + 220 / z * 80
        size = 280 / z
        return screen_x, screen_y, size

    def draw_background(self):
        # 天空
        pygame.draw.rect(screen, SKY_BLUE, (0, 0, WIDTH, HEIGHT//2))
        # 雪地
        pygame.draw.rect(screen, WHITE, (0, HEIGHT//2, WIDTH, HEIGHT//2))
        # 赛道透视引导线
        for i in range(1, 7):
            z = i * 180
            p1 = self.project(-10, z)
            p2 = self.project(10, z)
            if p1 and p2:
                pygame.draw.line(screen, (220,220,220), (p1[0], p1[1]), (p2[0], p2[1]), 2)

    def update(self):
        if self.game_state != "playing":
            return
        cfg = LEVEL_CONFIG[self.level]
        self.distance += cfg["speed"]
        # 树木滚动
        for t in self.tree_list:
            t["z"] -= cfg["speed"]
            if t["z"] < 0:
                t["z"] = self.goal_distance + random.uniform(50, 200)
                t["x"] = random.uniform(-12, 12)
        # 金币滚动
        for c in self.coin_list:
            c["z"] -= cfg["speed"]
            if c["z"] < 0:
                c["z"] = self.goal_distance + random.uniform(50, 150)
                c["x"] = random.uniform(-8, 8)
                c["collected"] = False
        # AI对手移动逻辑
        for ai in self.ai_list:
            ai["z"] -= ai["speed"]
            ai["x"] += ai["dir"] * 0.025
            if abs(ai["x"]) > 9:
                ai["dir"] *= -1
            if ai["z"] < 0:
                ai["z"] = self.goal_distance + random.uniform(80, 200)
                ai["x"] = random.uniform(-7,7)
                ai["speed"] = cfg["speed"] * random.uniform(0.85,1.15)
        # 金币拾取碰撞
        for coin in self.coin_list:
            if coin["collected"]:
                continue
            dx = self.player_yaw * 2 - coin["x"]
            dz = abs(coin["z"] - self.distance)
            if dz < 30 and abs(dx) < 2.2:
                coin["collected"] = True
                self.score += 100
                self.total_coins +=1
        # 到达终点判断
        if self.distance >= self.goal_distance:
            if self.level < 4:
                self.game_state = "levelup"
            else:
                self.game_state = "win"

    def draw_objects(self):
        # 按距离由远到近渲染
        render_list = []
        for t in self.tree_list:
            render_list.append(("tree", t["x"], t["z"]))
        for c in self.coin_list:
            if not c["collected"]:
                render_list.append(("coin", c["x"], c["z"]))
        for ai in self.ai_list:
            render_list.append(("ai", ai["x"], ai["z"]))
        render_list.sort(key=lambda item: -item[2])

        for typ, x, z in render_list:
            view_x = x - self.player_yaw * z * 0.3
            proj = self.project(view_x, z - self.distance)
            if not proj:
                continue
            sx, sy, sz = proj
            if sz < 1:
                continue
            if typ == "tree":
                pygame.draw.rect(screen, TREE_TRUNK, (sx - sz*0.12, sy, sz*0.24, sz*0.6))
                pygame.draw.circle(screen, TREE_GREEN, (sx, sy - sz*0.3), sz*0.45)
            elif typ == "coin":
                pygame.draw.circle(screen, GOLD, (int(sx), int(sy)), max(3, int(sz*0.22)))
            elif typ == "ai":
                pygame.draw.circle(screen, RED, (int(sx), int(sy)), max(4, int(sz*0.25)))

    def draw_ui(self):
        cfg = LEVEL_CONFIG[self.level]
        text1 = self.font_small.render(f"{cfg['name']}", True, BLACK)
        text2 = self.font_small.render(f"Score: {self.score}", True, BLACK)
        text3 = self.font_small.render(f"Coins: {self.total_coins}", True, BLACK)
        progress = self.distance / self.goal_distance
        pygame.draw.rect(screen, (80,80,80), (20, HEIGHT-40, 200,16))
        pygame.draw.rect(screen, (0,180,0), (20, HEIGHT-40, 200*progress,16))
        screen.blit(text1, (20, 10))
        screen.blit(text2, (20, 40))
        screen.blit(text3, (20, 70))

    def draw_menu(self):
        screen.fill(SKY_BLUE)
        t1 = self.font_big.render("First Person Ski Simulator", True, BLACK)
        t2 = self.font_mid.render("← → Arrow keys to turn", True, BLACK)
        t3 = self.font_mid.render("SPACE: Start Game", True, BLACK)
        t4 = self.font_mid.render("5 levels! Collect coins, race AI opponents!", True, BLACK)
        screen.blit(t1, (WIDTH//2 - t1.get_width()//2, 120))
        screen.blit(t2, (WIDTH//2 - t2.get_width()//2, 220))
        screen.blit(t3, (WIDTH//2 - t3.get_width()//2, 280))
        screen.blit(t4, (WIDTH//2 - t4.get_width()//2, 340))

    def draw_levelup(self):
        screen.fill(SKY_BLUE)
        t1 = self.font_big.render(f"Completed {LEVEL_CONFIG[self.level]['name']}!", True, BLACK)
        t2 = self.font_mid.render("Press SPACE for next level", True, BLACK)
        screen.blit(t1, (WIDTH//2 - t1.get_width()//2, 200))
        screen.blit(t2, (WIDTH//2 - t2.get_width()//2, 300))

    def draw_win(self):
        screen.fill(SKY_BLUE)
        t1 = self.font_huge.render("All Levels Cleared!", True, BLACK)
        t2 = self.font_mid.render(f"Final Score: {self.score}  Total Coins: {self.total_coins}", True, BLACK)
        t3 = self.font_mid.render("Press SPACE back to menu", True, BLACK)
        screen.blit(t1, (WIDTH//2 - t1.get_width()//2, 160))
        screen.blit(t2, (WIDTH//2 - t2.get_width()//2, 260))
        screen.blit(t3, (WIDTH//2 - t3.get_width()//2, 340))

    def handle_input(self, keys):
        if self.game_state == "playing":
            if keys[pygame.K_LEFT]:
                self.player_yaw += self.yaw_speed
            if keys[pygame.K_RIGHT]:
                self.player_yaw -= self.yaw_speed
            self.player_yaw = max(-self.max_yaw, min(self.max_yaw, self.player_yaw))

    def draw(self):
        if self.game_state == "menu":
            self.draw_menu()
        elif self.game_state == "levelup":
            self.draw_levelup()
        elif self.game_state == "win":
            self.draw_win()
        elif self.game_state == "playing":
            self.draw_background()
            self.draw_objects()
            self.draw_ui()

    def run(self):
        running = True
        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        if self.game_state == "menu":
                            self.level = 0
                            self.score = 0
                            self.total_coins = 0
                            self.reset_level()
                            self.game_state = "playing"
                        elif self.game_state == "levelup":
                            self.level += 1
                            self.reset_level()
                            self.game_state = "playing"
                        elif self.game_state == "win":
                            self.game_state = "menu"
            keys = pygame.key.get_pressed()
            self.handle_input(keys)
            self.update()
            self.draw()
            pygame.display.flip()
            clock.tick(FPS)
        pygame.quit()

if __name__ == "__main__":
    game = SkiGame()
    game.run()
