import pygame
import sys
import random
import math
from enum import Enum

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

# 窗口设置
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("是男人就上一百层")
clock = pygame.time.Clock()

# 颜色定义
SKY_BLUE = (135, 206, 235)        # 天空蓝
CLOUD_WHITE = (245, 245, 255)     # 云朵白
PLATFORM_BROWN = (139, 69, 19)    # 平台棕色
PLATFORM_GREEN = (60, 179, 113)   # 绿色平台
PLATFORM_RED = (220, 60, 60)      # 红色平台
PLATFORM_BLUE = (65, 105, 225)    # 蓝色平台
PLATFORM_GOLD = (255, 215, 0)     # 金色平台
PLAYER_RED = (220, 60, 60)        # 玩家红色
PLAYER_BLUE = (30, 144, 255)      # 玩家蓝色
TEXT_WHITE = (255, 255, 255)      # 白色文字
TEXT_BLACK = (20, 20, 20)         # 黑色文字
TEXT_GOLD = (255, 215, 0)         # 金色文字
UI_BG = (20, 20, 30, 200)         # UI背景
PARTICLE_COLOR = (255, 255, 200)  # 粒子颜色
DANGER_RED = (255, 50, 50, 150)   # 危险红色
SPRING_COLOR = (200, 200, 100)    # 弹簧颜色
JETPACK_COLOR = (255, 140, 0)     # 喷射器颜色
SHIELD_COLOR = (0, 191, 255, 100) # 护盾颜色

# 游戏常量
GRAVITY = 0.5
JUMP_FORCE = -12
MAX_FALL_SPEED = 15
PLAYER_WIDTH = 30
PLAYER_HEIGHT = 40
MIN_PLATFORM_WIDTH = 60
MAX_PLATFORM_WIDTH = 120
PLATFORM_HEIGHT = 20
MIN_PLATFORM_GAP = 80
MAX_PLATFORM_GAP = 150
CAMERA_SMOOTH = 0.1
INITIAL_PLATFORMS = 20
TARGET_FLOOR = 100
PARTICLE_COUNT = 50
FLOOR_HEIGHT = 30  # 每层高度

# 平台类型枚举
class PlatformType(Enum):
    NORMAL = 0      # 普通平台
    BOUNCY = 1      # 弹跳平台
    MOVING = 2      # 移动平台
    BREAKABLE = 3   # 易碎平台
    DISAPPEAR = 4   # 消失平台
    TRAMPOLINE = 5  # 蹦床平台
    CONVEYOR = 6    # 传送带平台
    SPIKE = 7       # 尖刺平台
    LAUNCH = 8      # 发射平台
    ICE = 9         # 冰面平台

# 道具类型枚举
class PowerUpType(Enum):
    NONE = 0
    SPRING = 1       # 弹簧鞋
    JETPACK = 2      # 喷射器
    SHIELD = 3       # 护盾
    MAGNET = 4       # 磁铁
    DOUBLE_JUMP = 5  # 二段跳
    SLOW_MO = 6      # 子弹时间
    ROCKET = 7       # 火箭推进

# 粒子类
class Particle:
    def __init__(self, x, y, color=PARTICLE_COLOR, particle_type="jump"):
        self.x = x
        self.y = y
        self.color = color
        self.type = particle_type
        
        if particle_type == "jump":
            self.vx = random.uniform(-2, 2)
            self.vy = random.uniform(-3, -1)
            self.size = random.randint(3, 6)
            self.life = random.randint(20, 40)
            self.gravity = 0.2
        elif particle_type == "land":
            self.vx = random.uniform(-1.5, 1.5)
            self.vy = random.uniform(-0.5, 0.5)
            self.size = random.randint(2, 4)
            self.life = random.randint(15, 30)
            self.gravity = 0.1
        elif particle_type == "trail":
            self.vx = random.uniform(-0.5, 0.5)
            self.vy = random.uniform(-0.3, 0.3)
            self.size = random.randint(2, 3)
            self.life = random.randint(10, 20)
            self.gravity = 0.05
        elif particle_type == "powerup":
            self.vx = random.uniform(-1, 1)
            self.vy = random.uniform(-2, 0)
            self.size = random.randint(4, 8)
            self.life = random.randint(30, 50)
            self.gravity = 0.1
        else:
            self.vx = random.uniform(-1, 1)
            self.vy = random.uniform(-1, 1)
            self.size = random.randint(2, 5)
            self.life = random.randint(20, 40)
            self.gravity = 0.15
    
    def update(self):
        self.x += self.vx
        self.y += self.vy
        self.vy += self.gravity
        self.life -= 1
        
        # 逐渐缩小
        self.size = max(0, self.size - 0.1)
        
        return self.life > 0 and self.size > 0
    
    def draw(self, screen, camera_y):
        screen_y = self.y - camera_y
        if 0 <= screen_y <= HEIGHT:
            alpha = min(255, self.life * 6)
            if self.type == "powerup":
                # 闪烁效果
                if (pygame.time.get_ticks() // 100) % 2 == 0:
                    color = self.color
                else:
                    color = (min(255, self.color[0] + 50), 
                            min(255, self.color[1] + 50), 
                            min(255, self.color[2] + 50))
                pygame.draw.circle(screen, color, 
                                 (int(self.x), int(screen_y)), 
                                 int(self.size))
            else:
                pygame.draw.circle(screen, self.color, 
                                 (int(self.x), int(screen_y)), 
                                 int(self.size))

# 平台类
class Platform:
    def __init__(self, x, y, width, platform_type=PlatformType.NORMAL):
        self.x = x
        self.y = y
        self.width = width
        self.height = PLATFORM_HEIGHT
        self.type = platform_type
        self.original_x = x
        self.original_y = y
        self.visible = True
        self.breaking = False
        self.break_timer = 0
        self.disappear_timer = 0
        self.move_direction = 1
        self.move_speed = random.uniform(0.5, 1.5)
        self.move_range = random.randint(50, 150)
        self.conveyor_speed = random.uniform(1, 2)
        self.bounce_factor = 1.5
        self.launch_power = 20
        self.ice_friction = 0.3
        self.collected = False
        self.animation_offset = 0
        self.animation_timer = 0
        
        # 设置平台颜色
        if self.type == PlatformType.NORMAL:
            self.color = PLATFORM_BROWN
        elif self.type == PlatformType.BOUNCY:
            self.color = PLATFORM_GREEN
        elif self.type == PlatformType.MOVING:
            self.color = (100, 100, 200)
        elif self.type == PlatformType.BREAKABLE:
            self.color = (160, 82, 45)
        elif self.type == PlatformType.DISAPPEAR:
            self.color = (200, 200, 200)
        elif self.type == PlatformType.TRAMPOLINE:
            self.color = (255, 165, 0)
        elif self.type == PlatformType.CONVEYOR:
            self.color = (169, 169, 169)
        elif self.type == PlatformType.SPIKE:
            self.color = (128, 128, 128)
        elif self.type == PlatformType.LAUNCH:
            self.color = (255, 69, 0)
        elif self.type == PlatformType.ICE:
            self.color = (173, 216, 230)
    
    def update(self):
        self.animation_timer += 1
        self.animation_offset = math.sin(self.animation_timer * 0.1) * 2
        
        if not self.visible:
            return
        
        # 更新移动平台
        if self.type == PlatformType.MOVING:
            self.x += self.move_direction * self.move_speed
            if abs(self.x - self.original_x) > self.move_range:
                self.move_direction *= -1
        
        # 更新消失平台计时器
        if self.type == PlatformType.DISAPPEAR and self.disappear_timer > 0:
            self.disappear_timer -= 1
            if self.disappear_timer <= 0:
                self.visible = False
        
        # 更新破碎平台
        if self.type == PlatformType.BREAKABLE and self.breaking:
            self.break_timer -= 1
            if self.break_timer <= 0:
                self.visible = False
    
    def draw(self, screen, camera_y):
        if not self.visible:
            return
        
        screen_y = self.y - camera_y + self.animation_offset
        
        # 只在屏幕内绘制
        if screen_y < -PLATFORM_HEIGHT or screen_y > HEIGHT:
            return
        
        # 绘制平台主体
        platform_rect = pygame.Rect(int(self.x), int(screen_y), 
                                  int(self.width), int(self.height))
        pygame.draw.rect(screen, self.color, platform_rect, border_radius=4)
        
        # 绘制平台边框
        border_color = (max(0, self.color[0] - 30), 
                       max(0, self.color[1] - 30), 
                       max(0, self.color[2] - 30))
        pygame.draw.rect(screen, border_color, platform_rect, 2, border_radius=4)
        
        # 绘制平台图案
        if self.type == PlatformType.BOUNCY:
            # 弹跳平台箭头
            arrow_y = screen_y + self.height // 2
            for i in range(3):
                arrow_x = self.x + self.width // 4 + i * 20
                pygame.draw.polygon(screen, (255, 255, 255), [
                    (arrow_x, arrow_y),
                    (arrow_x + 10, arrow_y - 5),
                    (arrow_x + 10, arrow_y + 5)
                ])
        
        elif self.type == PlatformType.MOVING:
            # 移动平台箭头
            arrow_x = self.x + self.width // 2
            arrow_y = screen_y + self.height // 2
            if self.move_direction > 0:
                pygame.draw.polygon(screen, (255, 255, 255), [
                    (arrow_x, arrow_y),
                    (arrow_x - 8, arrow_y - 5),
                    (arrow_x - 8, arrow_y + 5)
                ])
            else:
                pygame.draw.polygon(screen, (255, 255, 255), [
                    (arrow_x, arrow_y),
                    (arrow_x + 8, arrow_y - 5),
                    (arrow_x + 8, arrow_y + 5)
                ])
        
        elif self.type == PlatformType.BREAKABLE:
            # 易碎平台裂缝
            if self.breaking:
                # 闪烁效果
                if (pygame.time.get_ticks() // 100) % 2 == 0:
                    crack_color = (255, 100, 100)
                else:
                    crack_color = (255, 200, 200)
            else:
                crack_color = (100, 50, 0)
            
            for i in range(3):
                crack_x = self.x + random.randint(10, int(self.width) - 10)
                crack_length = random.randint(5, 15)
                pygame.draw.line(screen, crack_color,
                               (crack_x, screen_y + 5),
                               (crack_x, screen_y + self.height - 5), 2)
        
        elif self.type == PlatformType.DISAPPEAR:
            # 消失平台虚线边框
            if self.visible:
                dash_length = 8
                for i in range(0, int(self.width), dash_length * 2):
                    start_x = self.x + i
                    end_x = min(self.x + i + dash_length, self.x + self.width)
                    pygame.draw.line(screen, (100, 100, 100),
                                   (start_x, screen_y),
                                   (end_x, screen_y), 2)
                    pygame.draw.line(screen, (100, 100, 100),
                                   (start_x, screen_y + self.height),
                                   (end_x, screen_y + self.height), 2)
        
        elif self.type == PlatformType.TRAMPOLINE:
            # 蹦床弹簧
            spring_y = screen_y + self.height
            for i in range(5):
                spring_x = self.x + i * (self.width // 5)
                pygame.draw.arc(screen, SPRING_COLOR,
                              (spring_x, spring_y - 5, 10, 10),
                              0, math.pi, 2)
        
        elif self.type == PlatformType.CONVEYOR:
            # 传送带箭头
            arrow_y = screen_y + self.height // 2
            arrow_spacing = 20
            for i in range(int(self.width // arrow_spacing)):
                arrow_x = self.x + i * arrow_spacing + 10
                if self.conveyor_speed > 0:
                    pygame.draw.polygon(screen, (50, 50, 50), [
                        (arrow_x, arrow_y),
                        (arrow_x - 6, arrow_y - 4),
                        (arrow_x - 6, arrow_y + 4)
                    ])
                else:
                    pygame.draw.polygon(screen, (50, 50, 50), [
                        (arrow_x, arrow_y),
                        (arrow_x + 6, arrow_y - 4),
                        (arrow_x + 6, arrow_y + 4)
                    ])
        
        elif self.type == PlatformType.SPIKE:
            # 尖刺
            spike_count = 6
            spike_width = self.width / spike_count
            for i in range(spike_count):
                spike_x = self.x + i * spike_width + spike_width / 2
                pygame.draw.polygon(screen, (255, 50, 50), [
                    (spike_x, screen_y),
                    (spike_x - spike_width/3, screen_y + self.height),
                    (spike_x + spike_width/3, screen_y + self.height)
                ])
        
        elif self.type == PlatformType.LAUNCH:
            # 发射平台火焰效果
            flame_height = 10 + math.sin(pygame.time.get_ticks() * 0.01) * 5
            flame_points = [
                (self.x + self.width/2, screen_y + self.height),
                (self.x + self.width/2 - 10, screen_y + self.height + flame_height),
                (self.x + self.width/2 + 10, screen_y + self.height + flame_height)
            ]
            pygame.draw.polygon(screen, (255, 165, 0), flame_points)
            pygame.draw.polygon(screen, (255, 215, 0), flame_points, 1)
        
        elif self.type == PlatformType.ICE:
            # 冰面反光
            ice_highlight = pygame.Rect(self.x + 5, screen_y + 5, 
                                      self.width - 10, 5)
            pygame.draw.rect(screen, (255, 255, 255, 100), ice_highlight, 
                           border_radius=2)
    
    def get_jump_force(self):
        """获取平台的跳跃力"""
        if self.type == PlatformType.BOUNCY:
            return JUMP_FORCE * self.bounce_factor
        elif self.type == PlatformType.TRAMPOLINE:
            return JUMP_FORCE * 2.0
        elif self.type == PlatformType.LAUNCH:
            return -self.launch_power
        else:
            return JUMP_FORCE
    
    def trigger_effect(self):
        """触发平台效果"""
        if self.type == PlatformType.BREAKABLE and not self.breaking:
            self.breaking = True
            self.break_timer = 30
        elif self.type == PlatformType.DISAPPEAR and self.visible:
            self.disappear_timer = 60

# 道具类
class PowerUp:
    def __init__(self, x, y, powerup_type):
        self.x = x
        self.y = y
        self.width = 20
        self.height = 20
        self.type = powerup_type
        self.collected = False
        self.animation_offset = 0
        self.animation_timer = 0
        
        # 设置道具颜色
        if self.type == PowerUpType.SPRING:
            self.color = SPRING_COLOR
            self.name = "弹簧鞋"
            self.duration = 300
        elif self.type == PowerUpType.JETPACK:
            self.color = JETPACK_COLOR
            self.name = "喷射器"
            self.duration = 400
        elif self.type == PowerUpType.SHIELD:
            self.color = SHIELD_COLOR[:3]
            self.name = "护盾"
            self.duration = 500
        elif self.type == PowerUpType.MAGNET:
            self.color = (255, 0, 255)
            self.name = "磁铁"
            self.duration = 400
        elif self.type == PowerUpType.DOUBLE_JUMP:
            self.color = (0, 255, 255)
            self.name = "二段跳"
            self.duration = 0  # 永久效果直到使用
        elif self.type == PowerUpType.SLOW_MO:
            self.color = (100, 255, 100)
            self.name = "子弹时间"
            self.duration = 300
        elif self.type == PowerUpType.ROCKET:
            self.color = (255, 100, 100)
            self.name = "火箭推进"
            self.duration = 200
    
    def update(self):
        self.animation_timer += 1
        self.animation_offset = math.sin(self.animation_timer * 0.1) * 3
    
    def draw(self, screen, camera_y):
        if self.collected:
            return
        
        screen_y = self.y - camera_y + self.animation_offset
        
        if screen_y < -self.height or screen_y > HEIGHT:
            return
        
        # 绘制道具
        center_x = self.x + self.width // 2
        center_y = screen_y + self.height // 2
        
        # 绘制闪烁效果
        if (pygame.time.get_ticks() // 200) % 2 == 0:
            glow_color = (min(255, self.color[0] + 50), 
                         min(255, self.color[1] + 50), 
                         min(255, self.color[2] + 50))
        else:
            glow_color = self.color
        
        # 绘制外圈
        pygame.draw.circle(screen, glow_color, (int(center_x), int(center_y)), 
                         self.width // 2 + 2)
        
        # 绘制内圈
        pygame.draw.circle(screen, self.color, (int(center_x), int(center_y)), 
                         self.width // 2)
        
        # 绘制道具图标
        if self.type == PowerUpType.SPRING:
            # 弹簧图标
            pygame.draw.rect(screen, (255, 255, 255), 
                           (center_x - 4, center_y - 8, 8, 16), 2)
        elif self.type == PowerUpType.JETPACK:
            # 喷射器图标
            pygame.draw.rect(screen, (255, 255, 255), 
                           (center_x - 6, center_y - 4, 12, 8))
            # 火焰
            pygame.draw.polygon(screen, (255, 165, 0), [
                (center_x, center_y + 4),
                (center_x - 4, center_y + 10),
                (center_x + 4, center_y + 10)
            ])
        elif self.type == PowerUpType.SHIELD:
            # 护盾图标
            pygame.draw.circle(screen, (255, 255, 255), 
                             (int(center_x), int(center_y)), 6, 2)
        elif self.type == PowerUpType.MAGNET:
            # 磁铁图标
            pygame.draw.circle(screen, (255, 255, 255), 
                             (int(center_x - 3), int(center_y)), 3)
            pygame.draw.circle(screen, (255, 255, 255), 
                             (int(center_x + 3), int(center_y)), 3)
        elif self.type == PowerUpType.DOUBLE_JUMP:
            # 双跳图标
            pygame.draw.circle(screen, (255, 255, 255), 
                             (int(center_x - 3), int(center_y - 3)), 2)
            pygame.draw.circle(screen, (255, 255, 255), 
                             (int(center_x + 3), int(center_y + 3)), 2)
        elif self.type == PowerUpType.SLOW_MO:
            # 子弹时间图标
            pygame.draw.circle(screen, (255, 255, 255), 
                             (int(center_x), int(center_y)), 4)
            for i in range(4):
                angle = i * math.pi / 2
                pygame.draw.line(screen, (255, 255, 255),
                               (center_x, center_y),
                               (center_x + math.cos(angle) * 8,
                                center_y + math.sin(angle) * 8), 2)
        elif self.type == PowerUpType.ROCKET:
            # 火箭图标
            pygame.draw.polygon(screen, (255, 255, 255), [
                (center_x, center_y - 6),
                (center_x - 4, center_y + 6),
                (center_x + 4, center_y + 6)
            ])

# 玩家类
class Player:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.width = PLAYER_WIDTH
        self.height = PLAYER_HEIGHT
        self.vx = 0
        self.vy = 0
        self.is_jumping = False
        self.on_ground = False
        self.facing_right = True
        self.score = 0
        self.highest_y = y
        self.current_floor = 0
        self.lives = 3
        self.invincible = 0
        self.particles = []
        
        # 道具系统
        self.powerups = {}
        self.active_powerups = {}
        self.jumps_left = 1
        self.has_shield = False
        self.shield_timer = 0
        self.jetpack_active = False
        self.jetpack_timer = 0
        self.spring_active = False
        self.spring_timer = 0
        self.magnet_active = False
        self.magnet_timer = 0
        self.slow_mo_active = False
        self.slow_mo_timer = 0
        self.rocket_active = False
        self.rocket_timer = 0
        
        # 动画
        self.animation_timer = 0
        self.walk_frame = 0
        self.squash_stretch = 1.0
        
    def update(self, keys, platforms, powerups, camera_y):
        # 更新无敌时间
        if self.invincible > 0:
            self.invincible -= 1
        
        # 更新道具时间
        self.update_powerups()
        
        # 处理输入
        self.handle_input(keys)
        
        # 应用物理
        self.apply_physics()
        
        # 检查碰撞
        self.check_collisions(platforms, powerups, camera_y)
        
        # 更新最高位置
        if self.y < self.highest_y:
            self.highest_y = self.y
            self.current_floor = int(abs(self.highest_y) / FLOOR_HEIGHT)
            self.score = self.current_floor * 10
        
        # 更新动画
        self.animation_timer += 1
        if abs(self.vx) > 0.5:
            self.walk_frame = (self.walk_frame + 1) % 20
        
        # 更新粒子
        self.update_particles()
        
        # 恢复形状
        self.squash_stretch += (1.0 - self.squash_stretch) * 0.2
    
    def handle_input(self, keys):
        # 水平移动
        move_speed = 4
        if self.slow_mo_active:
            move_speed *= 0.7
        
        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            self.vx = -move_speed
            self.facing_right = False
        elif keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            self.vx = move_speed
            self.facing_right = True
        else:
            # 摩擦
            self.vx *= 0.8
        
        # 跳跃
        if (keys[pygame.K_SPACE] or keys[pygame.K_UP] or keys[pygame.K_w]) and not self.is_jumping:
            if self.on_ground or self.jumps_left > 0:
                self.jump()
        
        # 持续跳跃（喷射器）
        if self.jetpack_active and (keys[pygame.K_SPACE] or keys[pygame.K_UP] or keys[pygame.K_w]):
            self.vy = max(-8, self.vy - 0.3)
        
        # 火箭推进
        if self.rocket_active and (keys[pygame.K_SPACE] or keys[pygame.K_UP] or keys[pygame.K_w]):
            self.vy = -12
            # 添加推进粒子
            for _ in range(3):
                self.particles.append(Particle(
                    self.x + self.width // 2 + random.uniform(-5, 5),
                    self.y + self.height,
                    (255, 100, 0),
                    "powerup"
                ))
    
    def jump(self):
        jump_force = JUMP_FORCE
        if self.spring_active:
            jump_force *= 1.5
        
        self.vy = jump_force
        self.is_jumping = True
        self.on_ground = False
        self.jumps_left -= 1
        
        # 跳跃粒子效果
        for _ in range(10):
            self.particles.append(Particle(
                self.x + self.width // 2 + random.uniform(-10, 10),
                self.y + self.height,
                PARTICLE_COLOR,
                "jump"
            ))
    
    def apply_physics(self):
        # 应用重力
        if not self.jetpack_active or not (pygame.key.get_pressed()[pygame.K_SPACE] or 
                                          pygame.key.get_pressed()[pygame.K_UP] or 
                                          pygame.key.get_pressed()[pygame.K_w]):
            self.vy += GRAVITY
        
        # 限制下落速度
        self.vy = min(self.vy, MAX_FALL_SPEED)
        
        # 更新位置
        self.x += self.vx
        self.y += self.vy
        
        # 屏幕边界检查
        if self.x < 0:
            self.x = 0
            self.vx = 0
        elif self.x > WIDTH - self.width:
            self.x = WIDTH - self.width
            self.vx = 0
        
        # 如果掉出屏幕底部，损失生命
        if self.y - self.height > HEIGHT:
            self.take_damage()
    
    def check_collisions(self, platforms, powerups, camera_y):
        self.on_ground = False
        
        # 检查平台碰撞
        for platform in platforms:
            if not platform.visible:
                continue
            
            # 粗略碰撞检测
            if (self.x < platform.x + platform.width and
                self.x + self.width > platform.x and
                self.y + self.height > platform.y and
                self.y < platform.y + platform.height):
                
                # 精确碰撞检测：从上方落下
                if (self.vy > 0 and 
                    self.y + self.height - self.vy <= platform.y + 5):
                    
                    # 尖刺平台造成伤害
                    if platform.type == PlatformType.SPIKE:
                        if not self.has_shield:
                            self.take_damage()
                        platform.trigger_effect()
                        continue
                    
                    # 站在平台上
                    self.y = platform.y - self.height
                    self.vy = 0
                    self.on_ground = True
                    self.is_jumping = False
                    self.jumps_left = 1
                    
                    # 触发平台效果
                    jump_force = platform.get_jump_force()
                    self.vy = jump_force
                    
                    # 落地粒子效果
                    for _ in range(8):
                        self.particles.append(Particle(
                            self.x + self.width // 2 + random.uniform(-15, 15),
                            self.y + self.height,
                            platform.color,
                            "land"
                        ))
                    
                    # 触发平台特效
                    platform.trigger_effect()
                    
                    # 跳跃变形效果
                    self.squash_stretch = 0.8
                    
                    break
        
        # 检查道具碰撞
        for powerup in powerups:
            if (not powerup.collected and
                self.x < powerup.x + powerup.width and
                self.x + self.width > powerup.x and
                self.y < powerup.y + powerup.height and
                self.y + self.height > powerup.y):
                
                self.collect_powerup(powerup)
    
    def collect_powerup(self, powerup):
        powerup.collected = True
        self.score += 50
        
        # 激活道具
        if powerup.type != PowerUpType.NONE:
            self.active_powerups[powerup.type] = powerup.duration
            
            if powerup.type == PowerUpType.SHIELD:
                self.has_shield = True
                self.shield_timer = powerup.duration
            elif powerup.type == PowerUpType.JETPACK:
                self.jetpack_active = True
                self.jetpack_timer = powerup.duration
            elif powerup.type == PowerUpType.SPRING:
                self.spring_active = True
                self.spring_timer = powerup.duration
            elif powerup.type == PowerUpType.MAGNET:
                self.magnet_active = True
                self.magnet_timer = powerup.duration
            elif powerup.type == PowerUpType.DOUBLE_JUMP:
                self.jumps_left = 2
            elif powerup.type == PowerUpType.SLOW_MO:
                self.slow_mo_active = True
                self.slow_mo_timer = powerup.duration
            elif powerup.type == PowerUpType.ROCKET:
                self.rocket_active = True
                self.rocket_timer = powerup.duration
        
        # 收集粒子效果
        for _ in range(20):
            self.particles.append(Particle(
                powerup.x + powerup.width // 2,
                powerup.y + powerup.height // 2,
                powerup.color,
                "powerup"
            ))
    
    def update_powerups(self):
        # 更新护盾
        if self.has_shield:
            self.shield_timer -= 1
            if self.shield_timer <= 0:
                self.has_shield = False
        
        # 更新喷射器
        if self.jetpack_active:
            self.jetpack_timer -= 1
            if self.jetpack_timer <= 0:
                self.jetpack_active = False
        
        # 更新弹簧鞋
        if self.spring_active:
            self.spring_timer -= 1
            if self.spring_timer <= 0:
                self.spring_active = False
        
        # 更新磁铁
        if self.magnet_active:
            self.magnet_timer -= 1
            if self.magnet_timer <= 0:
                self.magnet_active = False
        
        # 更新子弹时间
        if self.slow_mo_active:
            self.slow_mo_timer -= 1
            if self.slow_mo_timer <= 0:
                self.slow_mo_active = False
        
        # 更新火箭推进
        if self.rocket_active:
            self.rocket_timer -= 1
            if self.rocket_timer <= 0:
                self.rocket_active = False
        
        # 移除过期道具
        expired = [p for p, t in self.active_powerups.items() if t <= 0]
        for p in expired:
            del self.active_powerups[p]
    
    def update_particles(self):
        # 更新所有粒子
        self.particles = [p for p in self.particles if p.update()]
        
        # 添加移动轨迹粒子
        if abs(self.vx) > 1 and self.on_ground:
            if random.random() < 0.3:
                self.particles.append(Particle(
                    self.x + random.uniform(0, self.width),
                    self.y + self.height,
                    (200, 200, 200),
                    "trail"
                ))
    
    def take_damage(self):
        if self.invincible > 0:
            return
        
        if self.has_shield:
            self.has_shield = False
            self.shield_timer = 0
            self.invincible = 30
        else:
            self.lives -= 1
            self.invincible = 60
            
            # 受伤粒子效果
            for _ in range(30):
                self.particles.append(Particle(
                    self.x + self.width // 2,
                    self.y + self.height // 2,
                    (255, 50, 50),
                    "jump"
                ))
    
    def draw(self, screen, camera_y):
        screen_y = self.y - camera_y
        
        # 绘制玩家
        player_rect = pygame.Rect(
            int(self.x),
            int(screen_y),
            int(self.width * (1.2 if not self.facing_right and self.vx < -1 else 1.0)),
            int(self.height * self.squash_stretch)
        )
        
        # 玩家颜色
        player_color = PLAYER_RED
        if self.invincible > 0 and (pygame.time.get_ticks() // 100) % 2 == 0:
            player_color = (255, 255, 255)  # 无敌闪烁
        
        # 绘制玩家身体
        pygame.draw.rect(screen, player_color, player_rect, border_radius=8)
        
        # 绘制玩家细节
        eye_x = self.x + (self.width * 0.7 if self.facing_right else self.width * 0.3)
        eye_y = screen_y + self.height * 0.4
        pygame.draw.circle(screen, (255, 255, 255), (int(eye_x), int(eye_y)), 4)
        pygame.draw.circle(screen, (0, 0, 0), (int(eye_x), int(eye_y)), 2)
        
        # 绘制嘴巴
        mouth_y = screen_y + self.height * 0.7
        if self.on_ground:
            # 微笑
            pygame.draw.arc(screen, (0, 0, 0),
                          (self.x + self.width * 0.3, mouth_y - 5, 
                           self.width * 0.4, 10),
                          0, math.pi, 2)
        else:
            # 惊讶
            pygame.draw.circle(screen, (0, 0, 0), 
                             (int(self.x + self.width // 2), int(mouth_y)), 3)
        
        # 绘制护盾
        if self.has_shield:
            shield_radius = self.width // 2 + 5
            shield_alpha = 100 + int(math.sin(pygame.time.get_ticks() * 0.01) * 50)
            shield_surface = pygame.Surface((shield_radius * 2, shield_radius * 2), pygame.SRCALPHA)
            pygame.draw.circle(shield_surface, (*SHIELD_COLOR[:3], shield_alpha),
                             (shield_radius, shield_radius), shield_radius, 3)
            screen.blit(shield_surface, 
                       (int(self.x + self.width // 2 - shield_radius),
                        int(screen_y + self.height // 2 - shield_radius)))
        
        # 绘制喷射器效果
        if self.jetpack_active:
            # 绘制喷射器
            jetpack_y = screen_y + self.height
            flame_height = 15 + math.sin(pygame.time.get_ticks() * 0.02) * 5
            flame_points = [
                (self.x + self.width // 2, jetpack_y),
                (self.x + self.width // 2 - 8, jetpack_y + flame_height),
                (self.x + self.width // 2 + 8, jetpack_y + flame_height)
            ]
            pygame.draw.polygon(screen, (255, 165, 0), flame_points)
            pygame.draw.polygon(screen, (255, 215, 0), flame_points, 1)
        
        # 绘制弹簧鞋
        if self.spring_active:
            spring_rect = pygame.Rect(self.x, screen_y + self.height - 5, 
                                    self.width, 5)
            pygame.draw.rect(screen, SPRING_COLOR, spring_rect)
        
        # 绘制粒子
        for particle in self.particles:
            particle.draw(screen, camera_y)

# 游戏主类
class HundredFloorsGame:
    def __init__(self):
        self.player = Player(WIDTH // 2, HEIGHT - 200)
        self.platforms = []
        self.powerups = []
        self.camera_y = 0
        self.game_state = "playing"  # playing, game_over, victory
        self.score = 0
        self.highest_floor = 0
        self.particles = []
        self.platform_spawn_timer = 0
        self.powerup_spawn_timer = 0
        self.difficulty = 1.0
        
        # 字体
        self.font_large = pygame.font.Font(None, 48)
        self.font_medium = pygame.font.Font(None, 32)
        self.font_small = pygame.font.Font(None, 24)
        
        # 生成初始平台
        self.generate_initial_platforms()
        
        # 音效
        self.load_sounds()
    
    def load_sounds(self):
        """加载音效（占位，实际需要音效文件）"""
        pass
    
    def generate_initial_platforms(self):
        """生成初始平台"""
        # 起始平台
        start_platform = Platform(WIDTH // 2 - 60, HEIGHT - 100, 120, PlatformType.NORMAL)
        self.platforms.append(start_platform)
        
        # 生成初始平台
        current_y = HEIGHT - 150
        for _ in range(INITIAL_PLATFORMS):
            self.spawn_platform(current_y)
            current_y -= random.randint(MIN_PLATFORM_GAP, MAX_PLATFORM_GAP)
    
    def spawn_platform(self, y):
        """生成单个平台"""
        platform_width = random.randint(MIN_PLATFORM_WIDTH, MAX_PLATFORM_WIDTH)
        x = random.randint(20, WIDTH - platform_width - 20)
        
        # 随机选择平台类型
        platform_types = [
            PlatformType.NORMAL,
            PlatformType.BOUNCY,
            PlatformType.MOVING,
            PlatformType.BREAKABLE,
            PlatformType.DISAPPEAR,
            PlatformType.TRAMPOLINE,
            PlatformType.CONVEYOR,
            PlatformType.SPIKE,
            PlatformType.LAUNCH,
            PlatformType.ICE
        ]
        
        # 根据难度调整平台类型概率
        weights = [30, 10, 8, 5, 5, 3, 4, 2, 2, 1]
        
        # 随着高度增加难度
        floor = int(abs(y) / FLOOR_HEIGHT)
        if floor > 50:
            weights[3] += 5  # 增加易碎平台
            weights[4] += 5  # 增加消失平台
            weights[7] += 3  # 增加尖刺平台
        
        platform_type = random.choices(platform_types, weights=weights, k=1)[0]
        
        platform = Platform(x, y, platform_width, platform_type)
        self.platforms.append(platform)
        
        # 随机生成道具
        if random.random() < 0.1:  # 10%概率生成道具
            self.spawn_powerup(x + platform_width // 2, y - 30)
    
    def spawn_powerup(self, x, y):
        """生成道具"""
        powerup_types = [
            PowerUpType.SPRING,
            PowerUpType.JETPACK,
            PowerUpType.SHIELD,
            PowerUpType.MAGNET,
            PowerUpType.DOUBLE_JUMP,
            PowerUpType.SLOW_MO,
            PowerUpType.ROCKET
        ]
        
        weights = [20, 15, 15, 10, 10, 10, 10]
        powerup_type = random.choices(powerup_types, weights=weights, k=1)[0]
        
        powerup = PowerUp(x - 10, y, powerup_type)
        self.powerups.append(powerup)
    
    def update(self):
        if self.game_state != "playing":
            return
        
        # 获取按键
        keys = pygame.key.get_pressed()
        
        # 更新玩家
        self.player.update(keys, self.platforms, self.powerups, self.camera_y)
        
        # 更新平台
        for platform in self.platforms:
            platform.update()
        
        # 更新道具
        for powerup in self.powerups:
            powerup.update()
        
        # 更新相机
        self.update_camera()
        
        # 生成新平台
        self.spawn_new_platforms()
        
        # 清理超出屏幕的平台
        self.cleanup_objects()
        
        # 更新游戏状态
        self.update_game_state()
        
        # 更新难度
        self.update_difficulty()
    
    def update_camera(self):
        """更新相机位置"""
        target_y = self.player.y - HEIGHT * 0.3
        
        # 平滑跟随
        self.camera_y += (target_y - self.camera_y) * CAMERA_SMOOTH
        
        # 限制相机位置
        self.camera_y = min(self.camera_y, 0)
    
    def spawn_new_platforms(self):
        """生成新平台"""
        # 找到最高的平台
        highest_platform = min(self.platforms, key=lambda p: p.y) if self.platforms else None
        
        if highest_platform:
            # 如果最高平台在屏幕上方，生成新平台
            screen_top = self.camera_y
            if highest_platform.y > screen_top - 200:
                self.spawn_platform(highest_platform.y - random.randint(MIN_PLATFORM_GAP, MAX_PLATFORM_GAP))
    
    def cleanup_objects(self):
        """清理超出屏幕的对象"""
        # 清理平台
        self.platforms = [p for p in self.platforms 
                         if p.y < self.camera_y + HEIGHT + 200 and p.visible]
        
        # 清理道具
        self.powerups = [p for p in self.powerups 
                        if p.y < self.camera_y + HEIGHT + 100 and not p.collected]
    
    def update_game_state(self):
        """更新游戏状态"""
        # 检查生命值
        if self.player.lives <= 0:
            self.game_state = "game_over"
        
        # 检查是否到达100层
        if self.player.current_floor >= TARGET_FLOOR:
            self.game_state = "victory"
            self.score = self.player.score + 1000  # 通关奖励
    
    def update_difficulty(self):
        """更新游戏难度"""
        floor = self.player.current_floor
        self.difficulty = 1.0 + floor * 0.01
        
        # 调整平台生成参数
        global MIN_PLATFORM_GAP, MAX_PLATFORM_GAP
        MIN_PLATFORM_GAP = max(50, 80 - floor * 0.5)
        MAX_PLATFORM_GAP = max(100, 150 - floor * 0.8)
    
    def handle_event(self, event):
        """处理事件"""
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_r and self.game_state != "playing":
                self.__init__()  # 重新开始游戏
            elif event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()
    
    def draw(self, screen):
        """绘制游戏"""
        # 绘制天空背景
        self.draw_background(screen)
        
        # 绘制所有平台
        for platform in self.platforms:
            platform.draw(screen, self.camera_y)
        
        # 绘制所有道具
        for powerup in self.powerups:
            powerup.draw(screen, self.camera_y)
        
        # 绘制玩家
        self.player.draw(screen, self.camera_y)
        
        # 绘制UI
        self.draw_ui(screen)
        
        # 绘制游戏结束画面
        if self.game_state == "game_over":
            self.draw_game_over(screen)
        elif self.game_state == "victory":
            self.draw_victory(screen)
    
    def draw_background(self, screen):
        """绘制背景"""
        # 渐变天空
        for y in range(0, HEIGHT, 2):
            progress = y / HEIGHT
            r = int(SKY_BLUE[0] * (1 - progress) + 10 * progress)
            g = int(SKY_BLUE[1] * (1 - progress) + 20 * progress)
            b = int(SKY_BLUE[2] * (1 - progress) + 30 * progress)
            pygame.draw.line(screen, (r, g, b), (0, y), (WIDTH, y))
        
        # 绘制云朵
        for i in range(5):
            cloud_x = (pygame.time.get_ticks() * 0.02 + i * 200) % (WIDTH + 400) - 200
            cloud_y = 50 + i * 60
            cloud_y_screen = cloud_y - self.camera_y * 0.3
            
            if 0 <= cloud_y_screen <= HEIGHT:
                for j in range(3):
                    pygame.draw.circle(screen, CLOUD_WHITE,
                                     (int(cloud_x + j * 30), int(cloud_y_screen)), 20)
                pygame.draw.ellipse(screen, CLOUD_WHITE,
                                  (cloud_x, cloud_y_screen - 15, 90, 30))
        
        # 绘制楼层指示线
        for i in range(0, 1000, FLOOR_HEIGHT):
            line_y = i - self.camera_y
            if 0 <= line_y <= HEIGHT:
                alpha = 50 + int(math.sin(i * 0.1 + pygame.time.get_ticks() * 0.001) * 20)
                line_color = (255, 255, 255, alpha)
                
                # 每10层加粗显示
                if i % (FLOOR_HEIGHT * 10) == 0:
                    pygame.draw.line(screen, (255, 255, 255, 100),
                                   (0, line_y), (WIDTH, line_y), 3)
                    
                    # 显示楼层数
                    floor_num = i // FLOOR_HEIGHT
                    floor_text = self.font_small.render(f"{floor_num}F", True, (255, 255, 255, 150))
                    screen.blit(floor_text, (10, line_y - 15))
                else:
                    pygame.draw.line(screen, (255, 255, 255, 30),
                                   (0, line_y), (WIDTH, line_y), 1)
    
    def draw_ui(self, screen):
        """绘制用户界面"""
        # 绘制半透明背景
        ui_bg = pygame.Surface((WIDTH, 100), pygame.SRCALPHA)
        ui_bg.fill((0, 0, 0, 100))
        screen.blit(ui_bg, (0, 0))
        
        # 绘制分数
        score_text = self.font_medium.render(f"分数: {self.player.score}", True, TEXT_WHITE)
        screen.blit(score_text, (20, 20))
        
        # 绘制当前楼层
        floor_text = self.font_medium.render(f"楼层: {self.player.current_floor}/{TARGET_FLOOR}", True, TEXT_WHITE)
        screen.blit(floor_text, (20, 50))
        
        # 绘制生命值
        lives_text = self.font_medium.render(f"生命: {self.player.lives}", True, 
                                           (255, 100, 100) if self.player.lives == 1 else TEXT_WHITE)
        screen.blit(lives_text, (WIDTH - 120, 20))
        
        # 绘制最高记录
        if self.player.current_floor > self.highest_floor:
            self.highest_floor = self.player.current_floor
        highest_text = self.font_small.render(f"最高: {self.highest_floor}层", True, TEXT_GOLD)
        screen.blit(highest_text, (WIDTH - 120, 50))
        
        # 绘制道具状态
        y_offset = HEIGHT - 30
        active_powerups = [p for p, t in self.player.active_powerups.items() if t > 0]
        
        for i, powerup_type in enumerate(active_powerups[:5]):  # 最多显示5个
            duration = self.player.active_powerups[powerup_type]
            
            # 道具颜色
            if powerup_type == PowerUpType.SPRING:
                color = SPRING_COLOR
                name = "弹簧"
            elif powerup_type == PowerUpType.JETPACK:
                color = JETPACK_COLOR
                name = "喷射"
            elif powerup_type == PowerUpType.SHIELD:
                color = SHIELD_COLOR[:3]
                name = "护盾"
            elif powerup_type == PowerUpType.MAGNET:
                color = (255, 0, 255)
                name = "磁铁"
            elif powerup_type == PowerUpType.DOUBLE_JUMP:
                color = (0, 255, 255)
                name = "二段跳"
            elif powerup_type == PowerUpType.SLOW_MO:
                color = (100, 255, 100)
                name = "慢动作"
            elif powerup_type == PowerUpType.ROCKET:
                color = (255, 100, 100)
                name = "火箭"
            else:
                color = (200, 200, 200)
                name = "道具"
            
            # 绘制道具条
            bar_width = 60
            bar_height = 20
            bar_x = 20 + i * 70
            bar_y = y_offset
            
            # 背景
            pygame.draw.rect(screen, (50, 50, 50), 
                           (bar_x, bar_y, bar_width, bar_height), border_radius=3)
            
            # 进度条
            progress = duration / 300  # 假设最大持续时间为300帧
            fill_width = max(2, int(bar_width * progress))
            pygame.draw.rect(screen, color, 
                           (bar_x, bar_y, fill_width, bar_height), border_radius=3)
            
            # 边框
            pygame.draw.rect(screen, (200, 200, 200), 
                           (bar_x, bar_y, bar_width, bar_height), 1, border_radius=3)
            
            # 道具名称
            name_text = self.font_small.render(name, True, TEXT_WHITE)
            screen.blit(name_text, (bar_x + bar_width//2 - name_text.get_width()//2, bar_y - 15))
        
        # 绘制控制提示
        controls = [
            "控制: ←→/AD移动, 空格/W/↑跳跃, R重新开始, ESC退出"
        ]
        
        for i, text in enumerate(controls):
            control_text = self.font_small.render(text, True, (200, 200, 200))
            screen.blit(control_text, (WIDTH//2 - control_text.get_width()//2, HEIGHT - 25))
    
    def draw_game_over(self, screen):
        """绘制游戏结束画面"""
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 150))
        screen.blit(overlay, (0, 0))
        
        # 游戏结束文字
        game_over_text = self.font_large.render("游戏结束!", True, (255, 50, 50))
        final_score_text = self.font_medium.render(f"最终分数: {self.player.score}", True, TEXT_WHITE)
        highest_floor_text = self.font_medium.render(f"到达楼层: {self.player.current_floor}", True, TEXT_GOLD)
        restart_text = self.font_medium.render("按 R 键重新开始", True, (100, 255, 100))
        quit_text = self.font_medium.render("按 ESC 键退出", True, (200, 200, 200))
        
        texts = [game_over_text, final_score_text, highest_floor_text, restart_text, quit_text]
        y_start = HEIGHT // 2 - len(texts) * 20
        
        for i, text in enumerate(texts):
            screen.blit(text, (WIDTH//2 - text.get_width()//2, y_start + i * 50))
    
    def draw_victory(self, screen):
        """绘制胜利画面"""
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 150))
        screen.blit(overlay, (0, 0))
        
        # 胜利文字
        victory_text = self.font_large.render("恭喜通关!", True, TEXT_GOLD)
        congrats_text = self.font_medium.render("是男人就上一百层!", True, (100, 255, 255))
        final_score_text = self.font_medium.render(f"最终分数: {self.score}", True, TEXT_WHITE)
        time_text = self.font_medium.render(f"到达楼层: {self.player.current_floor}", True, TEXT_GOLD)
        restart_text = self.font_medium.render("按 R 键再玩一次", True, (100, 255, 100))
        
        # 绘制奖杯
        cup_center_x, cup_center_y = WIDTH // 2, HEIGHT // 2 - 100
        # 奖杯杯身
        pygame.draw.rect(screen, (255, 215, 0), 
                        (cup_center_x - 20, cup_center_y, 40, 60))
        # 奖杯手柄
        pygame.draw.rect(screen, (255, 215, 0), 
                        (cup_center_x - 40, cup_center_y + 20, 20, 20))
        pygame.draw.rect(screen, (255, 215, 0), 
                        (cup_center_x + 20, cup_center_y + 20, 20, 20))
        # 奖杯顶部
        pygame.draw.ellipse(screen, (255, 215, 0), 
                          (cup_center_x - 30, cup_center_y - 10, 60, 20))
        
        texts = [victory_text, congrats_text, final_score_text, time_text, restart_text]
        y_start = HEIGHT // 2 + 20
        
        for i, text in enumerate(texts):
            screen.blit(text, (WIDTH//2 - text.get_width()//2, y_start + i * 40))

# 主函数
def main():
    game = HundredFloorsGame()
    
    # 主循环
    running = True
    while running:
        # 处理事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            else:
                game.handle_event(event)
        
        # 更新游戏
        game.update()
        
        # 绘制游戏
        screen.fill((0, 0, 0))  # 清除屏幕
        game.draw(screen)
        
        # 更新显示
        pygame.display.flip()
        clock.tick(60)
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()