import pygame
import sys
import random
import math
from pygame.locals import *

# 初始化pygame
pygame.init()
pygame.mixer.init()

# 游戏常量
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 600
FPS = 60
GRAVITY = 0.8
JUMP_FORCE = -18
PLAYER_SPEED = 5
GROUND_HEIGHT = 500
OBSTACLE_SPEED = 5
ENEMY_SPEED = 3
GAME_SPEED = 5

# 颜色定义
COLORS = {
    'background': (135, 206, 235),  # 天空蓝
    'ground': (139, 115, 85),      # 土地色
    'player': (255, 105, 97),      # 红色
    'obstacle': (100, 100, 100),   # 灰色
    'enemy': (255, 0, 0),          # 红色
    'coin': (255, 215, 0),         # 金色
    'shield': (0, 191, 255),       # 蓝色
    'jump_power': (50, 205, 50),   # 绿色
    'text': (50, 50, 50),          # 深灰色
    'health': (255, 50, 50),       # 红色
    'ui_bg': (0, 0, 0, 180)        # 半透明黑色
}

class Player:
    def __init__(self, x, y):
        self.width = 40
        self.height = 60
        self.x = x
        self.y = y
        self.vel_y = 0
        self.is_jumping = False
        self.is_double_jump = False
        self.health = 100
        self.score = 0
        self.coins = 0
        self.shield = False
        self.shield_time = 0
        self.jump_power = False
        self.jump_power_time = 0
        self.invincible = 0
        self.animation_frame = 0
        self.direction = 1  # 1向右，-1向左
        self.is_running = False
        
    def update(self, keys, platforms):
        # 左右移动
        if keys[K_LEFT] or keys[K_a]:
            self.x = max(0, self.x - PLAYER_SPEED)
            self.direction = -1
            self.is_running = True
        elif keys[K_RIGHT] or keys[K_d]:
            self.x = min(SCREEN_WIDTH - self.width, self.x + PLAYER_SPEED)
            self.direction = 1
            self.is_running = True
        else:
            self.is_running = False
        
        # 跳跃
        if (keys[K_SPACE] or keys[K_UP] or keys[K_w]) and not self.is_jumping:
            self.jump()
        elif (keys[K_SPACE] or keys[K_UP] or keys[K_w]) and not self.is_double_jump and self.jump_power:
            self.jump(double=True)
            self.is_double_jump = True
        
        # 应用重力
        self.vel_y += GRAVITY
        self.y += self.vel_y
        
        # 落地检测
        if self.y >= GROUND_HEIGHT - self.height:
            self.y = GROUND_HEIGHT - self.height
            self.vel_y = 0
            self.is_jumping = False
            self.is_double_jump = False
        
        # 平台碰撞检测
        for platform in platforms:
            if (self.x + self.width > platform.x and 
                self.x < platform.x + platform.width and
                self.y + self.height > platform.y and
                self.y + self.height < platform.y + 20 and
                self.vel_y > 0):
                self.y = platform.y - self.height
                self.vel_y = 0
                self.is_jumping = False
                self.is_double_jump = False
        
        # 更新道具时间
        if self.shield_time > 0:
            self.shield_time -= 1
        else:
            self.shield = False
            
        if self.jump_power_time > 0:
            self.jump_power_time -= 1
        else:
            self.jump_power = False
        
        if self.invincible > 0:
            self.invincible -= 1
        
        # 更新动画帧
        if self.is_running or self.is_jumping:
            self.animation_frame = (self.animation_frame + 1) % 20
    
    def jump(self, double=False):
        force = JUMP_FORCE * 1.5 if double else JUMP_FORCE
        self.vel_y = force
        self.is_jumping = True
        if double:
            self.is_double_jump = True
    
    def take_damage(self, amount):
        if self.invincible > 0 or self.shield:
            return False
        
        self.health = max(0, self.health - amount)
        self.invincible = 30  # 1秒无敌时间
        return True
    
    def collect_coin(self, value=1):
        self.coins += value
        self.score += value * 10
    
    def draw(self, screen):
        # 无敌闪烁效果
        if self.invincible > 0 and self.invincible % 6 < 3:
            return
        
        # 绘制玩家身体
        pygame.draw.rect(screen, COLORS['player'], 
                        (self.x, self.y, self.width, self.height), 
                        border_radius=10)
        
        # 绘制眼睛
        eye_x = self.x + 25 if self.direction == 1 else self.x + 15
        pygame.draw.circle(screen, (255, 255, 255), (int(eye_x), int(self.y + 20)), 8)
        pygame.draw.circle(screen, (0, 0, 0), (int(eye_x), int(self.y + 20)), 4)
        
        # 绘制嘴巴
        mouth_y = self.y + 40
        if self.is_jumping:
            pygame.draw.arc(screen, (0, 0, 0), 
                          (self.x + 10, mouth_y - 5, 20, 15), 
                          0, math.pi, 2)
        else:
            pygame.draw.arc(screen, (0, 0, 0), 
                          (self.x + 10, mouth_y, 20, 10), 
                          math.pi, 2 * math.pi, 2)
        
        # 护盾效果
        if self.shield:
            pygame.draw.circle(screen, COLORS['shield'], 
                             (int(self.x + self.width//2), int(self.y + self.height//2)),
                             self.width//2 + 10, 2)
        
        # 跳跃强化效果
        if self.jump_power:
            pygame.draw.circle(screen, COLORS['jump_power'], 
                             (int(self.x + self.width//2), int(self.y - 10)),
                             5)
    
    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

class Platform:
    def __init__(self, x, y, width=200, height=20):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = (139, 115, 85)
    
    def update(self, speed):
        self.x -= speed
    
    def draw(self, screen):
        pygame.draw.rect(screen, self.color, 
                        (self.x, self.y, self.width, self.height),
                        border_radius=5)
        # 平台顶部细节
        pygame.draw.line(screen, (160, 140, 110), 
                        (self.x, self.y), 
                        (self.x + self.width, self.y), 3)

class Obstacle:
    def __init__(self, x, y, obstacle_type="spike"):
        self.x = x
        self.y = y
        self.type = obstacle_type
        self.width = 40
        self.height = 40
        self.speed = OBSTACLE_SPEED
        self.animation_frame = 0
        
        if self.type == "spike":
            self.color = (100, 100, 100)
            self.height = 30
        elif self.type == "rock":
            self.color = (120, 120, 120)
            self.width = 60
            self.height = 40
        elif self.type == "moving":
            self.color = (80, 80, 80)
            self.speed += 2
            self.move_direction = 1
            self.move_range = 100
    
    def update(self, platforms):
        self.x -= self.speed
        self.animation_frame += 1
        
        # 移动障碍物上下移动
        if self.type == "moving":
            self.y += 2 * self.move_direction
            if self.y > GROUND_HEIGHT - self.height or self.y < GROUND_HEIGHT - self.height - self.move_range:
                self.move_direction *= -1
        
        # 平台上的障碍物
        for platform in platforms:
            if (self.x + self.width > platform.x and 
                self.x < platform.x + platform.width and
                self.y + self.height >= platform.y and
                self.y < platform.y + platform.height):
                self.y = platform.y - self.height
                break
        else:
            if self.y < GROUND_HEIGHT - self.height and self.type != "moving":
                self.y += GRAVITY * 2
                if self.y > GROUND_HEIGHT - self.height:
                    self.y = GROUND_HEIGHT - self.height
    
    def draw(self, screen):
        if self.type == "spike":
            # 绘制尖刺
            points = [
                (self.x + self.width//2, self.y),
                (self.x, self.y + self.height),
                (self.x + self.width, self.y + self.height)
            ]
            pygame.draw.polygon(screen, self.color, points)
            
        elif self.type == "rock":
            # 绘制岩石
            pygame.draw.ellipse(screen, self.color, 
                              (self.x, self.y, self.width, self.height))
            # 岩石纹理
            for i in range(3):
                offset = i * 15
                pygame.draw.ellipse(screen, (100, 100, 100), 
                                  (self.x + offset, self.y + 10, 10, 10))
        
        elif self.type == "moving":
            # 绘制移动方块
            pygame.draw.rect(screen, self.color, 
                           (self.x, self.y, self.width, self.height),
                           border_radius=8)
            # 移动指示器
            if self.animation_frame % 30 < 15:
                arrow_y = self.y - 20
                pygame.draw.polygon(screen, (255, 255, 0), [
                    (self.x + self.width//2, arrow_y),
                    (self.x + self.width//2 - 10, arrow_y + 10),
                    (self.x + self.width//2 + 10, arrow_y + 10)
                ])
    
    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

class Enemy:
    def __init__(self, x, y, enemy_type="ground"):
        self.x = x
        self.y = y
        self.type = enemy_type
        self.width = 50
        self.height = 60
        self.speed = ENEMY_SPEED
        self.health = 3
        self.direction = -1
        self.animation_frame = 0
        self.attack_cooldown = 0
        
        if self.type == "flying":
            self.color = (220, 0, 0)
            self.speed = ENEMY_SPEED + 2
            self.height = 40
        elif self.type == "boss":
            self.color = (180, 0, 0)
            self.width = 80
            self.height = 100
            self.speed = ENEMY_SPEED - 1
            self.health = 10
        else:  # ground
            self.color = (200, 0, 0)
    
    def update(self, player, platforms):
        self.x -= self.speed
        self.animation_frame += 1
        
        if self.type == "flying":
            # 飞行敌人上下浮动
            self.y += math.sin(self.animation_frame * 0.1) * 2
            
            # 追踪玩家
            if player.y < self.y:
                self.y -= 1
            elif player.y > self.y + 20:
                self.y += 1
        
        elif self.type == "ground":
            # 地面敌人在平台上移动
            on_platform = False
            for platform in platforms:
                if (self.x + self.width > platform.x and 
                    self.x < platform.x + platform.width and
                    self.y + self.height >= platform.y and
                    self.y < platform.y + platform.height):
                    self.y = platform.y - self.height
                    on_platform = True
                    break
            
            if not on_platform:
                self.y += GRAVITY
                if self.y > GROUND_HEIGHT - self.height:
                    self.y = GROUND_HEIGHT - self.height
        
        # 攻击冷却
        if self.attack_cooldown > 0:
            self.attack_cooldown -= 1
    
    def draw(self, screen):
        # 绘制敌人身体
        if self.type == "boss":
            pygame.draw.rect(screen, self.color, 
                           (self.x, self.y, self.width, self.height),
                           border_radius=15)
        else:
            pygame.draw.rect(screen, self.color, 
                           (self.x, self.y, self.width, self.height),
                           border_radius=10)
        
        # 绘制眼睛
        eye_offset = 0
        if self.animation_frame % 30 < 15:
            eye_offset = 2
        
        if self.type == "flying":
            pygame.draw.circle(screen, (255, 255, 255), 
                             (int(self.x + 15), int(self.y + 15 + eye_offset)), 6)
            pygame.draw.circle(screen, (0, 0, 0), 
                             (int(self.x + 15), int(self.y + 15 + eye_offset)), 3)
            pygame.draw.circle(screen, (255, 255, 255), 
                             (int(self.x + 35), int(self.y + 15 + eye_offset)), 6)
            pygame.draw.circle(screen, (0, 0, 0), 
                             (int(self.x + 35), int(self.y + 15 + eye_offset)), 3)
        else:
            pygame.draw.circle(screen, (255, 255, 255), 
                             (int(self.x + 15), int(self.y + 20 + eye_offset)), 8)
            pygame.draw.circle(screen, (0, 0, 0), 
                             (int(self.x + 15), int(self.y + 20 + eye_offset)), 4)
            pygame.draw.circle(screen, (255, 255, 255), 
                             (int(self.x + 35), int(self.y + 20 + eye_offset)), 8)
            pygame.draw.circle(screen, (0, 0, 0), 
                             (int(self.x + 35), int(self.y + 20 + eye_offset)), 4)
        
        # 绘制嘴巴
        if self.type == "boss":
            pygame.draw.arc(screen, (0, 0, 0), 
                          (self.x + 20, self.y + 60, 40, 20), 
                          0, math.pi, 3)
        else:
            pygame.draw.arc(screen, (0, 0, 0), 
                          (self.x + 10, self.y + 35, 30, 15), 
                          0, math.pi, 2)
        
        # 绘制血量条（Boss）
        if self.type == "boss" and self.health < 10:
            bar_width = 60
            bar_height = 8
            health_width = bar_width * self.health / 10
            pygame.draw.rect(screen, (100, 100, 100), 
                           (self.x + 10, self.y - 15, bar_width, bar_height))
            pygame.draw.rect(screen, COLORS['health'], 
                           (self.x + 10, self.y - 15, health_width, bar_height))
        
        # 翅膀（飞行敌人）
        if self.type == "flying" and self.animation_frame % 20 < 10:
            wing_y = self.y + 10
            wing_width = 20
            pygame.draw.ellipse(screen, (255, 100, 100), 
                              (self.x - 10, wing_y, wing_width, 15))
            pygame.draw.ellipse(screen, (255, 100, 100), 
                              (self.x + 40, wing_y, wing_width, 15))
    
    def attack(self, player):
        if self.attack_cooldown > 0:
            return False
        
        player_rect = player.get_rect()
        enemy_rect = self.get_rect()
        
        if enemy_rect.colliderect(player_rect):
            self.attack_cooldown = 60  # 1秒冷却
            return True
        
        return False
    
    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

class PowerUp:
    def __init__(self, x, y, power_type="coin"):
        self.x = x
        self.y = y
        self.type = power_type
        self.width = 30
        self.height = 30
        self.collected = False
        self.animation_frame = 0
        
        if self.type == "coin":
            self.color = COLORS['coin']
            self.value = 1
        elif self.type == "shield":
            self.color = COLORS['shield']
        elif self.type == "jump_power":
            self.color = COLORS['jump_power']
        elif self.type == "health":
            self.color = COLORS['health']
        elif self.type == "big_coin":
            self.color = COLORS['coin']
            self.width = 40
            self.height = 40
            self.value = 5
    
    def update(self, speed):
        self.x -= speed
        self.animation_frame += 1
    
    def draw(self, screen):
        if self.collected:
            return
            
        # 浮动动画
        float_offset = math.sin(self.animation_frame * 0.1) * 5
        
        if self.type == "coin":
            # 金币
            pygame.draw.circle(screen, self.color, 
                             (int(self.x + self.width//2), 
                              int(self.y + self.height//2 + float_offset)), 
                             self.width//2)
            pygame.draw.circle(screen, (255, 255, 200), 
                             (int(self.x + self.width//2), 
                              int(self.y + self.height//2 + float_offset)), 
                             self.width//3)
            
            # 金币闪烁
            if self.animation_frame % 20 < 10:
                pygame.draw.line(screen, (255, 255, 200),
                               (self.x + self.width//2, self.y + 5 + float_offset),
                               (self.x + self.width//2, self.y + self.height - 5 + float_offset), 2)
        
        elif self.type == "big_coin":
            # 大金币
            pygame.draw.circle(screen, self.color, 
                             (int(self.x + self.width//2), 
                              int(self.y + self.height//2 + float_offset)), 
                             self.width//2)
            pygame.draw.circle(screen, (255, 255, 200), 
                             (int(self.x + self.width//2), 
                              int(self.y + self.height//2 + float_offset)), 
                             self.width//4)
            
            # 星形效果
            for i in range(5):
                angle = i * 72 + self.animation_frame * 2
                x1 = self.x + self.width//2 + math.cos(math.radians(angle)) * 15
                y1 = self.y + self.height//2 + math.sin(math.radians(angle)) * 15 + float_offset
                x2 = self.x + self.width//2 + math.cos(math.radians(angle + 36)) * 8
                y2 = self.y + self.height//2 + math.sin(math.radians(angle + 36)) * 8 + float_offset
                pygame.draw.line(screen, (255, 255, 200), (x1, y1), (x2, y2), 2)
        
        elif self.type == "shield":
            # 护盾
            pygame.draw.circle(screen, self.color, 
                             (int(self.x + self.width//2), 
                              int(self.y + self.height//2 + float_offset)), 
                             self.width//2, 3)
            
            # 旋转的护盾
            for i in range(4):
                angle = i * 90 + self.animation_frame * 3
                x1 = self.x + self.width//2 + math.cos(math.radians(angle)) * 10
                y1 = self.y + self.height//2 + math.sin(math.radians(angle)) * 10 + float_offset
                pygame.draw.circle(screen, self.color, (int(x1), int(y1)), 4)
        
        elif self.type == "jump_power":
            # 跳跃强化
            pygame.draw.circle(screen, self.color, 
                             (int(self.x + self.width//2), 
                              int(self.y + self.height//2 + float_offset)), 
                             self.width//2)
            
            # 向上箭头
            pygame.draw.polygon(screen, (255, 255, 255), [
                (self.x + self.width//2, self.y + 5 + float_offset),
                (self.x + 5, self.y + self.height - 5 + float_offset),
                (self.x + self.width - 5, self.y + self.height - 5 + float_offset)
            ])
        
        elif self.type == "health":
            # 生命值
            pygame.draw.circle(screen, self.color, 
                             (int(self.x + self.width//2), 
                              int(self.y + self.height//2 + float_offset)), 
                             self.width//2)
            
            # 心形
            pygame.draw.polygon(screen, (255, 255, 255), [
                (self.x + self.width//2, self.y + 20 + float_offset),
                (self.x + 10, self.y + 10 + float_offset),
                (self.x + self.width//2, self.y + self.height - 5 + float_offset),
                (self.x + self.width - 10, self.y + 10 + float_offset)
            ])
    
    def collect(self, player):
        if self.collected:
            return False
            
        self.collected = True
        
        if self.type == "coin" or self.type == "big_coin":
            player.collect_coin(self.value)
            return "coin"
        elif self.type == "shield":
            player.shield = True
            player.shield_time = 600  # 10秒
            return "shield"
        elif self.type == "jump_power":
            player.jump_power = True
            player.jump_power_time = 600  # 10秒
            return "jump_power"
        elif self.type == "health":
            player.health = min(100, player.health + 30)
            return "health"
        
        return None
    
    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

class Game:
    def __init__(self):
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        pygame.display.set_caption("2D跑酷冒险")
        self.clock = pygame.time.Clock()
        
        # 加载字体
        self.font_large = pygame.font.Font(None, 48)
        self.font_medium = pygame.font.Font(None, 36)
        self.font_small = pygame.font.Font(None, 24)
        
        # 加载音效
        self.load_sounds()
        
        # 游戏状态
        self.reset_game()
        
        # 生成初始元素
        self.generate_initial_elements()
    
    def load_sounds(self):
        """加载音效"""
        self.sounds = {}
        # 这里可以添加实际音效文件
    
    def reset_game(self):
        """重置游戏状态"""
        self.player = Player(100, GROUND_HEIGHT - 100)
        self.platforms = []
        self.obstacles = []
        self.enemies = []
        self.powerups = []
        self.game_speed = GAME_SPEED
        self.score = 0
        self.game_over = False
        self.paused = False
        self.level = 1
        self.last_obstacle_time = 0
        self.last_powerup_time = 0
        self.last_enemy_time = 0
        self.scroll_x = 0
        self.particle_effects = []
        
    def generate_initial_elements(self):
        """生成初始游戏元素"""
        # 生成初始平台
        for i in range(5):
            x = 300 + i * 250
            y = GROUND_HEIGHT - 150 - (i % 3) * 50
            width = random.randint(150, 300)
            self.platforms.append(Platform(x, y, width))
        
        # 生成一些初始障碍
        for i in range(3):
            x = 500 + i * 300
            obstacle_type = random.choice(["spike", "rock", "moving"])
            self.obstacles.append(Obstacle(x, GROUND_HEIGHT - 40, obstacle_type))
        
        # 生成一些初始道具
        for i in range(2):
            x = 400 + i * 400
            power_type = random.choice(["coin", "coin", "coin", "shield", "jump_power"])
            self.powerups.append(PowerUp(x, GROUND_HEIGHT - 100, power_type))
    
    def spawn_obstacle(self):
        """生成障碍物"""
        obstacle_types = ["spike", "rock", "moving"]
        weights = [0.5, 0.3, 0.2]  # 不同障碍物的生成概率
        
        if random.random() < 0.3:  # 30%几率生成在平台上
            if self.platforms:
                platform = random.choice(self.platforms)
                x = platform.x + platform.width + 100
                y = platform.y - 40
            else:
                x = SCREEN_WIDTH + 100
                y = GROUND_HEIGHT - 40
        else:
            x = SCREEN_WIDTH + 100
            y = GROUND_HEIGHT - 40
        
        obstacle_type = random.choices(obstacle_types, weights=weights)[0]
        self.obstacles.append(Obstacle(x, y, obstacle_type))
    
    def spawn_powerup(self):
        """生成道具"""
        power_types = ["coin", "coin", "coin", "big_coin", "shield", "jump_power", "health"]
        weights = [0.4, 0.4, 0.4, 0.1, 0.05, 0.05, 0.1]  # 不同道具的生成概率
        
        if random.random() < 0.4:  # 40%几率生成在平台上
            if self.platforms:
                platform = random.choice(self.platforms)
                x = platform.x + platform.width + 50
                y = platform.y - 50
            else:
                x = SCREEN_WIDTH + 50
                y = GROUND_HEIGHT - 100
        else:
            x = SCREEN_WIDTH + 50
            y = random.randint(GROUND_HEIGHT - 200, GROUND_HEIGHT - 80)
        
        power_type = random.choices(power_types, weights=weights)[0]
        self.powerups.append(PowerUp(x, y, power_type))
    
    def spawn_enemy(self):
        """生成敌人"""
        enemy_types = ["ground", "flying", "boss"]
        weights = [0.6, 0.3, 0.1]  # 不同敌人的生成概率
        
        if self.level >= 3 and random.random() < 0.1:  # 10%几率生成Boss
            enemy_type = "boss"
        else:
            enemy_type = random.choices(enemy_types, weights=weights)[0]
        
        x = SCREEN_WIDTH + 100
        if enemy_type == "flying":
            y = random.randint(100, GROUND_HEIGHT - 200)
        elif enemy_type == "boss":
            y = GROUND_HEIGHT - 150
        else:
            y = GROUND_HEIGHT - 60
        
        self.enemies.append(Enemy(x, y, enemy_type))
    
    def spawn_platform(self):
        """生成新平台"""
        if not self.platforms or self.platforms[-1].x < SCREEN_WIDTH - 200:
            x = SCREEN_WIDTH + random.randint(100, 300)
            y = random.randint(GROUND_HEIGHT - 300, GROUND_HEIGHT - 100)
            width = random.randint(150, 400)
            self.platforms.append(Platform(x, y, width))
    
    def handle_events(self):
        """处理事件"""
        for event in pygame.event.get():
            if event.type == QUIT:
                return False
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    return False
                elif event.key == K_p:
                    self.paused = not self.paused
                elif event.key == K_r and self.game_over:
                    self.reset_game()
                    self.generate_initial_elements()
                elif event.key == K_SPACE and self.game_over:
                    self.reset_game()
                    self.generate_initial_elements()
        
        return True
    
    def update(self):
        """更新游戏状态"""
        if self.paused or self.game_over:
            return
        
        # 获取按键状态
        keys = pygame.key.get_pressed()
        
        # 更新玩家
        self.player.update(keys, self.platforms)
        
        # 更新游戏速度
        self.game_speed = GAME_SPEED + self.level * 0.5
        
        # 更新平台
        for platform in self.platforms[:]:
            platform.update(self.game_speed)
            if platform.x + platform.width < 0:
                self.platforms.remove(platform)
        
        # 生成新平台
        self.spawn_platform()
        
        # 更新障碍物
        for obstacle in self.obstacles[:]:
            obstacle.update(self.platforms)
            
            # 检测碰撞
            if obstacle.get_rect().colliderect(self.player.get_rect()):
                if self.player.take_damage(20):
                    self.add_particles(self.player.x, self.player.y, (255, 0, 0), 10)
            
            if obstacle.x + obstacle.width < 0:
                self.obstacles.remove(obstacle)
        
        # 更新敌人
        for enemy in self.enemies[:]:
            enemy.update(self.player, self.platforms)
            
            # 检测攻击
            if enemy.attack(self.player):
                if self.player.take_damage(10 if enemy.type == "boss" else 5):
                    self.add_particles(self.player.x, self.player.y, (255, 0, 0), 8)
            
            # 玩家跳跃攻击敌人
            if (self.player.get_rect().colliderect(enemy.get_rect()) and 
                self.player.vel_y > 0 and 
                self.player.y + self.player.height < enemy.y + 20):
                enemy.health -= 1
                if enemy.health <= 0:
                    self.enemies.remove(enemy)
                    self.score += 50 if enemy.type == "boss" else 20
                    self.add_particles(enemy.x, enemy.y, (255, 255, 0), 15)
                self.player.vel_y = JUMP_FORCE * 0.7
                self.add_particles(enemy.x, enemy.y, (255, 255, 0), 10)
            
            if enemy.x + enemy.width < 0:
                self.enemies.remove(enemy)
        
        # 更新道具
        for powerup in self.powerups[:]:
            powerup.update(self.game_speed)
            
            # 检测收集
            if (not powerup.collected and 
                powerup.get_rect().colliderect(self.player.get_rect())):
                effect = powerup.collect(self.player)
                if effect:
                    self.add_particles(powerup.x, powerup.y, powerup.color, 8)
                    if effect == "coin":
                        self.score += 10
            
            if powerup.x + powerup.width < 0 or powerup.collected:
                self.powerups.remove(powerup)
        
        # 生成新障碍物
        current_time = pygame.time.get_ticks()
        if current_time - self.last_obstacle_time > 2000 - self.level * 100:  # 随着等级提高，生成更快
            self.spawn_obstacle()
            self.last_obstacle_time = current_time
        
        # 生成新道具
        if current_time - self.last_powerup_time > 3000:
            self.spawn_powerup()
            self.last_powerup_time = current_time
        
        # 生成新敌人
        if current_time - self.last_enemy_time > 5000 - self.level * 200:
            self.spawn_enemy()
            self.last_enemy_time = current_time
        
        # 更新粒子效果
        for particle in self.particle_effects[:]:
            particle['x'] += particle['vx']
            particle['y'] += particle['vy']
            particle['life'] -= 1
            if particle['life'] <= 0:
                self.particle_effects.remove(particle)
        
        # 更新分数
        self.score += 1
        self.player.score = self.score
        
        # 更新等级
        self.level = 1 + self.score // 1000
        
        # 检查游戏结束
        if self.player.health <= 0:
            self.game_over = True
        
        # 屏幕滚动
        if self.player.x > SCREEN_WIDTH * 0.7:
            self.scroll_x = self.player.x - SCREEN_WIDTH * 0.7
            self.player.x = SCREEN_WIDTH * 0.7
    
    def add_particles(self, x, y, color, count=5):
        """添加粒子效果"""
        for _ in range(count):
            particle = {
                'x': x + random.randint(-10, 10),
                'y': y + random.randint(-10, 10),
                'vx': random.uniform(-3, 3),
                'vy': random.uniform(-5, 0),
                'life': random.randint(20, 40),
                'color': color,
                'size': random.randint(3, 6)
            }
            self.particle_effects.append(particle)
    
    def draw_background(self):
        """绘制背景"""
        # 天空
        self.screen.fill(COLORS['background'])
        
        # 云朵
        for i in range(3):
            cloud_x = (i * 400 - self.scroll_x * 0.5) % (SCREEN_WIDTH + 400) - 200
            cloud_y = 100 + i * 50
            cloud_size = 60 + i * 20
            pygame.draw.ellipse(self.screen, (255, 255, 255, 200), 
                              (cloud_x, cloud_y, cloud_size * 3, cloud_size))
        
        # 地面
        pygame.draw.rect(self.screen, COLORS['ground'], 
                        (0, GROUND_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - GROUND_HEIGHT))
        
        # 地面纹理
        for i in range(20):
            x = (i * 50 - self.scroll_x) % SCREEN_WIDTH
            pygame.draw.line(self.screen, (160, 140, 110), 
                           (x, GROUND_HEIGHT), (x, GROUND_HEIGHT + 10), 2)
    
    def draw_parallax(self):
        """绘制视差背景"""
        # 远山
        for i in range(3):
            x = (i * 300 - self.scroll_x * 0.3) % (SCREEN_WIDTH + 300) - 100
            y = GROUND_HEIGHT - 100
            points = [
                (x, y),
                (x + 50, y - 80),
                (x + 150, y - 120),
                (x + 250, y - 60),
                (x + 300, y)
            ]
            pygame.draw.polygon(self.screen, (100, 150, 100), points)
    
    def draw_ui(self):
        """绘制用户界面"""
        # 半透明背景
        ui_surface = pygame.Surface((SCREEN_WIDTH, 60), pygame.SRCALPHA)
        ui_surface.fill(COLORS['ui_bg'])
        self.screen.blit(ui_surface, (0, 0))
        
        # 分数
        score_text = self.font_medium.render(f"分数: {self.score}", True, (255, 255, 255))
        self.screen.blit(score_text, (20, 15))
        
        # 金币
        coin_text = self.font_medium.render(f"金币: {self.player.coins}", True, COLORS['coin'])
        self.screen.blit(coin_text, (200, 15))
        
        # 等级
        level_text = self.font_medium.render(f"等级: {self.level}", True, (255, 255, 255))
        self.screen.blit(level_text, (350, 15))
        
        # 血量条
        bar_width = 200
        bar_height = 20
        health_width = bar_width * self.player.health / 100
        
        pygame.draw.rect(self.screen, (100, 100, 100), 
                        (SCREEN_WIDTH - bar_width - 20, 20, bar_width, bar_height))
        pygame.draw.rect(self.screen, COLORS['health'], 
                        (SCREEN_WIDTH - bar_width - 20, 20, health_width, bar_height))
        
        health_text = self.font_small.render(f"{int(self.player.health)}/100", True, (255, 255, 255))
        self.screen.blit(health_text, (SCREEN_WIDTH - bar_width//2 - 30, 22))
        
        # 道具状态
        if self.player.shield:
            shield_text = self.font_small.render("护盾", True, COLORS['shield'])
            self.screen.blit(shield_text, (500, 20))
        
        if self.player.jump_power:
            jump_text = self.font_small.render("二段跳", True, COLORS['jump_power'])
            self.screen.blit(jump_text, (570, 20))
    
    def draw_particles(self):
        """绘制粒子效果"""
        for particle in self.particle_effects:
            alpha = int(255 * particle['life'] / 40)
            color = particle['color'] + (alpha,)
            s = pygame.Surface((particle['size']*2, particle['size']*2), pygame.SRCALPHA)
            pygame.draw.circle(s, color, (particle['size'], particle['size']), particle['size'])
            self.screen.blit(s, (int(particle['x']-particle['size']), int(particle['y']-particle['size'])))
    
    def draw_game_over(self):
        """绘制游戏结束画面"""
        if not self.game_over:
            return
        
        # 半透明覆盖层
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 150))
        self.screen.blit(overlay, (0, 0))
        
        # 游戏结束框
        game_over_rect = pygame.Rect(SCREEN_WIDTH//2 - 200, SCREEN_HEIGHT//2 - 150, 400, 300)
        pygame.draw.rect(self.screen, (50, 50, 50), game_over_rect, border_radius=20)
        pygame.draw.rect(self.screen, (100, 100, 100), game_over_rect, 3, border_radius=20)
        
        # 游戏结束文字
        game_over_text = self.font_large.render("游戏结束", True, (255, 50, 50))
        self.screen.blit(game_over_text, (SCREEN_WIDTH//2 - game_over_text.get_width()//2, 
                                        SCREEN_HEIGHT//2 - 120))
        
        # 分数显示
        score_text = self.font_medium.render(f"最终分数: {self.score}", True, (255, 255, 255))
        self.screen.blit(score_text, (SCREEN_WIDTH//2 - score_text.get_width()//2,
                                    SCREEN_HEIGHT//2 - 60))
        
        # 金币显示
        coin_text = self.font_medium.render(f"收集金币: {self.player.coins}", True, COLORS['coin'])
        self.screen.blit(coin_text, (SCREEN_WIDTH//2 - coin_text.get_width()//2,
                                   SCREEN_HEIGHT//2 - 20))
        
        # 等级显示
        level_text = self.font_medium.render(f"达到等级: {self.level}", True, (255, 255, 255))
        self.screen.blit(level_text, (SCREEN_WIDTH//2 - level_text.get_width()//2,
                                    SCREEN_HEIGHT//2 + 20))
        
        # 提示
        hint_text = self.font_small.render("按空格键或R键重新开始", True, (200, 200, 200))
        self.screen.blit(hint_text, (SCREEN_WIDTH//2 - hint_text.get_width()//2,
                                   SCREEN_HEIGHT//2 + 100))
    
    def draw_pause_screen(self):
        """绘制暂停屏幕"""
        if not self.paused:
            return
        
        # 半透明覆盖层
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 150))
        self.screen.blit(overlay, (0, 0))
        
        # 暂停框
        pause_rect = pygame.Rect(SCREEN_WIDTH//2 - 150, SCREEN_HEIGHT//2 - 100, 300, 200)
        pygame.draw.rect(self.screen, (50, 50, 50), pause_rect, border_radius=20)
        pygame.draw.rect(self.screen, (100, 100, 100), pause_rect, 3, border_radius=20)
        
        # 暂停文字
        pause_text = self.font_large.render("游戏暂停", True, (255, 255, 255))
        self.screen.blit(pause_text, (SCREEN_WIDTH//2 - pause_text.get_width()//2, 
                                    SCREEN_HEIGHT//2 - 80))
        
        # 提示
        hint_text = self.font_small.render("按P键继续游戏", True, (200, 200, 200))
        self.screen.blit(hint_text, (SCREEN_WIDTH//2 - hint_text.get_width()//2,
                                   SCREEN_HEIGHT//2))
        
        # 控制说明
        controls = [
            "控制说明:",
            "←→ AD: 左右移动",
            "空格/W/↑: 跳跃",
            "P: 暂停游戏",
            "ESC: 退出游戏"
        ]
        
        y_pos = SCREEN_HEIGHT//2 + 30
        for line in controls:
            control_text = self.font_small.render(line, True, (200, 200, 200))
            self.screen.blit(control_text, (SCREEN_WIDTH//2 - control_text.get_width()//2, y_pos))
            y_pos += 25
    
    def draw_instructions(self):
        """绘制操作说明"""
        if not self.game_over and not self.paused:
            instructions = [
                "控制: ←→移动, 空格跳跃, P暂停, ESC退出",
                "提示: 踩在敌人头上可以消灭它们",
                f"速度: {self.game_speed:.1f}x"
            ]
            
            y_pos = SCREEN_HEIGHT - 80
            for line in instructions:
                text = self.font_small.render(line, True, (255, 255, 255))
                self.screen.blit(text, (20, y_pos))
                y_pos += 25
    
    def draw(self):
        """绘制整个游戏"""
        # 绘制背景
        self.draw_background()
        self.draw_parallax()
        
        # 绘制平台
        for platform in self.platforms:
            platform.draw(self.screen)
        
        # 绘制障碍物
        for obstacle in self.obstacles:
            obstacle.draw(self.screen)
        
        # 绘制敌人
        for enemy in self.enemies:
            enemy.draw(self.screen)
        
        # 绘制道具
        for powerup in self.powerups:
            powerup.draw(self.screen)
        
        # 绘制粒子
        self.draw_particles()
        
        # 绘制玩家
        self.player.draw(self.screen)
        
        # 绘制UI
        self.draw_ui()
        self.draw_instructions()
        
        # 绘制暂停/游戏结束界面
        self.draw_pause_screen()
        self.draw_game_over()
    
    def run(self):
        """运行游戏主循环"""
        running = True
        while running:
            running = self.handle_events()
            self.update()
            self.draw()
            pygame.display.flip()
            self.clock.tick(FPS)
        
        pygame.quit()
        sys.exit()

# 启动游戏
if __name__ == "__main__":
    print("=" * 50)
    print("2D跑酷游戏启动")
    print("=" * 50)
    print("游戏说明:")
    print("1. 使用方向键或AD键左右移动")
    print("2. 空格键、W键或上键跳跃")
    print("3. 踩在敌人头上可以消灭它们")
    print("4. 收集金币和道具获得分数和能力")
    print("5. 避免撞到障碍物和敌人")
    print("6. 按P键暂停游戏")
    print("7. 按ESC键退出游戏")
    print("=" * 50)
    
    try:
        game = Game()
        game.run()
    except Exception as e:
        print(f"游戏运行出错: {e}")
        import traceback
        traceback.print_exc()
        input("按Enter键退出...")