import pygame
import sys
import random
import time
import math
from pygame import mixer

# 初始化pygame
pygame.init()
mixer.init()

# 游戏窗口设置
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("极速跑酷冒险")
clock = pygame.time.Clock()
FPS = 60

# 颜色定义
SKY_BLUE = (135, 206, 235)
SUN_YELLOW = (255, 255, 150)
CLOUD_WHITE = (255, 255, 255)
GROUND_GREEN = (34, 139, 34)
PLAYER_RED = (220, 20, 60)
OBSTACLE_BROWN = (139, 69, 19)
COIN_YELLOW = (255, 215, 0)
POWERUP_BLUE = (0, 191, 255)
TEXT_WHITE = (255, 255, 255)
BUTTON_BLUE = (30, 144, 255)
BUTTON_HOVER = (0, 0, 139)
UI_BG = (0, 0, 0, 180)

# 加载字体
try:
    font_large = pygame.font.Font(None, 64)
    font_medium = pygame.font.Font(None, 48)
    font_small = pygame.font.Font(None, 32)
except:
    font_large = pygame.font.SysFont(None, 64)
    font_medium = pygame.font.SysFont(None, 48)
    font_small = pygame.font.SysFont(None, 32)

# 游戏状态


class GameState:
    MENU = 0
    PLAYING = 1
    PAUSED = 2
    GAME_OVER = 3
    SHOP = 4

# 粒子系统


class Particle:
    def __init__(self, x, y, color=(255, 255, 255)):
        self.x = x
        self.y = y
        self.vx = random.uniform(-2, 2)
        self.vy = random.uniform(-3, -1)
        self.life = 100
        self.color = color
        self.size = random.randint(2, 6)

    def update(self):
        self.x += self.vx
        self.y += self.vy
        self.vy += 0.1
        self.life -= 2
        self.size = max(1, self.size - 0.1)

    def draw(self, surface):
        pygame.draw.circle(surface, self.color,
                           (int(self.x), int(self.y)), int(self.size))

    def is_alive(self):
        return self.life > 0

# 游戏对象基类


class GameObject:
    def __init__(self, x, y, width, height):
        self.rect = pygame.Rect(x, y, width, height)
        self.vx = 0
        self.vy = 0

    def update(self):
        self.rect.x += self.vx
        self.rect.y += self.vy

    def draw(self, surface):
        pass

    def check_collision(self, other):
        return self.rect.colliderect(other.rect)

# 玩家类


class Player(GameObject):
    def __init__(self, x, y):
        super().__init__(x, y, 50, 80)
        self.jump_power = 20
        self.gravity = 1
        self.is_jumping = False
        self.is_sliding = False
        self.slide_timer = 0
        self.color = PLAYER_RED
        self.coins = 0
        self.powerups = 0
        self.invincible = False
        self.invincible_timer = 0
        self.animation_frame = 0
        self.leg_angle = 0

    def jump(self):
        if not self.is_jumping:
            self.vy = -self.jump_power
            self.is_jumping = True
            return True
        return False

    def slide(self):
        if not self.is_sliding:
            self.is_sliding = True
            self.slide_timer = 30
            self.rect.height = 40
            self.rect.y += 40

    def update(self):
        # 应用重力
        if self.is_jumping:
            self.vy += self.gravity
            if self.rect.y >= SCREEN_HEIGHT - 150 - self.rect.height:
                self.rect.y = SCREEN_HEIGHT - 150 - self.rect.height
                self.vy = 0
                self.is_jumping = False

        self.rect.y += self.vy

        # 更新滑行动画
        if self.is_sliding:
            self.slide_timer -= 1
            if self.slide_timer <= 0:
                self.is_sliding = False
                self.rect.height = 80
                self.rect.y -= 40

        # 更新无敌状态
        if self.invincible:
            self.invincible_timer -= 1
            if self.invincible_timer <= 0:
                self.invincible = False

        # 更新动画
        self.animation_frame = (self.animation_frame + 0.2) % 10
        self.leg_angle = math.sin(self.animation_frame) * 20

    def draw(self, surface):
        # 无敌状态闪烁效果
        if self.invincible and (pygame.time.get_ticks() // 100) % 2 == 0:
            draw_color = (255, 255, 255)
        else:
            draw_color = self.color

        if self.is_sliding:
            # 滑行动画 - 用圆角矩形替代椭圆
            pygame.draw.rect(surface, draw_color, self.rect)
            # 头部
            pygame.draw.circle(surface, draw_color,
                               (self.rect.centerx, self.rect.top - 5), 20)
        else:
            # 站立/跳跃动画
            # 身体
            pygame.draw.rect(surface, draw_color, self.rect)
            # 头部
            pygame.draw.circle(surface, draw_color,
                               (self.rect.centerx, self.rect.top - 15), 20)
            # 腿部动画
            leg_length = 25
            left_leg_y = self.rect.bottom + math.sin(self.leg_angle) * 10
            right_leg_y = self.rect.bottom - math.sin(self.leg_angle) * 10

            pygame.draw.line(surface, draw_color,
                             (self.rect.left + 15, self.rect.bottom),
                             (self.rect.left + 15, left_leg_y), 5)
            pygame.draw.line(surface, draw_color,
                             (self.rect.right - 15, self.rect.bottom),
                             (self.rect.right - 15, right_leg_y), 5)

        # 眼睛
        eye_radius = 5
        pygame.draw.circle(surface, (255, 255, 255),
                           (self.rect.centerx - 8, self.rect.top - 5), eye_radius)
        pygame.draw.circle(surface, (255, 255, 255),
                           (self.rect.centerx + 8, self.rect.top - 5), eye_radius)
        pygame.draw.circle(surface, (0, 0, 0),
                           (self.rect.centerx - 8, self.rect.top - 5), 2)
        pygame.draw.circle(surface, (0, 0, 0),
                           (self.rect.centerx + 8, self.rect.top - 5), 2)

# 障碍物类


class Obstacle(GameObject):
    def __init__(self, x, y, obstacle_type, speed):
        width, height = self.get_size(obstacle_type)
        super().__init__(x, y, width, height)
        self.type = obstacle_type
        self.vx = -speed
        self.color = OBSTACLE_BROWN

    def get_size(self, obstacle_type):
        sizes = {
            "rock": (40, 40),
            "cactus": (30, 60),
            "bird": (50, 30),
            "spike": (40, 20),
            "log": (80, 30)
        }
        return sizes.get(obstacle_type, (40, 40))

    def update(self):
        self.rect.x += self.vx

    def draw(self, surface):
        if self.type == "rock":
            pygame.draw.circle(surface, self.color, self.rect.center, 20)
        elif self.type == "cactus":
            pygame.draw.rect(surface, (0, 100, 0), self.rect)
            # 仙人掌刺
            for i in range(3):
                pygame.draw.line(surface, (0, 100, 0),
                                 (self.rect.centerx, self.rect.top + 10 + i*15),
                                 (self.rect.right, self.rect.top + 20 + i*15), 3)
        elif self.type == "bird":
            # 绘制鸟
            pygame.draw.ellipse(surface, (100, 100, 100), self.rect)
            pygame.draw.polygon(surface, (100, 100, 100), [
                (self.rect.right, self.rect.centery),
                (self.rect.right + 20, self.rect.centery - 10),
                (self.rect.right + 20, self.rect.centery + 10)
            ])
        elif self.type == "spike":
            points = [
                (self.rect.left, self.rect.bottom),
                (self.rect.centerx, self.rect.top),
                (self.rect.right, self.rect.bottom)
            ]
            pygame.draw.polygon(surface, (150, 150, 150), points)
        else:  # log
            pygame.draw.rect(surface, (101, 67, 33), self.rect)
            # 年轮
            for i in range(1, 4):
                pygame.draw.ellipse(surface, (139, 69, 19),
                                    (self.rect.centerx - i*3, self.rect.centery - i*3, i*6, i*6), 2)

# 金币类


class Coin(GameObject):
    def __init__(self, x, y, speed):
        super().__init__(x, y, 20, 20)
        self.vx = -speed
        self.animation = 0
        self.collected = False

    def update(self):
        self.rect.x += self.vx
        self.animation = (self.animation + 0.3) % (2 * math.pi)

    def draw(self, surface):
        if not self.collected:
            # 旋转动画
            bounce = math.sin(self.animation) * 5
            pygame.draw.circle(surface, (255, 215, 0),
                               (self.rect.centerx, self.rect.centery + bounce), 10)
            pygame.draw.circle(surface, (255, 255, 100),
                               (self.rect.centerx, self.rect.centery + bounce), 7)
            # 金币上的$符号
            coin_text = font_small.render("$", True, (255, 215, 0))
            surface.blit(coin_text, coin_text.get_rect(center=(self.rect.centerx,
                                                               self.rect.centery + bounce)))

# 道具类


class PowerUp(GameObject):
    def __init__(self, x, y, speed, power_type="shield"):
        super().__init__(x, y, 30, 30)
        self.vx = -speed
        self.type = power_type
        self.animation = 0

    def update(self):
        self.rect.x += self.vx
        self.animation = (self.animation + 0.2) % (2 * math.pi)

    def draw(self, surface):
        bounce = math.sin(self.animation) * 3
        if self.type == "shield":
            pygame.draw.circle(surface, (0, 191, 255),
                               (self.rect.centerx, self.rect.centery + bounce), 15)
            pygame.draw.circle(surface, (100, 200, 255),
                               (self.rect.centerx, self.rect.centery + bounce), 12, 2)
            pygame.draw.circle(surface, (255, 255, 255),
                               (self.rect.centerx, self.rect.centery + bounce), 8, 2)
        elif self.type == "magnet":
            pygame.draw.rect(surface, (255, 0, 0),
                             (self.rect.centerx - 10, self.rect.centery + bounce - 5, 20, 10))
            pygame.draw.rect(surface, (255, 0, 0),
                             (self.rect.centerx - 5, self.rect.centery + bounce - 15, 10, 20))

# 背景元素


class Cloud:
    def __init__(self):
        self.width = random.randint(60, 120)
        self.height = random.randint(20, 40)
        self.x = SCREEN_WIDTH + random.randint(0, 300)
        self.y = random.randint(20, 150)
        self.speed = random.uniform(0.5, 2)

    def update(self):
        self.x -= self.speed
        return self.x < -self.width

    def draw(self, surface):
        # 绘制云朵
        pygame.draw.ellipse(surface, CLOUD_WHITE,
                            (self.x, self.y, self.width, self.height))
        for offset in [-15, 0, 15]:
            pygame.draw.circle(surface, CLOUD_WHITE,
                               (self.x + self.width//2 + offset, self.y + 5), 20)


class Mountain:
    def __init__(self, x, height, speed, color):
        self.x = x
        self.height = height
        self.speed = speed
        self.color = color
        self.width = random.randint(200, 400)

    def update(self):
        self.x -= self.speed
        if self.x < -self.width:
            self.x = SCREEN_WIDTH
            self.width = random.randint(200, 400)
            self.height = random.randint(100, 200)

    def draw(self, surface):
        points = [
            (self.x, SCREEN_HEIGHT - 100),
            (self.x + self.width//2, SCREEN_HEIGHT - 100 - self.height),
            (self.x + self.width, SCREEN_HEIGHT - 100)
        ]
        pygame.draw.polygon(surface, self.color, points)

# UI按钮


class Button:
    def __init__(self, x, y, width, height, text, action=None):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.action = action
        self.is_hovered = False
        self.color = BUTTON_BLUE

    def draw(self, surface):
        color = BUTTON_HOVER if self.is_hovered else self.color

        # 绘制渐变按钮
        for i in range(self.rect.height):
            shade = max(0, color[0] - i//2)
            pygame.draw.rect(surface, (shade, color[1], color[2]),
                             (self.rect.x, self.rect.y + i, self.rect.width, 1))

        # 绘制按钮边框
        pygame.draw.rect(surface, (255, 255, 255), self.rect, 2)

        # 绘制按钮文字
        text_color = (255, 255, 255) if not self.is_hovered else (
            255, 255, 200)
        text_surf = font_medium.render(self.text, True, text_color)
        text_rect = text_surf.get_rect(center=self.rect.center)

        # 文字阴影
        shadow_surf = font_medium.render(self.text, True, (0, 0, 0, 100))
        shadow_rect = text_surf.get_rect(
            center=(self.rect.centerx+2, self.rect.centery+2))
        surface.blit(shadow_surf, shadow_rect)
        surface.blit(text_surf, text_rect)

    def check_hover(self, pos):
        self.is_hovered = self.rect.collidepoint(pos)
        return self.is_hovered

    def check_click(self, pos):
        if self.rect.collidepoint(pos) and self.action:
            return self.action
        return None

# 游戏主类


class Game:
    def __init__(self):
        self.state = GameState.MENU
        self.score = 0
        self.high_score = 0
        self.coins = 0
        self.game_speed = 8
        self.spawn_timer = 0
        self.cloud_timer = 0
        self.particles = []
        self.buttons = []
        self.player_skins = ["red", "blue", "green", "purple"]
        self.current_skin = 0
        self.player_colors = {
            "red": (220, 20, 60),
            "blue": (30, 144, 255),
            "green": (50, 205, 50),
            "purple": (138, 43, 226)
        }

        self.reset_game()
        self.init_menu()

    def reset_game(self):
        self.player = Player(100, SCREEN_HEIGHT - 230)
        self.obstacles = []
        self.coin_list = []
        self.powerups = []
        self.clouds = []
        self.mountains = []
        self.score = 0
        self.game_speed = 8
        self.spawn_timer = 0
        self.cloud_timer = 0
        self.particles = []

        # 创建初始山脉
        for i in range(3):
            self.mountains.append(Mountain(i * 300, random.randint(100, 200),
                                           self.game_speed * 0.3,
                                           (60, 179, 113 - i*20)))

    def init_menu(self):
        self.buttons = [
            Button(SCREEN_WIDTH//2 - 150, 200, 300,
                   60, "开始游戏", self.start_game),
            Button(SCREEN_WIDTH//2 - 150, 280, 300, 60, "商店", self.open_shop),
            Button(SCREEN_WIDTH//2 - 150, 360, 300, 60, "退出游戏", self.quit_game)
        ]

    def start_game(self):
        self.state = GameState.PLAYING
        self.reset_game()

    def open_shop(self):
        self.state = GameState.SHOP

    def quit_game(self):
        pygame.quit()
        sys.exit()

    def spawn_object(self):
        self.spawn_timer += 1

        # 生成障碍物
        if self.spawn_timer >= random.randint(30, 60):
            obstacle_types = ["rock", "cactus", "bird", "spike", "log"]
            obstacle_type = random.choice(obstacle_types)

            if obstacle_type == "bird":
                y = random.randint(SCREEN_HEIGHT - 300, SCREEN_HEIGHT - 200)
            else:
                y = SCREEN_HEIGHT - 150

            self.obstacles.append(
                Obstacle(SCREEN_WIDTH, y, obstacle_type, self.game_speed))
            self.spawn_timer = 0

        # 生成金币
        if random.random() < 0.05:
            y = random.randint(SCREEN_HEIGHT - 250, SCREEN_HEIGHT - 100)
            self.coin_list.append(Coin(SCREEN_WIDTH, y, self.game_speed))

        # 生成道具
        if random.random() < 0.01 and len(self.powerups) < 1:
            power_type = random.choice(["shield", "magnet"])
            y = random.randint(SCREEN_HEIGHT - 250, SCREEN_HEIGHT - 100)
            self.powerups.append(
                PowerUp(SCREEN_WIDTH, y, self.game_speed, power_type))

    def spawn_cloud(self):
        self.cloud_timer += 1
        if self.cloud_timer >= random.randint(30, 100):
            self.clouds.append(Cloud())
            self.cloud_timer = 0

    def create_particles(self, x, y, count=10, color=(255, 255, 255)):
        for _ in range(count):
            self.particles.append(Particle(x, y, color))

    def check_collisions(self):
        # 检查障碍物碰撞
        for obstacle in self.obstacles[:]:
            if self.player.check_collision(obstacle):
                if not self.player.invincible:
                    self.state = GameState.GAME_OVER
                    self.create_particles(self.player.rect.centerx, self.player.rect.centery,
                                          20, self.player.color)
                    if self.score > self.high_score:
                        self.high_score = self.score
                    return

        # 检查金币碰撞
        for coin in self.coin_list[:]:
            if self.player.check_collision(coin) and not coin.collected:
                self.coins += 1
                self.score += 10
                coin.collected = True
                self.create_particles(
                    coin.rect.centerx, coin.rect.centery, 5, (255, 215, 0))

        # 检查道具碰撞
        for powerup in self.powerups[:]:
            if self.player.check_collision(powerup):
                if powerup.type == "shield":
                    self.player.invincible = True
                    self.player.invincible_timer = 300  # 5秒无敌
                self.create_particles(
                    powerup.rect.centerx, powerup.rect.centery, 10, POWERUP_BLUE)
                self.powerups.remove(powerup)

    def update(self):
        if self.state == GameState.PLAYING:
            # 更新玩家
            self.player.update()

            # 生成对象
            self.spawn_object()
            self.spawn_cloud()

            # 更新障碍物
            for obstacle in self.obstacles[:]:
                obstacle.update()
                if obstacle.rect.right < 0:
                    self.obstacles.remove(obstacle)

            # 更新金币
            for coin in self.coin_list[:]:
                coin.update()
                if coin.rect.right < 0 or coin.collected:
                    if coin in self.coin_list:
                        self.coin_list.remove(coin)

            # 更新道具
            for powerup in self.powerups[:]:
                powerup.update()
                if powerup.rect.right < 0:
                    self.powerups.remove(powerup)

            # 更新云朵
            for cloud in self.clouds[:]:
                if cloud.update():
                    self.clouds.remove(cloud)

            # 更新山脉
            for mountain in self.mountains:
                mountain.update()

            # 更新粒子
            for particle in self.particles[:]:
                particle.update()
                if not particle.is_alive():
                    self.particles.remove(particle)

            # 检查碰撞
            self.check_collisions()

            # 增加游戏速度
            self.score += 1
            if self.score % 500 == 0:
                self.game_speed += 0.5

            # 更新障碍物和金币速度
            for obj in self.obstacles + self.coin_list + self.powerups:
                obj.vx = -self.game_speed

            for mountain in self.mountains:
                mountain.speed = self.game_speed * 0.3

    def draw_background(self, surface):
        # 天空渐变
        for y in range(SCREEN_HEIGHT - 100):
            color_value = int(135 + y * 0.2)
            color = (135, 206, min(235, color_value))
            pygame.draw.line(surface, color, (0, y), (SCREEN_WIDTH, y))

        # 太阳
        sun_x = SCREEN_WIDTH // 4
        sun_y = 100
        for i in range(20, 0, -1):
            alpha = 50 - i * 2
            # 简化太阳光晕绘制
            pygame.draw.circle(
                surface, (255, 255, 150, alpha), (sun_x, sun_y), i*2)
        pygame.draw.circle(surface, (255, 255, 100), (sun_x, sun_y), 20)

        # 绘制山脉
        for mountain in self.mountains:
            mountain.draw(surface)

        # 绘制云朵
        for cloud in self.clouds:
            cloud.draw(surface)

        # 地面
        pygame.draw.rect(surface, GROUND_GREEN,
                         (0, SCREEN_HEIGHT - 100, SCREEN_WIDTH, 100))

        # 地面纹理
        for i in range(0, SCREEN_WIDTH, 40):
            pygame.draw.line(surface, (0, 100, 0),
                             (i, SCREEN_HEIGHT - 100), (i, SCREEN_HEIGHT - 60), 2)

    def draw_ui(self, surface):
        if self.state == GameState.PLAYING:
            # 创建半透明背景
            ui_bg = pygame.Surface((220, 100))
            ui_bg.fill((0, 0, 0))
            ui_bg.set_alpha(128)
            surface.blit(ui_bg, (10, 10))

            # 分数
            score_text = font_medium.render(
                f"分数: {self.score}", True, TEXT_WHITE)
            surface.blit(score_text, (20, 20))

            # 金币
            coin_text = font_small.render(
                f"金币: {self.coins}", True, (255, 215, 0))
            surface.blit(coin_text, (20, 60))

            # 速度
            speed_text = font_small.render(
                f"速度: {self.game_speed:.1f}", True, TEXT_WHITE)
            surface.blit(speed_text, (150, 60))

            # 无敌状态指示器
            if self.player.invincible:
                shield_text = font_small.render("无敌!", True, (0, 191, 255))
                surface.blit(shield_text, (SCREEN_WIDTH - 100, 20))

            # 控制提示
            controls = font_small.render(
                "空格:跳跃  S:滑行  ESC:暂停", True, TEXT_WHITE)
            surface.blit(controls, (SCREEN_WIDTH -
                         controls.get_width() - 20, SCREEN_HEIGHT - 40))

        elif self.state == GameState.MENU:
            # 半透明背景
            overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
            overlay.fill((0, 0, 0))
            overlay.set_alpha(150)
            surface.blit(overlay, (0, 0))

            # 游戏标题
            title = font_large.render("极速跑酷冒险", True, (255, 255, 0))
            shadow = font_large.render("极速跑酷冒险", True, (0, 0, 0))
            surface.blit(shadow, (SCREEN_WIDTH//2 -
                         title.get_width()//2 + 3, 103))
            surface.blit(title, (SCREEN_WIDTH//2 - title.get_width()//2, 100))

            subtitle = font_medium.render("按空格键开始游戏", True, (200, 200, 255))
            surface.blit(subtitle, (SCREEN_WIDTH//2 -
                         subtitle.get_width()//2, 170))

            # 绘制玩家示例
            player_example = Player(SCREEN_WIDTH//2, 400)
            player_example.color = self.player_colors[self.player_skins[self.current_skin]]
            player_example.draw(surface)

            # 绘制按钮
            for button in self.buttons:
                button.draw(surface)

        elif self.state == GameState.GAME_OVER:
            overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
            overlay.fill((0, 0, 0))
            overlay.set_alpha(200)
            surface.blit(overlay, (0, 0))

            # 游戏结束文字
            game_over = font_large.render("游戏结束", True, (255, 50, 50))
            surface.blit(game_over, (SCREEN_WIDTH//2 -
                         game_over.get_width()//2, 150))

            # 分数显示
            score_text = font_medium.render(
                f"本次得分: {self.score}", True, TEXT_WHITE)
            surface.blit(score_text, (SCREEN_WIDTH//2 -
                         score_text.get_width()//2, 220))

            high_score_text = font_medium.render(
                f"最高分: {self.high_score}", True, (255, 215, 0))
            surface.blit(high_score_text, (SCREEN_WIDTH//2 -
                         high_score_text.get_width()//2, 270))

            # 重新开始按钮
            restart_btn = Button(SCREEN_WIDTH//2 - 150, 350,
                                 300, 60, "重新开始", self.start_game)
            menu_btn = Button(SCREEN_WIDTH//2 - 150, 430, 300, 60, "返回菜单",
                              lambda: setattr(self, 'state', GameState.MENU))

            mouse_pos = pygame.mouse.get_pos()
            restart_btn.check_hover(mouse_pos)
            menu_btn.check_hover(mouse_pos)

            restart_btn.draw(surface)
            menu_btn.draw(surface)

        elif self.state == GameState.PAUSED:
            overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
            overlay.fill((0, 0, 0))
            overlay.set_alpha(180)
            surface.blit(overlay, (0, 0))

            pause_text = font_large.render("游戏暂停", True, (255, 255, 0))
            surface.blit(pause_text, (SCREEN_WIDTH//2 -
                         pause_text.get_width()//2, 150))

            continue_btn = Button(SCREEN_WIDTH//2 - 150, 250, 300, 60, "继续游戏",
                                  lambda: setattr(self, 'state', GameState.PLAYING))
            menu_btn = Button(SCREEN_WIDTH//2 - 150, 330, 300, 60, "返回菜单",
                              lambda: setattr(self, 'state', GameState.MENU))

            mouse_pos = pygame.mouse.get_pos()
            continue_btn.check_hover(mouse_pos)
            menu_btn.check_hover(mouse_pos)

            continue_btn.draw(surface)
            menu_btn.draw(surface)

        elif self.state == GameState.SHOP:
            overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
            overlay.fill((0, 0, 0))
            overlay.set_alpha(200)
            surface.blit(overlay, (0, 0))

            shop_title = font_large.render("商店", True, (255, 215, 0))
            surface.blit(shop_title, (SCREEN_WIDTH//2 -
                         shop_title.get_width()//2, 50))

            coins_text = font_medium.render(
                f"金币: {self.coins}", True, (255, 215, 0))
            surface.blit(coins_text, (SCREEN_WIDTH//2 -
                         coins_text.get_width()//2, 120))

            # 皮肤选择
            skin_text = font_medium.render("选择皮肤", True, TEXT_WHITE)
            surface.blit(skin_text, (SCREEN_WIDTH//2 -
                         skin_text.get_width()//2, 180))

            # 皮肤预览
            skin_x = SCREEN_WIDTH//2 - 150
            for i, skin in enumerate(self.player_skins):
                color = self.player_colors[skin]
                rect = pygame.Rect(skin_x + i*100, 250, 80, 120)

                # 绘制皮肤框
                if i == self.current_skin:
                    pygame.draw.rect(surface, (255, 215, 0), rect, 4)
                else:
                    pygame.draw.rect(surface, (100, 100, 100), rect, 2)

                # 绘制皮肤
                inner_rect = pygame.Rect(
                    rect.x + 10, rect.y + 20, rect.width - 20, rect.height - 40)
                pygame.draw.rect(surface, color, inner_rect)
                pygame.draw.circle(
                    surface, color, (rect.centerx, rect.top + 30), 15)

                # 皮肤名称
                name_text = font_small.render(
                    skin.capitalize(), True, TEXT_WHITE)
                surface.blit(name_text, (rect.centerx -
                             name_text.get_width()//2, rect.bottom - 20))

            back_btn = Button(SCREEN_WIDTH//2 - 150, 400, 300, 60, "返回菜单",
                              lambda: setattr(self, 'state', GameState.MENU))

            mouse_pos = pygame.mouse.get_pos()
            back_btn.check_hover(mouse_pos)
            back_btn.draw(surface)

    def draw(self, surface):
        # 绘制背景
        self.draw_background(surface)

        # 绘制游戏对象
        if self.state in [GameState.PLAYING, GameState.PAUSED, GameState.GAME_OVER]:
            # 绘制粒子
            for particle in self.particles:
                particle.draw(surface)

            # 绘制障碍物
            for obstacle in self.obstacles:
                obstacle.draw(surface)

            # 绘制金币
            for coin in self.coin_list:
                coin.draw(surface)

            # 绘制道具
            for powerup in self.powerups:
                powerup.draw(surface)

            # 绘制玩家
            self.player.draw(surface)

        # 绘制UI
        self.draw_ui(surface)

    def handle_events(self):
        mouse_pos = pygame.mouse.get_pos()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    if self.state == GameState.PLAYING:
                        self.state = GameState.PAUSED
                    elif self.state == GameState.PAUSED:
                        self.state = GameState.PLAYING
                    elif self.state == GameState.GAME_OVER:
                        self.state = GameState.MENU
                    elif self.state == GameState.SHOP:
                        self.state = GameState.MENU

                elif event.key == pygame.K_SPACE:
                    if self.state == GameState.PLAYING:
                        self.player.jump()
                    elif self.state == GameState.MENU:
                        self.start_game()

                elif event.key == pygame.K_s and self.state == GameState.PLAYING:
                    self.player.slide()

                elif event.key == pygame.K_r and self.state == GameState.GAME_OVER:
                    self.start_game()

            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # 左键点击
                    if self.state == GameState.MENU:
                        for button in self.buttons:
                            action = button.check_click(mouse_pos)
                            if action:
                                action()

                    elif self.state == GameState.SHOP:
                        # 检查皮肤点击
                        skin_x = SCREEN_WIDTH//2 - 150
                        for i in range(len(self.player_skins)):
                            rect = pygame.Rect(skin_x + i*100, 250, 80, 120)
                            if rect.collidepoint(mouse_pos):
                                self.current_skin = i
                                self.player.color = self.player_colors[self.player_skins[i]]

            elif event.type == pygame.MOUSEMOTION:
                if self.state == GameState.MENU:
                    for button in self.buttons:
                        button.check_hover(mouse_pos)


def main():
    game = Game()

    # 尝试加载背景音乐
    try:
        mixer.music.load("background.mp3")
        mixer.music.set_volume(0.3)
        mixer.music.play(-1)
    except:
        pass  # 如果没有音乐文件，静音运行

    while True:
        game.handle_events()
        game.update()

        # 填充背景
        screen.fill((0, 0, 0))

        # 绘制游戏
        game.draw(screen)

        # 更新显示
        pygame.display.flip()
        clock.tick(FPS)


if __name__ == "__main__":
    main()
