import pygame
import random
import sys
import math
import os

# 初始化 Pygame
pygame.init()

# 游戏常量
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 500
FPS = 60
GRAVITY = 1
JUMP_STRENGTH = -20
INITIAL_GAME_SPEED = 5
OBSTACLE_SPAWN_RATE = 1200
POWERUP_SPAWN_RATE = 5000
ITEM_DURATION = 10000

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 200, 0)
BLUE = (0, 120, 255)
BROWN = (139, 69, 19)
RED = (255, 0, 0)
SKY_BLUE = (135, 206, 235)
YELLOW = (255, 255, 0)
PURPLE = (128, 0, 128)
ORANGE = (255, 165, 0)
PINK = (255, 192, 203)
CYAN = (0, 255, 255)
GOLD = (255, 215, 0)
GRAY = (128, 128, 128)
LIGHT_GREEN = (144, 238, 144)
DARK_GREEN = (0, 100, 0)
DARK_BLUE = (0, 0, 139)
LIGHT_BROWN = (210, 180, 140)
DARK_RED = (139, 0, 0)

# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("跑酷大冒险 - 增强版")
clock = pygame.time.Clock()

# 尝试加载字体
try:
    font = pygame.font.SysFont('simhei', 24, bold=True)
    big_font = pygame.font.SysFont('simhei', 48, bold=True)
    title_font = pygame.font.SysFont('simhei', 64, bold=True)
    small_font = pygame.font.SysFont('simhei', 20)
except:
    # 如果找不到中文字体，使用默认字体
    font = pygame.font.SysFont(None, 24, bold=True)
    big_font = pygame.font.SysFont(None, 48, bold=True)
    title_font = pygame.font.SysFont(None, 64, bold=True)
    small_font = pygame.font.SysFont(None, 20)

class Player:
    def __init__(self):
        self.width = 40
        self.height = 60
        self.x = 100
        self.y = SCREEN_HEIGHT - 100 - self.height
        self.vel_y = 0
        self.jumping = False
        self.score = 0
        self.coins = 0
        self.powerups = {
            "double_jump": 0,
            "shield": 0,
            "magnet": 0,
            "invincible": 0
        }
        self.is_invincible = False
        self.invincible_timer = 0
        self.double_jump_available = True
        self.has_shield = False
        self.level = 1
        self.flash_timer = 0
        
    def jump(self):
        if not self.jumping:
            self.vel_y = JUMP_STRENGTH
            self.jumping = True
        elif self.powerups["double_jump"] > 0 and self.double_jump_available:
            self.vel_y = JUMP_STRENGTH
            self.double_jump_available = False
    
    def update(self, game_speed):
        # 更新无敌状态
        if self.is_invincible:
            self.invincible_timer -= 1
            if self.invincible_timer <= 0:
                self.is_invincible = False
                
        # 更新闪烁效果
        if self.flash_timer > 0:
            self.flash_timer -= 1
                
        # 应用重力
        self.vel_y += GRAVITY
        self.y += self.vel_y
        
        # 检测地面碰撞
        if self.y >= SCREEN_HEIGHT - 100 - self.height:
            self.y = SCREEN_HEIGHT - 100 - self.height
            self.jumping = False
            self.vel_y = 0
            self.double_jump_available = True
            
        # 增加分数
        self.score += 0.1 * game_speed / INITIAL_GAME_SPEED
        
    def draw(self):
        # 判断是否闪烁
        should_draw = True
        if self.flash_timer > 0 and self.flash_timer % 10 < 5:
            should_draw = False
            
        if not should_draw:
            return
            
        # 绘制盾牌
        if self.has_shield and not self.is_invincible:
            shield_radius = 35
            pygame.draw.circle(screen, CYAN, 
                             (int(self.x + self.width//2), int(self.y + self.height//2)), 
                             shield_radius, 3)
            # 盾牌发光效果
            for i in range(3):
                radius = shield_radius + i * 2
                alpha = 100 - i * 30
                s = pygame.Surface((radius*2, radius*2), pygame.SRCALPHA)
                pygame.draw.circle(s, (0, 255, 255, alpha), (radius, radius), radius, 2)
                screen.blit(s, (self.x + self.width//2 - radius, self.y + self.height//2 - radius))
        
        # 绘制玩家身体
        if self.is_invincible:
            # 无敌时的闪烁效果
            if pygame.time.get_ticks() % 200 < 100:
                body_color = GOLD
            else:
                body_color = (255, 255, 100)
        else:
            body_color = BLUE
            
        pygame.draw.rect(screen, body_color, (self.x, self.y, self.width, self.height))
        
        # 绘制玩家细节
        pygame.draw.rect(screen, DARK_BLUE, (self.x, self.y, self.width, 15))  # 头部
        pygame.draw.rect(screen, BLACK, (self.x + 10, self.y + 5, 8, 8))  # 左眼
        pygame.draw.rect(screen, BLACK, (self.x + self.width - 18, self.y + 5, 8, 8))  # 右眼
        
        # 绘制嘴巴
        pygame.draw.line(screen, BLACK, 
                        (self.x + 15, self.y + 25), 
                        (self.x + self.width - 15, self.y + 25), 2)
        
        # 绘制身体细节
        pygame.draw.rect(screen, DARK_BLUE, (self.x, self.y + 40, self.width, 20))  # 裤子
        
    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)
    
    def add_powerup(self, powerup_type, duration=ITEM_DURATION):
        if powerup_type == "double_jump":
            self.powerups["double_jump"] += duration
        elif powerup_type == "shield":
            self.has_shield = True
            self.powerups["shield"] += duration
        elif powerup_type == "magnet":
            self.powerups["magnet"] += duration
        elif powerup_type == "invincible":
            self.is_invincible = True
            self.invincible_timer = duration / 16.67
            self.powerups["invincible"] += duration
        elif powerup_type == "coin":
            self.coins += 1
    
    def update_powerups(self):
        for powerup in self.powerups:
            if self.powerups[powerup] > 0:
                self.powerups[powerup] -= 16.67
                if self.powerups[powerup] <= 0:
                    self.powerups[powerup] = 0
                    if powerup == "shield":
                        self.has_shield = False
                    elif powerup == "invincible":
                        self.is_invincible = False
    
    def take_damage(self):
        if not self.is_invincible and not self.has_shield:
            self.flash_timer = 60
            return True
        elif self.has_shield:
            self.has_shield = False
            self.powerups["shield"] = 0
            self.flash_timer = 30
        return False

class BaseObstacle:
    def __init__(self, x, y, width, height, color, points=10):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.points = points
        self.hit_color = RED
        
    def update(self, game_speed):
        self.x -= game_speed
        
    def draw(self, screen):
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
        
    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)
    
    def is_off_screen(self):
        return self.x + self.width < 0

class BoxObstacle(BaseObstacle):
    def __init__(self, x, y):
        super().__init__(x, y, 40, 60, BROWN, 10)
        self.texture_color = LIGHT_BROWN
        
    def draw(self, screen):
        # 绘制箱子主体
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
        
        # 绘制箱子纹理
        pygame.draw.rect(screen, self.texture_color, 
                        (self.x + 5, self.y + 5, self.width - 10, self.height - 10))
        
        # 绘制箱子边缘
        pygame.draw.rect(screen, BLACK, (self.x, self.y, self.width, self.height), 2)
        
        # 绘制木板纹理
        for i in range(3):
            y_pos = self.y + 10 + i * 15
            pygame.draw.rect(screen, DARK_RED, 
                           (self.x + 5, y_pos, self.width - 10, 5))

class SpikeObstacle(BaseObstacle):
    def __init__(self, x, y):
        super().__init__(x, y, 30, 40, RED, 20)
        
    def draw(self, screen):
        # 绘制尖刺三角形
        points = [
            (self.x, self.y + self.height),
            (self.x + self.width//2, self.y),
            (self.x + self.width, self.y + self.height)
        ]
        pygame.draw.polygon(screen, self.color, points)
        pygame.draw.polygon(screen, DARK_RED, points, 2)
        
        # 绘制尖刺纹理
        for i in range(1, 3):
            x_pos = self.x + i * 10
            pygame.draw.line(screen, (255, 100, 100), 
                           (x_pos, self.y + self.height - 10), 
                           (x_pos, self.y + self.height - 20), 2)

class MovingObstacle(BaseObstacle):
    def __init__(self, x, y):
        super().__init__(x, y, 35, 35, PURPLE, 15)
        self.initial_y = y
        self.oscillation = random.random() * 6.28
        self.speed = random.uniform(0.05, 0.1)
        
    def update(self, game_speed):
        super().update(game_speed)
        self.oscillation += self.speed
        self.y = self.initial_y + math.sin(self.oscillation) * 30
        
    def draw(self, screen):
        # 绘制移动方块
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
        
        # 绘制能量效果
        for i in range(3):
            radius = 20 + i * 3
            alpha = 50 - i * 15
            s = pygame.Surface((self.width + 20, self.height + 20), pygame.SRCALPHA)
            pygame.draw.rect(s, (*PURPLE, alpha), 
                           (i * 2, i * 2, self.width, self.height), 3)
            screen.blit(s, (self.x - 10, self.y - 10))

class BreakableObstacle(BaseObstacle):
    def __init__(self, x, y):
        super().__init__(x, y, 30, 50, ORANGE, 5)
        self.health = 2
        self.crack_color = (200, 100, 0)
        
    def draw(self, screen):
        # 绘制可破坏方块
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
        
        # 根据生命值绘制裂缝
        if self.health == 1:
            # 绘制裂缝
            pygame.draw.line(screen, self.crack_color, 
                           (self.x + 5, self.y + 5), 
                           (self.x + self.width - 5, self.y + self.height - 5), 3)
            pygame.draw.line(screen, self.crack_color, 
                           (self.x + self.width - 5, self.y + 5), 
                           (self.x + 5, self.y + self.height - 5), 3)
        
        # 绘制边缘
        pygame.draw.rect(screen, (150, 75, 0), (self.x, self.y, self.width, self.height), 2)
        
    def hit(self):
        self.health -= 1
        if self.health <= 0:
            return True
        return False

class WideObstacle(BaseObstacle):
    def __init__(self, x, y):
        super().__init__(x, y, 100, 40, (100, 50, 0), 12)
        self.pattern_color = (80, 40, 0)
        
    def draw(self, screen):
        # 绘制宽障碍物
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
        
        # 绘制纹理图案
        for i in range(3):
            x_offset = i * 25
            pygame.draw.rect(screen, self.pattern_color, 
                           (self.x + 5 + x_offset, self.y + 5, 20, 10))
            pygame.draw.rect(screen, self.pattern_color, 
                           (self.x + 5 + x_offset, self.y + 25, 20, 10))

class BouncingObstacle(BaseObstacle):
    def __init__(self, x, y):
        super().__init__(x, y, 35, 35, PINK, 18)
        self.initial_y = y
        self.bounce_height = 50
        self.bounce_speed = 0.1
        self.angle = 0
        
    def update(self, game_speed):
        super().update(game_speed)
        self.angle += self.bounce_speed
        bounce = math.sin(self.angle * 2) * self.bounce_height
        self.y = self.initial_y + bounce
        
    def draw(self, screen):
        # 绘制弹跳方块
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
        
        # 绘制弹跳效果
        pygame.draw.circle(screen, (255, 150, 200), 
                         (int(self.x + self.width//2), int(self.y + self.height//2)), 
                         self.width//2 - 2)
        
        # 绘制内部图案
        pygame.draw.circle(screen, WHITE, 
                         (int(self.x + self.width//2), int(self.y + self.height//2)), 
                         self.width//4)

class PowerUp:
    def __init__(self, x, y, p_type):
        self.x = x
        self.y = y
        self.width = 25
        self.height = 25
        self.type = p_type
        self.collected = False
        self.float_offset = random.random() * 6.28
        self.float_speed = 0.05
        self.rotation = 0
        
    def update(self, game_speed):
        self.x -= game_speed
        self.float_offset += self.float_speed
        self.rotation += 1
        
    def draw(self, screen):
        if self.collected:
            return
            
        # 漂浮效果
        y_offset = math.sin(self.float_offset) * 8
        
        # 绘制背景光晕
        glow_radius = 15
        for i in range(3):
            radius = glow_radius + i * 3
            alpha = 50 - i * 15
            s = pygame.Surface((radius*2, radius*2), pygame.SRCALPHA)
            color = self.get_color()
            pygame.draw.circle(s, (*color, alpha), (radius, radius), radius)
            screen.blit(s, (self.x + self.width//2 - radius, 
                          self.y + y_offset + self.height//2 - radius))
        
        # 绘制道具主体
        if self.type == "double_jump":
            self.draw_double_jump(screen, y_offset)
        elif self.type == "shield":
            self.draw_shield(screen, y_offset)
        elif self.type == "magnet":
            self.draw_magnet(screen, y_offset)
        elif self.type == "invincible":
            self.draw_invincible(screen, y_offset)
        elif self.type == "coin":
            self.draw_coin(screen, y_offset)
            
    def get_color(self):
        colors = {
            "double_jump": YELLOW,
            "shield": CYAN,
            "magnet": PINK,
            "invincible": GOLD,
            "coin": GOLD
        }
        return colors.get(self.type, WHITE)
    
    def draw_double_jump(self, screen, y_offset):
        center_x = self.x + self.width//2
        center_y = self.y + y_offset + self.height//2
        
        # 绘制外圈
        pygame.draw.circle(screen, YELLOW, (int(center_x), int(center_y)), 10)
        pygame.draw.circle(screen, BLACK, (int(center_x), int(center_y)), 10, 2)
        
        # 绘制向上箭头
        pygame.draw.polygon(screen, BLACK, [
            (center_x, center_y - 6),
            (center_x - 4, center_y),
            (center_x + 4, center_y)
        ])
        
        # 绘制第二个箭头
        pygame.draw.polygon(screen, BLACK, [
            (center_x, center_y - 1),
            (center_x - 4, center_y + 5),
            (center_x + 4, center_y + 5)
        ])
    
    def draw_shield(self, screen, y_offset):
        center_x = self.x + self.width//2
        center_y = self.y + y_offset + self.height//2
        
        # 绘制盾牌
        pygame.draw.circle(screen, CYAN, (int(center_x), int(center_y)), 12)
        pygame.draw.circle(screen, BLACK, (int(center_x), int(center_y)), 12, 2)
        
        # 绘制盾牌内部
        pygame.draw.circle(screen, WHITE, (int(center_x), int(center_y)), 8)
        pygame.draw.circle(screen, CYAN, (int(center_x), int(center_y)), 8, 2)
        
        # 绘制十字
        pygame.draw.line(screen, BLACK, (center_x - 4, center_y), (center_x + 4, center_y), 2)
        pygame.draw.line(screen, BLACK, (center_x, center_y - 4), (center_x, center_y + 4), 2)
    
    def draw_magnet(self, screen, y_offset):
        center_x = self.x + self.width//2
        center_y = self.y + y_offset + self.height//2
        
        # 绘制磁铁
        pygame.draw.rect(screen, PINK, (self.x, self.y + y_offset, self.width, self.height))
        pygame.draw.rect(screen, BLACK, (self.x, self.y + y_offset, self.width, self.height), 2)
        
        # 绘制磁极
        pygame.draw.rect(screen, RED, (self.x + 3, self.y + y_offset + 3, 8, 8))
        pygame.draw.rect(screen, BLUE, (self.x + 14, self.y + y_offset + 3, 8, 8))
        
        # 绘制N和S
        n_text = small_font.render("N", True, WHITE)
        s_text = small_font.render("S", True, WHITE)
        screen.blit(n_text, (self.x + 5, self.y + y_offset + 2))
        screen.blit(s_text, (self.x + 16, self.y + y_offset + 2))
    
    def draw_invincible(self, screen, y_offset):
        center_x = self.x + self.width//2
        center_y = self.y + y_offset + self.height//2
        
        # 绘制星星
        self.draw_star(screen, center_x, center_y, 12, 6, 5, GOLD)
        
        # 绘制外圈发光
        pygame.draw.circle(screen, (255, 255, 150, 100), 
                         (int(center_x), int(center_y)), 15, 3)
    
    def draw_coin(self, screen, y_offset):
        center_x = self.x + self.width//2
        center_y = self.y + y_offset + self.height//2
        
        # 绘制金币
        pygame.draw.circle(screen, GOLD, (int(center_x), int(center_y)), 10)
        pygame.draw.circle(screen, (200, 170, 0), (int(center_x), int(center_y)), 8)
        pygame.draw.circle(screen, (255, 215, 0), (int(center_x), int(center_y)), 6)
        
        # 绘制金币图案
        pygame.draw.circle(screen, (255, 200, 0), (int(center_x), int(center_y)), 4)
        pygame.draw.circle(screen, GOLD, (int(center_x), int(center_y)), 4, 1)
        
        # 绘制旋转效果
        angle = math.radians(self.rotation)
        end_x = center_x + math.cos(angle) * 8
        end_y = center_y + math.sin(angle) * 8
        pygame.draw.line(screen, (255, 200, 0), (center_x, center_y), (end_x, end_y), 2)
    
    def draw_star(self, screen, cx, cy, outer_radius, inner_radius, points, color):
        coords = []
        for i in range(points * 2):
            angle = i * math.pi / points
            radius = inner_radius if i % 2 else outer_radius
            coords.append((cx + radius * math.sin(angle), cy + radius * math.cos(angle)))
        pygame.draw.polygon(screen, color, coords)
        
    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)
    
    def is_off_screen(self):
        return self.x + self.width < 0

class Coin(PowerUp):
    def __init__(self, x, y):
        super().__init__(x, y, "coin")
        self.value = random.randint(1, 5)
        self.spin_speed = 5
        
    def update(self, game_speed):
        super().update(game_speed)
        self.rotation += self.spin_speed

class LevelSystem:
    def __init__(self):
        self.current_level = 1
        self.score_to_next_level = 100
        self.game_speed = INITIAL_GAME_SPEED
        self.obstacle_density = 1.0
        self.background_index = 0
        self.backgrounds = [
            {"sky": (135, 206, 235), "ground": (0, 200, 0), "name": "草原"},
            {"sky": (25, 25, 112), "ground": (34, 139, 34), "name": "森林"},
            {"sky": (255, 140, 0), "ground": (160, 82, 45), "name": "沙漠"},
            {"sky": (70, 130, 180), "ground": (105, 105, 105), "name": "山脉"}
        ]
        
    def update(self, score):
        if score >= self.score_to_next_level:
            self.current_level += 1
            self.score_to_next_level = int(self.score_to_next_level * 1.5)
            self.game_speed += 0.5
            self.obstacle_density = min(2.0, self.obstacle_density * 1.1)
            
            # 每2级更换背景
            if self.current_level % 2 == 1:
                self.background_index = (self.background_index + 1) % len(self.backgrounds)
                
            return True
        return False
    
    def get_sky_color(self):
        return self.backgrounds[self.background_index]["sky"]
    
    def get_ground_color(self):
        return self.backgrounds[self.background_index]["ground"]
    
    def get_spawn_rate(self):
        return max(300, OBSTACLE_SPAWN_RATE - (self.current_level - 1) * 50)
    
    def get_powerup_chance(self):
        return min(0.3, 0.1 + (self.current_level - 1) * 0.02)

class Cloud:
    def __init__(self, sky_color):
        self.x = SCREEN_WIDTH
        self.y = random.randint(20, 150)
        self.width = random.randint(60, 120)
        self.height = random.randint(20, 40)
        self.speed = random.uniform(0.5, 2.0)
        self.color = (
            min(255, sky_color[0] + random.randint(20, 40)),
            min(255, sky_color[1] + random.randint(20, 40)),
            min(255, sky_color[2] + random.randint(20, 40))
        )
        
    def update(self, game_speed):
        self.x -= self.speed * (game_speed / INITIAL_GAME_SPEED)
        
    def draw(self, screen):
        # 绘制云朵
        pygame.draw.ellipse(screen, self.color, (self.x, self.y, self.width, self.height))
        pygame.draw.ellipse(screen, self.color, (self.x - 20, self.y + 10, self.width * 0.7, self.height * 0.8))
        pygame.draw.ellipse(screen, self.color, (self.x + 20, self.y + 10, self.width * 0.7, self.height * 0.8))
        
    def is_off_screen(self):
        return self.x + self.width < 0

def draw_background(level_system):
    sky_color = level_system.get_sky_color()
    ground_color = level_system.get_ground_color()
    
    # 绘制渐变天空
    for i in range(SCREEN_HEIGHT - 100):
        ratio = i / (SCREEN_HEIGHT - 100)
        r = int(sky_color[0] * (1 - ratio) + sky_color[0] * 0.7 * ratio)
        g = int(sky_color[1] * (1 - ratio) + sky_color[1] * 0.7 * ratio)
        b = int(sky_color[2] * (1 - ratio) + sky_color[2] * 0.7 * ratio)
        pygame.draw.line(screen, (r, g, b), (0, i), (SCREEN_WIDTH, i))
    
    # 绘制地面
    pygame.draw.rect(screen, ground_color, (0, SCREEN_HEIGHT - 100, SCREEN_WIDTH, 100))
    
    # 绘制地面纹理
    dark_ground = (
        max(0, ground_color[0] - 30),
        max(0, ground_color[1] - 30),
        max(0, ground_color[2] - 30)
    )
    
    for i in range(0, SCREEN_WIDTH, 30):
        pygame.draw.line(screen, dark_ground, 
                        (i, SCREEN_HEIGHT - 100), 
                        (i, SCREEN_HEIGHT), 2)
    
    # 在高层级时绘制远山
    if level_system.current_level >= 3:
        for i in range(5):
            x = i * 200 - 100
            height = random.randint(80, 150)
            mountain_color = (
                max(0, ground_color[0] - 40),
                max(0, ground_color[1] - 40),
                max(0, ground_color[2] - 40)
            )
            points = [
                (x, SCREEN_HEIGHT - 100),
                (x + 100, SCREEN_HEIGHT - 100 - height),
                (x + 200, SCREEN_HEIGHT - 100)
            ]
            pygame.draw.polygon(screen, mountain_color, points)
            
            # 山顶雪
            if level_system.current_level >= 4:
                pygame.draw.polygon(screen, WHITE, [
                    (x + 80, SCREEN_HEIGHT - 100 - height),
                    (x + 100, SCREEN_HEIGHT - 100 - height - 20),
                    (x + 120, SCREEN_HEIGHT - 100 - height)
                ])

def draw_hud(player, level_system, game_speed):
    # 绘制分数
    score_text = font.render(f"分数: {int(player.score)}", True, WHITE)
    screen.blit(score_text, (20, 20))
    
    # 绘制金币
    coin_text = font.render(f"金币: {player.coins}", True, GOLD)
    screen.blit(coin_text, (20, 60))
    
    # 绘制等级
    level_text = font.render(f"等级: {level_system.current_level}", True, PURPLE)
    screen.blit(level_text, (20, 100))
    
    # 绘制速度
    speed_text = font.render(f"速度: {game_speed:.1f}", True, WHITE)
    screen.blit(speed_text, (20, 140))
    
    # 绘制下一级所需分数
    next_level_text = font.render(f"下一级: {int(level_system.score_to_next_level - player.score)}分", True, ORANGE)
    screen.blit(next_level_text, (SCREEN_WIDTH - next_level_text.get_width() - 20, 20))
    
    # 绘制道具状态
    y_pos = 180
    for powerup, duration in player.powerups.items():
        if duration > 0:
            if powerup == "double_jump":
                color = YELLOW
                name = "二段跳"
            elif powerup == "shield":
                color = CYAN
                name = "护盾"
            elif powerup == "magnet":
                color = PINK
                name = "磁铁"
            elif powerup == "invincible":
                color = GOLD
                name = "无敌"
            else:
                continue
                
            time_left = int(duration / 1000)
            if time_left > 0:
                powerup_text = font.render(f"{name}: {time_left}秒", True, color)
                screen.blit(powerup_text, (20, y_pos))
                y_pos += 40

def draw_game_over(score, coins, level):
    # 半透明遮罩
    overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
    overlay.fill((0, 0, 0, 180))
    screen.blit(overlay, (0, 0))
    
    # 游戏结束文本
    game_over_text = big_font.render("游戏结束", True, RED)
    score_text = font.render(f"最终分数: {int(score)}", True, WHITE)
    coin_text = font.render(f"收集金币: {coins}", True, GOLD)
    level_text = font.render(f"达到等级: {level}", True, PURPLE)
    restart_text = font.render("按R键重新开始 或 按ESC键退出", True, WHITE)
    
    screen.blit(game_over_text, (SCREEN_WIDTH//2 - game_over_text.get_width()//2, SCREEN_HEIGHT//2 - 150))
    screen.blit(score_text, (SCREEN_WIDTH//2 - score_text.get_width()//2, SCREEN_HEIGHT//2 - 80))
    screen.blit(coin_text, (SCREEN_WIDTH//2 - coin_text.get_width()//2, SCREEN_HEIGHT//2 - 40))
    screen.blit(level_text, (SCREEN_WIDTH//2 - level_text.get_width()//2, SCREEN_HEIGHT//2))
    screen.blit(restart_text, (SCREEN_WIDTH//2 - restart_text.get_width()//2, SCREEN_HEIGHT//2 + 60))

def show_level_up(level):
    # 创建半透明表面
    overlay = pygame.Surface((SCREEN_WIDTH, 100), pygame.SRCALPHA)
    overlay.fill((0, 0, 0, 150))
    screen.blit(overlay, (0, SCREEN_HEIGHT//2 - 50))
    
    # 等级提升文本
    level_text = big_font.render(f"等级提升! 等级 {level}", True, GOLD)
    screen.blit(level_text, (SCREEN_WIDTH//2 - level_text.get_width()//2, SCREEN_HEIGHT//2 - 30))

def create_random_obstacle(x_pos, level):
    y = SCREEN_HEIGHT - 100
    obstacle_classes = [BoxObstacle, SpikeObstacle, MovingObstacle, BreakableObstacle, WideObstacle, BouncingObstacle]
    
    # 根据等级调整权重
    if level < 2:
        weights = [0.4, 0.3, 0.2, 0.1, 0.0, 0.0]  # 前2级只有基础障碍物
    elif level < 4:
        weights = [0.3, 0.25, 0.2, 0.15, 0.1, 0.0]  # 3-4级增加宽障碍物
    elif level < 6:
        weights = [0.2, 0.2, 0.2, 0.15, 0.15, 0.1]  # 5-6级增加弹跳障碍物
    else:
        weights = [0.15, 0.15, 0.2, 0.15, 0.2, 0.15]  # 高级别平衡分布
    
    obstacle_class = random.choices(obstacle_classes, weights=weights)[0]
    
    if obstacle_class == SpikeObstacle:
        return SpikeObstacle(x_pos, y - 40)
    elif obstacle_class == MovingObstacle:
        return MovingObstacle(x_pos, y - 35)
    elif obstacle_class == BouncingObstacle:
        return BouncingObstacle(x_pos, y - 35)
    elif obstacle_class == WideObstacle:
        return WideObstacle(x_pos, y - 40)
    else:
        height = random.randint(40, 70)
        if obstacle_class == BreakableObstacle:
            return BreakableObstacle(x_pos, y - height)
        else:  # BoxObstacle
            return BoxObstacle(x_pos, y - height)

def create_random_powerup(x_pos, level):
    y = random.randint(100, SCREEN_HEIGHT - 150)
    powerup_types = ["double_jump", "shield", "magnet", "invincible", "coin"]
    
    # 调整概率
    weights = [0.1, 0.1, 0.1, 0.1, 0.6]  # 60%概率是金币
    
    # 高级别增加特殊道具概率
    if level >= 4:
        weights = [0.15, 0.15, 0.15, 0.15, 0.4]
    
    p_type = random.choices(powerup_types, weights=weights)[0]
    
    if p_type == "coin":
        return Coin(x_pos, y)
    else:
        return PowerUp(x_pos, y, p_type)

def main():
    player = Player()
    obstacles = []
    powerups = []
    clouds = []
    
    level_system = LevelSystem()
    
    last_obstacle_time = pygame.time.get_ticks()
    last_powerup_time = pygame.time.get_ticks()
    last_cloud_time = pygame.time.get_ticks()
    level_up_display_time = 0
    
    game_over = False
    running = True
    level_up_just_happened = False
    
    while running:
        current_time = pygame.time.get_ticks()
        
        # 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                return False
                
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and not game_over:
                    player.jump()
                    
                if event.key == pygame.K_r:
                    if game_over:
                        return True
                    else:
                        # 游戏进行中按R也可以重新开始
                        return True
                    
                if event.key == pygame.K_ESCAPE:
                    running = False
                    return False
        
        if not game_over:
            # 更新等级
            if level_system.update(player.score) and not level_up_just_happened:
                level_up_just_happened = True
                level_up_display_time = current_time
                
            # 清除等级提升显示
            if level_up_just_happened and current_time - level_up_display_time > 2000:
                level_up_just_happened = False
            
            # 更新游戏速度
            game_speed = level_system.game_speed
            
            # 更新玩家
            player.update(game_speed)
            player.update_powerups()
            
            # 生成障碍物
            spawn_rate = level_system.get_spawn_rate()
            if current_time - last_obstacle_time > spawn_rate:
                num_obstacles = 1
                if random.random() < 0.3 and level_system.current_level >= 3:
                    num_obstacles = 2
                    
                for _ in range(num_obstacles):
                    if random.random() < level_system.obstacle_density:
                        x_offset = random.randint(0, 200) if num_obstacles > 1 else 0
                        obstacles.append(create_random_obstacle(SCREEN_WIDTH + x_offset, level_system.current_level))
                last_obstacle_time = current_time
                
            # 生成道具
            if current_time - last_powerup_time > POWERUP_SPAWN_RATE:
                if random.random() < level_system.get_powerup_chance():
                    powerups.append(create_random_powerup(SCREEN_WIDTH, level_system.current_level))
                last_powerup_time = current_time
                
            # 生成云朵
            if current_time - last_cloud_time > 1500:
                clouds.append(Cloud(level_system.get_sky_color()))
                last_cloud_time = current_time
                
            # 更新障碍物
            for obstacle in obstacles[:]:
                obstacle.update(game_speed)
                if obstacle.is_off_screen():
                    obstacles.remove(obstacle)
                    
            # 更新道具
            for powerup in powerups[:]:
                powerup.update(game_speed)
                if powerup.is_off_screen():
                    powerups.remove(powerup)
                    
            # 更新云朵
            for cloud in clouds[:]:
                cloud.update(game_speed)
                if cloud.is_off_screen():
                    clouds.remove(cloud)
                    
            # 检测道具碰撞
            player_rect = player.get_rect()
            for powerup in powerups[:]:
                if not powerup.collected and player_rect.colliderect(powerup.get_rect()):
                    if powerup.type == "coin":
                        player.coins += powerup.value
                    else:
                        player.add_powerup(powerup.type)
                    powerup.collected = True
                    powerups.remove(powerup)
                    
            # 检测障碍物碰撞
            for obstacle in obstacles[:]:
                if player_rect.colliderect(obstacle.get_rect()):
                    if isinstance(obstacle, BreakableObstacle):
                        if player.has_shield or obstacle.hit():
                            player.has_shield = False
                            player.powerups["shield"] = 0
                            player.score += obstacle.points
                            obstacles.remove(obstacle)
                            continue
                    
                    if player.has_shield:
                        player.has_shield = False
                        player.powerups["shield"] = 0
                        obstacles.remove(obstacle)
                    else:
                        if player.take_damage():
                            game_over = True
        
        # 绘制
        draw_background(level_system)
        
        # 绘制云朵
        for cloud in clouds:
            cloud.draw(screen)
            
        # 绘制障碍物
        for obstacle in obstacles:
            obstacle.draw(screen)
            
        # 绘制道具
        for powerup in powerups:
            powerup.draw(screen)
            
        # 绘制玩家
        player.draw()
        
        # 绘制HUD
        draw_hud(player, level_system, game_speed)
        
        # 显示等级提升
        if level_up_just_happened:
            show_level_up(level_system.current_level)
        
        # 如果游戏结束，显示游戏结束画面
        if game_over:
            draw_game_over(player.score, player.coins, level_system.current_level)
            
        # 更新显示
        pygame.display.flip()
        clock.tick(FPS)
    
    return False

def show_start_screen():
    screen.fill(SKY_BLUE)
    
    # 绘制标题
    try:
        title = title_font.render("跑酷大冒险", True, PURPLE)
        subtitle = big_font.render("增强版", True, GOLD)
    except:
        title = title_font.render("Parkour Adventure", True, PURPLE)
        subtitle = big_font.render("Enhanced Edition", True, GOLD)
    
    # 绘制游戏说明
    instructions = [
        "游戏控制:",
        "空格键 - 跳跃 / 二段跳",
        "R键 - 重新开始游戏",
        "ESC键 - 退出游戏",
        "",
        "道具说明:",
        "黄色 - 二段跳 (在空中可再次跳跃)",
        "青色 - 护盾 (抵挡一次碰撞)",
        "粉色 - 磁铁 (自动吸附附近道具)",
        "金色 - 无敌 (短暂无敌时间)",
        "金币 - 收集增加金币数量",
        "",
        "游戏目标:",
        "躲避障碍物，收集金币和道具！",
        "生存越久，分数越高！",
        "",
        "按任意键开始游戏"
    ]
    
    # 绘制标题
    screen.blit(title, (SCREEN_WIDTH//2 - title.get_width()//2, 50))
    screen.blit(subtitle, (SCREEN_WIDTH//2 - subtitle.get_width()//2, 120))
    
    # 绘制说明
    y_pos = 200
    for i, line in enumerate(instructions):
        if line == "":
            y_pos += 20
            continue
            
        if line.startswith("游戏控制:") or line.startswith("道具说明:") or line.startswith("游戏目标:"):
            text_color = ORANGE
            text_font = font
        elif "按任意键" in line:
            text_color = RED
            text_font = big_font
        else:
            text_color = WHITE
            text_font = small_font
            
        if "黄色" in line:
            text_color = YELLOW
        elif "青色" in line:
            text_color = CYAN
        elif "粉色" in line:
            text_color = PINK
        elif "金色" in line or "金币" in line:
            text_color = GOLD
            
        try:
            text = text_font.render(line, True, text_color)
        except:
            # 如果字体渲染失败，使用英文
            if "游戏控制:" in line:
                line = "CONTROLS:"
            elif "空格键" in line:
                line = "SPACE - JUMP / DOUBLE JUMP"
            elif "R键" in line:
                line = "R - RESTART GAME"
            elif "ESC键" in line:
                line = "ESC - QUIT GAME"
            elif "道具说明:" in line:
                line = "POWER-UPS:"
            elif "黄色" in line:
                line = "YELLOW - DOUBLE JUMP"
            elif "青色" in line:
                line = "CYAN - SHIELD"
            elif "粉色" in line:
                line = "PINK - MAGNET"
            elif "金色" in line:
                line = "GOLD - INVINCIBILITY"
            elif "金币" in line:
                line = "GOLD COIN - Collect for points"
            elif "游戏目标:" in line:
                line = "OBJECTIVE:"
            elif "躲避障碍物" in line:
                line = "Avoid obstacles, collect items!"
            elif "生存越久" in line:
                line = "Survive as long as possible!"
            elif "按任意键" in line:
                line = "PRESS ANY KEY TO START"
                
            text = text_font.render(line, True, text_color)
        
        screen.blit(text, (SCREEN_WIDTH//2 - text.get_width()//2, y_pos))
        y_pos += 40 if "按任意键" in line or "PRESS ANY KEY" in line else 30
    
    pygame.display.flip()
    
    waiting = True
    while waiting:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type in (pygame.KEYDOWN, pygame.MOUSEBUTTONDOWN):
                waiting = False

# 游戏主循环
def game_loop():
    show_start_screen()
    
    while True:
        restart = main()
        if not restart:
            break
        # 如果main返回True，表示要重新开始，不显示开始画面直接进入游戏
        # 这样可以快速重新开始

game_loop()
pygame.quit()
sys.exit()