import pygame
import sys
import math
import random

# 初始化 Pygame
pygame.init()

# 窗口设置
WIDTH, HEIGHT = 900, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("⚔️ 沙威码传奇")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 50, 50)
DARK_RED = (180, 0, 0)
GREEN = (50, 200, 50)
DARK_GREEN = (0, 150, 0)
LIGHT_GREEN = (144, 238, 144)
BLUE = (50, 150, 255)
DARK_BLUE = (0, 0, 200)
LIGHT_BLUE = (173, 216, 230)
YELLOW = (255, 255, 100)
GOLD = (255, 215, 0)
ORANGE = (255, 165, 0)
PURPLE = (200, 50, 255)
PINK = (255, 182, 193)
BROWN = (139, 69, 19)
LIGHT_BROWN = (160, 120, 80)
DARK_BROWN = (101, 67, 33)
GRAY = (150, 150, 150)
DARK_GRAY = (80, 80, 80)
LIGHT_GRAY = (200, 200, 200)
SKY_BLUE = (135, 206, 235)
ANCIENT_GOLD = (218, 165, 32)
JADE_GREEN = (80, 180, 120)
BLOOD_RED = (139, 0, 0)
DARK_PURPLE = (100, 0, 150)

# 帧率控制
clock = pygame.time.Clock()
FPS = 60

# 中文字体
def get_chinese_font(size):
    font_names = ["SimHei", "Microsoft YaHei", "PingFang SC", "Noto Sans CJK SC", "WenQuanYi Micro Hei", "Arial"]
    for name in font_names:
        try:
            return pygame.font.SysFont(name, size)
        except:
            continue
    return pygame.font.Font(None, size)

font = get_chinese_font(24)
small_font = get_chinese_font(16)
big_font = get_chinese_font(36)
title_font = get_chinese_font(48)
huge_font = get_chinese_font(60)

# 粒子系统
class Particle:
    def __init__(self, x, y, color, vx=None, vy=None, life=30, size=4):
        self.x = x
        self.y = y
        self.vx = vx if vx is not None else random.uniform(-4, 4)
        self.vy = vy if vy is not None else random.uniform(-6, -1)
        self.life = life
        self.max_life = life
        self.size = size
        self.color = color
        self.alive = True
        self.gravity = 0.15
    
    def update(self):
        self.x += self.vx
        self.y += self.vy
        self.vy += self.gravity
        self.life -= 1
        if self.life <= 0:
            self.alive = False
    
    def draw(self, surface):
        if not self.alive:
            return
        alpha = int(255 * (self.life / self.max_life))
        size = int(self.size * (self.life / self.max_life))
        if size < 1:
            return
        particle_surf = pygame.Surface((size * 2, size * 2), pygame.SRCALPHA)
        temp_surf = pygame.Surface((size * 2, size * 2), pygame.SRCALPHA)
        pygame.draw.circle(temp_surf, self.color, (size, size), size)
        temp_surf.set_alpha(alpha)
        particle_surf.blit(temp_surf, (0, 0))
        surface.blit(particle_surf, (int(self.x) - size, int(self.y) - size))

# 技能类
class Skill:
    def __init__(self, name, damage, cost, description, color, icon, skill_type="damage"):
        self.name = name
        self.damage = damage
        self.cost = cost
        self.description = description
        self.color = color
        self.icon = icon
        self.type = skill_type  # "damage", "heal", "buff"
        self.cooldown = 0
        self.max_cooldown = 0
        self.level = 1
        self.xp = 0
        
        # 升级所需经验
        self.xp_to_next = 50 * self.level
    
    def use(self, player, enemy):
        if self.cooldown > 0:
            return None, "技能冷却中！"
        
        if player.qi < self.cost:
            return None, "真气不足！"
        
        player.qi -= self.cost
        self.cooldown = self.max_cooldown
        
        if self.type == "damage":
            # 计算伤害（基础伤害 + 攻击力加成）
            total_damage = self.damage + int(player.attack * 0.3)
            if enemy:
                actual = enemy.take_damage(total_damage)
                # 技能经验
                self.xp += 10
                # 生成攻击粒子
                for _ in range(30):
                    color = random.choice([RED, ORANGE, YELLOW, GOLD])
                    p = Particle(enemy.x, enemy.y, color, 
                               random.uniform(-8, 8), random.uniform(-8, 8),
                               random.randint(20, 40), random.randint(3, 8))
                    player.particles.append(p)
                return actual, f"{self.name}！造成 {actual} 点伤害！"
        
        elif self.type == "heal":
            heal_amount = self.damage + int(player.max_hp * 0.15)
            player.hp = min(player.max_hp, player.hp + heal_amount)
            self.xp += 5
            # 治疗粒子
            for _ in range(20):
                p = Particle(player.x, player.y, GREEN, 
                           random.uniform(-4, 4), random.uniform(-6, -1),
                           random.randint(20, 40), random.randint(3, 6))
                player.particles.append(p)
            return heal_amount, f"{self.name}！恢复 {heal_amount} 点生命！"
        
        elif self.type == "buff":
            # 增益效果（提升攻击力）
            boost = self.damage
            player.attack += boost
            self.xp += 5
            for _ in range(20):
                p = Particle(player.x, player.y, GOLD, 
                           random.uniform(-5, 5), random.uniform(-5, 5),
                           random.randint(20, 40), random.randint(3, 6))
                player.particles.append(p)
            return boost, f"{self.name}！攻击力提升 {boost} 点！"
        
        return None, ""

# 敌人
class Enemy:
    def __init__(self, name, hp, damage, defense, speed, color, reward, enemy_type="normal"):
        self.name = name
        self.max_hp = hp
        self.hp = hp
        self.damage = damage
        self.defense = defense
        self.speed = speed
        self.color = color
        self.reward = reward
        self.type = enemy_type
        self.alive = True
        self.x = random.randint(200, WIDTH - 200)
        self.y = random.randint(200, HEIGHT - 150)
        self.target_x = self.x
        self.target_y = self.y
        self.move_timer = 0
        self.anim_frame = 0
        self.anim_timer = 0
        self.size = 35
        
        # 敌人专属技能
        self.special_attack = random.random() < 0.2
        
        if enemy_type == "boss":
            self.size = 55
            self.damage = int(damage * 1.5)
            self.hp = int(hp * 3)
            self.max_hp = self.hp
            self.reward = int(reward * 3)
            self.color = DARK_RED
    
    def update(self, player_pos):
        if not self.alive:
            return
        
        self.anim_timer += 1
        if self.anim_timer > 10:
            self.anim_timer = 0
            self.anim_frame = (self.anim_frame + 1) % 4
        
        # AI移动 - 追击玩家
        dx = player_pos[0] - self.x
        dy = player_pos[1] - self.y
        dist = math.hypot(dx, dy)
        
        if dist > 80:
            # 追击
            if dist > 5:
                self.x += (dx / dist) * self.speed
                self.y += (dy / dist) * self.speed
        elif dist < 50:
            # 远离玩家
            self.x -= (dx / dist) * self.speed * 0.5
            self.y -= (dy / dist) * self.speed * 0.5
        
        # 边界限制
        self.x = max(50, min(WIDTH - 50, self.x))
        self.y = max(150, min(HEIGHT - 50, self.y))
    
    def take_damage(self, damage):
        actual_damage = max(1, damage - self.defense // 2)
        self.hp -= actual_damage
        if self.hp <= 0:
            self.alive = False
        return actual_damage
    
    def attack_player(self, player):
        damage = self.damage + random.randint(-5, 10)
        actual = max(1, damage - player.defense // 2)
        player.hp -= actual
        return actual
    
    def draw(self, surface):
        if not self.alive:
            return
        
        cx, cy = self.x, self.y
        size = self.size
        
        # 阴影
        shadow_surf = pygame.Surface((size, size//3), pygame.SRCALPHA)
        pygame.draw.ellipse(shadow_surf, (0, 0, 0, 80), (0, 0, size, size//3))
        surface.blit(shadow_surf, (cx - size//2, cy + size//2 - 5))
        
        if self.type == "boss":
            # BOSS - 武林魔头
            # 身体
            pygame.draw.circle(surface, self.color, (cx, cy), size)
            pygame.draw.circle(surface, DARK_RED, (cx, cy), size, 3)
            
            # 魔气环绕
            for i in range(6):
                angle = pygame.time.get_ticks() / 1000 + i * math.pi / 3
                r = size + 10 + 5 * math.sin(pygame.time.get_ticks() / 500 + i)
                px = cx + r * math.cos(angle)
                py = cy + r * math.sin(angle)
                pygame.draw.circle(surface, DARK_PURPLE, (int(px), int(py)), 4)
            
            # 王冠
            crown_points = [
                (cx - size//2, cy - size//2 + 5),
                (cx - size//3, cy - size + 5),
                (cx, cy - size//2 - 5),
                (cx + size//3, cy - size + 5),
                (cx + size//2, cy - size//2 + 5),
            ]
            pygame.draw.polygon(surface, GOLD, crown_points)
            # 眼睛（红色发光）
            pygame.draw.circle(surface, RED, (cx - 14, cy - 5), 7)
            pygame.draw.circle(surface, RED, (cx + 14, cy - 5), 7)
            pygame.draw.circle(surface, (255, 200, 100), (cx - 12, cy - 5), 3)
            pygame.draw.circle(surface, (255, 200, 100), (cx + 12, cy - 5), 3)
            # 嘴
            pygame.draw.arc(surface, BLACK, (cx - 18, cy + 5, 36, 18), 0, math.pi, 2)
            # 武器
            pygame.draw.line(surface, GRAY, (cx + size, cy - 15), (cx + size + 40, cy - 40), 5)
            pygame.draw.line(surface, GRAY, (cx + size, cy + 15), (cx + size + 40, cy + 40), 5)
            # 名字标签
            name_text = small_font.render(f"👑 {self.name}", True, RED)
            name_rect = name_text.get_rect(center=(cx, cy - size - 15))
            surface.blit(name_text, name_rect)
        
        elif self.type == "normal":
            # 普通敌人 - 江湖人士
            # 身体
            pygame.draw.circle(surface, self.color, (cx, cy), size)
            pygame.draw.circle(surface, DARK_GRAY, (cx, cy), size, 2)
            
            # 斗笠
            pygame.draw.arc(surface, BROWN, (cx - size, cy - size, size*2, size*0.8), math.pi, 2*math.pi, 3)
            
            # 眼睛
            pygame.draw.circle(surface, BLACK, (cx - 8, cy - 5), 4)
            pygame.draw.circle(surface, BLACK, (cx + 8, cy - 5), 4)
            pygame.draw.circle(surface, WHITE, (cx - 7, cy - 7), 2)
            pygame.draw.circle(surface, WHITE, (cx + 9, cy - 7), 2)
            # 嘴
            pygame.draw.line(surface, BLACK, (cx - 8, cy + 8), (cx + 8, cy + 8), 2)
            # 武器
            pygame.draw.line(surface, GRAY, (cx + size, cy), (cx + size + 25, cy - 20), 3)
            
            # 名字
            name_text = small_font.render(self.name, True, DARK_GRAY)
            name_rect = name_text.get_rect(center=(cx, cy - size - 10))
            surface.blit(name_text, name_rect)
        
        # 血条
        bar_width = size * 1.5
        bar_height = 5
        bar_x = cx - bar_width // 2
        bar_y = cy - size - 5
        pygame.draw.rect(surface, RED, (bar_x, bar_y, bar_width, bar_height), border_radius=2)
        hp_ratio = self.hp / self.max_hp
        color = GREEN if hp_ratio > 0.5 else ORANGE if hp_ratio > 0.25 else RED
        pygame.draw.rect(surface, color, (bar_x, bar_y, bar_width * hp_ratio, bar_height), border_radius=2)
        pygame.draw.rect(surface, BLACK, (bar_x, bar_y, bar_width, bar_height), 1, border_radius=2)

# 玩家类
class Player:
    def __init__(self):
        self.x = WIDTH // 2
        self.y = HEIGHT - 100
        self.max_hp = 100
        self.hp = 100
        self.max_qi = 100
        self.qi = 100
        self.attack = 15
        self.defense = 5
        self.speed = 3
        self.level = 1
        self.xp = 0
        self.xp_to_next = 50
        self.gold = 0
        self.kills = 0
        self.alive = True
        self.skills = []
        self.particles = []
        self.floating_texts = []
        self.anim_frame = 0
        self.anim_timer = 0
        self.facing = 1
        self.moving = False
        
        # 默认技能
        self.add_skill(Skill("基础剑法", 10, 5, "基础攻击技能", RED, "⚔️", "damage"))
        self.add_skill(Skill("疗伤心法", 20, 15, "恢复生命值", GREEN, "💚", "heal"))
        self.add_skill(Skill("金钟罩", 5, 10, "临时提升防御", GOLD, "🛡️", "buff"))
    
    def add_skill(self, skill):
        skill.max_cooldown = max(0, 10 - skill.level)
        self.skills.append(skill)
    
    def update(self, keys):
        if not self.alive:
            return
        
        # 移动
        dx, dy = 0, 0
        self.moving = False
        if keys[pygame.K_a] or keys[pygame.K_LEFT]:
            dx = -self.speed
            self.facing = -1
            self.moving = True
        if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
            dx = self.speed
            self.facing = 1
            self.moving = True
        if keys[pygame.K_w] or keys[pygame.K_UP]:
            dy = -self.speed
            self.moving = True
        if keys[pygame.K_s] or keys[pygame.K_DOWN]:
            dy = self.speed
            self.moving = True
        
        # 归一化对角线移动
        if dx != 0 and dy != 0:
            dx *= 0.707
            dy *= 0.707
        
        self.x += dx
        self.y += dy
        
        # 边界限制
        self.x = max(30, min(WIDTH - 30, self.x))
        self.y = max(120, min(HEIGHT - 30, self.y))
        
        # 动画
        if self.moving:
            self.anim_timer += 1
            if self.anim_timer > 8:
                self.anim_timer = 0
                self.anim_frame = (self.anim_frame + 1) % 4
        
        # 真气恢复
        if self.qi < self.max_qi:
            self.qi += 0.2
        if self.qi > self.max_qi:
            self.qi = self.max_qi
        
        # 更新技能冷却
        for skill in self.skills:
            if skill.cooldown > 0:
                skill.cooldown -= 1
        
        # 更新粒子
        for p in self.particles[:]:
            p.update()
            if not p.alive:
                self.particles.remove(p)
    
    def draw(self, surface):
        if not self.alive:
            return
        
        cx, cy = self.x, self.y
        
        # 阴影
        shadow_surf = pygame.Surface((30, 8), pygame.SRCALPHA)
        pygame.draw.ellipse(shadow_surf, (0, 0, 0, 80), (0, 0, 30, 8))
        surface.blit(shadow_surf, (cx - 15, cy + 20))
        
        # 身体（武侠形象）
        # 披风
        if self.facing == 1:
            cloak_points = [
                (cx - 12, cy - 15),
                (cx - 20, cy + 15),
                (cx - 8, cy + 18),
                (cx, cy + 10),
            ]
        else:
            cloak_points = [
                (cx + 12, cy - 15),
                (cx + 20, cy + 15),
                (cx + 8, cy + 18),
                (cx, cy + 10),
            ]
        pygame.draw.polygon(surface, (50, 50, 150), cloak_points)
        
        # 身体
        pygame.draw.rect(surface, (200, 180, 160), (cx - 10, cy - 18, 20, 30), border_radius=5)
        
        # 腰带
        pygame.draw.rect(surface, (180, 50, 50), (cx - 10, cy - 2, 20, 4))
        pygame.draw.circle(surface, GOLD, (cx, cy), 3)
        
        # 头
        pygame.draw.circle(surface, (220, 200, 180), (cx, cy - 22), 14)
        
        # 头发
        if self.facing == 1:
            hair_points = [(cx - 12, cy - 30), (cx - 8, cy - 38), (cx, cy - 35), (cx + 8, cy - 38), (cx + 12, cy - 30)]
        else:
            hair_points = [(cx + 12, cy - 30), (cx + 8, cy - 38), (cx, cy - 35), (cx - 8, cy - 38), (cx - 12, cy - 30)]
        pygame.draw.polygon(surface, (30, 30, 30), hair_points)
        
        # 眼睛
        if self.facing == 1:
            pygame.draw.circle(surface, BLACK, (cx - 6, cy - 24), 3)
            pygame.draw.circle(surface, BLACK, (cx + 6, cy - 24), 3)
            pygame.draw.circle(surface, WHITE, (cx - 5, cy - 25), 1)
            pygame.draw.circle(surface, WHITE, (cx + 7, cy - 25), 1)
        else:
            pygame.draw.circle(surface, BLACK, (cx + 6, cy - 24), 3)
            pygame.draw.circle(surface, BLACK, (cx - 6, cy - 24), 3)
            pygame.draw.circle(surface, WHITE, (cx + 7, cy - 25), 1)
            pygame.draw.circle(surface, WHITE, (cx - 5, cy - 25), 1)
        
        # 嘴
        pygame.draw.arc(surface, BLACK, (cx - 6, cy - 20, 12, 6), 0, math.pi, 1)
        
        # 武器（剑）
        if self.facing == 1:
            pygame.draw.line(surface, GRAY, (cx + 12, cy - 20), (cx + 28, cy - 40), 2)
            pygame.draw.line(surface, GRAY, (cx + 12, cy - 20), (cx + 28, cy - 38), 1)
            # 剑格
            pygame.draw.line(surface, GOLD, (cx + 14, cy - 18), (cx + 18, cy - 22), 2)
        else:
            pygame.draw.line(surface, GRAY, (cx - 12, cy - 20), (cx - 28, cy - 40), 2)
            pygame.draw.line(surface, GRAY, (cx - 12, cy - 20), (cx - 28, cy - 38), 1)
            pygame.draw.line(surface, GOLD, (cx - 14, cy - 18), (cx - 18, cy - 22), 2)
        
        # 姓名
        name_text = small_font.render("沙威码", True, DARK_RED)
        name_rect = name_text.get_rect(center=(cx, cy - 48))
        surface.blit(name_text, name_rect)
        
        # 绘制粒子
        for p in self.particles:
            p.draw(surface)
    
    def use_skill(self, skill_index, enemies):
        if skill_index < 0 or skill_index >= len(self.skills):
            return None, "无效技能"
        
        skill = self.skills[skill_index]
        
        # 寻找最近的敌人
        target = None
        min_dist = float('inf')
        for enemy in enemies:
            if enemy.alive:
                dist = math.hypot(self.x - enemy.x, self.y - enemy.y)
                if dist < min_dist:
                    min_dist = dist
                    target = enemy
        
        if skill.type == "damage" and not target:
            return None, "没有可攻击的敌人"
        
        return skill.use(self, target)

# 游戏主类
class Game:
    def __init__(self):
        self.player = Player()
        self.enemies = []
        self.particles = []
        self.messages = []
        self.message_timer = 0
        self.current_message = ""
        self.game_over = False
        self.win = False
        self.selected_skill = 0
        self.spawn_timer = 0
        self.boss_spawned = False
        self.wave = 1
        self.enemies_per_wave = 3
        self.enemies_spawned = 0
        
        # 创建初始敌人
        self.spawn_wave()
        
        # UI按钮区域
        self.skill_buttons = []
        self.create_skill_buttons()
    
    def create_skill_buttons(self):
        self.skill_buttons = []
        for i, skill in enumerate(self.player.skills):
            x = 20 + i * 120
            y = HEIGHT - 60
            rect = pygame.Rect(x, y, 100, 40)
            self.skill_buttons.append((rect, i, skill))
    
    def spawn_wave(self):
        enemy_names = [
            "流寇", "山贼", "剑客", "刀客", "镖师", "游侠", "隐士", "武僧"
        ]
        
        for i in range(self.enemies_per_wave):
            name = random.choice(enemy_names)
            hp = 20 + self.wave * 5
            damage = 5 + self.wave * 2
            defense = 2 + self.wave
            speed = 1 + self.wave * 0.1
            color = random.choice([RED, ORANGE, PURPLE, BLUE, DARK_GREEN])
            reward = 10 + self.wave * 5
            
            enemy = Enemy(name, hp, damage, defense, speed, color, reward, "normal")
            self.enemies.append(enemy)
        
        self.enemies_spawned = 0
        self.boss_spawned = False
    
    def update(self, keys):
        if self.game_over or self.win:
            if keys[pygame.K_r]:
                self.__init__()
            return
        
        # 更新玩家
        self.player.update(keys)
        
        # 更新敌人
        player_pos = (self.player.x, self.player.y)
        for enemy in self.enemies:
            enemy.update(player_pos)
        
        # 敌人攻击玩家
        for enemy in self.enemies:
            if enemy.alive:
                dist = math.hypot(self.player.x - enemy.x, self.player.y - enemy.y)
                if dist < 60:
                    # 敌人攻击
                    if random.random() < 0.02:
                        damage = enemy.attack_player(self.player)
                        self.add_message(f"{enemy.name} 攻击！造成 {damage} 点伤害！", RED)
                        if self.player.hp <= 0:
                            self.player.alive = False
                            self.game_over = True
        
        # 检查是否所有敌人都被消灭
        alive_enemies = [e for e in self.enemies if e.alive]
        if not alive_enemies and not self.boss_spawned:
            if self.wave % 3 == 0:
                # 生成BOSS
                self.spawn_boss()
                self.boss_spawned = True
            else:
                self.wave += 1
                self.enemies_per_wave = min(8, self.enemies_per_wave + 1)
                self.spawn_wave()
                self.add_message(f"第 {self.wave} 波敌人来袭！", GOLD)
        
        # 检查是否胜利（击败BOSS）
        if self.boss_spawned:
            alive_bosses = [e for e in self.enemies if e.alive and e.type == "boss"]
            if not alive_bosses:
                self.win = True
        
        # 更新消息
        if self.message_timer > 0:
            self.message_timer -= 1
    
    def spawn_boss(self):
        boss = Enemy("沙威码大魔王", 80 + self.wave * 10, 15 + self.wave * 3, 8 + self.wave, 1.5, DARK_RED, 100, "boss")
        self.enemies.append(boss)
        self.add_message("⚠️ 沙威码大魔王出现了！", RED)
    
    def add_message(self, text, color=WHITE):
        self.current_message = text
        self.message_timer = 120  # 2秒
        self.messages.append((text, color))
        if len(self.messages) > 10:
            self.messages.pop(0)
    
    def use_skill(self, index):
        result, message = self.player.use_skill(index, self.enemies)
        if result is not None:
            self.add_message(message, GOLD)
            # 检查敌人是否死亡
            for enemy in self.enemies:
                if not enemy.alive:
                    self.player.gold += enemy.reward
                    self.player.xp += enemy.reward
                    self.player.kills += 1
                    # 升级检查
                    while self.player.xp >= self.player.xp_to_next:
                        self.player.xp -= self.player.xp_to_next
                        self.player.level += 1
                        self.player.xp_to_next = int(self.player.xp_to_next * 1.3)
                        self.player.max_hp += 10
                        self.player.hp = self.player.max_hp
                        self.player.max_qi += 5
                        self.player.attack += 2
                        self.player.defense += 1
                        self.add_message(f"🎉 升级！当前等级 {self.player.level}", GOLD)
                    self.add_message(f"击败 {enemy.name}！获得 {enemy.reward} 金币", YELLOW)
        else:
            self.add_message(message, RED)
    
    def draw(self, surface):
        # 背景
        gradient = pygame.Surface((WIDTH, HEIGHT))
        for y in range(HEIGHT):
            color = (220 - y * 0.1, 210 - y * 0.1, 200 - y * 0.05)
            pygame.draw.line(gradient, color, (0, y), (WIDTH, y))
        surface.blit(gradient, (0, 0))
        
        # 绘制地面纹理
        for x in range(0, WIDTH, 40):
            for y in range(120, HEIGHT, 40):
                if (x // 40 + y // 40) % 2 == 0:
                    pygame.draw.rect(surface, (200, 190, 180), (x, y, 40, 40))
        
        # 绘制敌人
        for enemy in self.enemies:
            enemy.draw(surface)
        
        # 绘制玩家
        self.player.draw(surface)
        
        # 绘制UI
        self.draw_ui(surface)
        
        # 游戏结束/胜利
        if self.game_over:
            overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
            overlay.fill((0, 0, 0, 180))
            surface.blit(overlay, (0, 0))
            
            text = huge_font.render("💀 沙威码倒下了", True, RED)
            text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 40))
            surface.blit(text, text_rect)
            
            restart = font.render("按 R 重新开始", True, WHITE)
            restart_rect = restart.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 40))
            surface.blit(restart, restart_rect)
        
        if self.win:
            overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
            overlay.fill((0, 0, 0, 180))
            surface.blit(overlay, (0, 0))
            
            text = huge_font.render("🏆 武林盟主！", True, GOLD)
            text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 60))
            surface.blit(text, text_rect)
            
            stats = font.render(f"等级: {self.player.level}  |  击杀: {self.player.kills}  |  金币: {self.player.gold}", True, WHITE)
            stats_rect = stats.get_rect(center=(WIDTH // 2, HEIGHT // 2))
            surface.blit(stats, stats_rect)
            
            restart = font.render("按 R 重新开始", True, WHITE)
            restart_rect = restart.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 50))
            surface.blit(restart, restart_rect)
    
    def draw_ui(self, surface):
        # 顶部信息栏
        ui_bg = pygame.Surface((WIDTH, 45), pygame.SRCALPHA)
        ui_bg.fill((0, 0, 0, 150))
        surface.blit(ui_bg, (0, 0))
        
        # 生命值
        hp_text = font.render(f"❤️ {int(self.player.hp)}/{int(self.player.max_hp)}", True, RED)
        surface.blit(hp_text, (10, 8))
        
        # 真气
        qi_text = font.render(f"💠 {int(self.player.qi)}/{int(self.player.max_qi)}", True, BLUE)
        surface.blit(qi_text, (170, 8))
        
        # 等级
        level_text = font.render(f"📈 Lv.{self.player.level}", True, GOLD)
        surface.blit(level_text, (330, 8))
        
        # 经验
        xp_text = font.render(f"⭐ {self.player.xp}/{self.player.xp_to_next}", True, WHITE)
        surface.blit(xp_text, (450, 8))
        
        # 金币
        gold_text = font.render(f"💰 {self.player.gold}", True, YELLOW)
        surface.blit(gold_text, (600, 8))
        
        # 击杀
        kill_text = font.render(f"⚔️ {self.player.kills}", True, RED)
        surface.blit(kill_text, (720, 8))
        
        # 波次
        wave_text = font.render(f"🌊 {self.wave}", True, WHITE)
        surface.blit(wave_text, (830, 8))
        
        # 消息显示
        if self.message_timer > 0:
            msg_surf = pygame.Surface((WIDTH - 100, 40), pygame.SRCALPHA)
            msg_surf.fill((0, 0, 0, 180))
            surface.blit(msg_surf, (50, 50))
            msg_text = font.render(self.current_message, True, WHITE)
            msg_rect = msg_text.get_rect(center=(WIDTH // 2, 70))
            surface.blit(msg_text, msg_rect)
        
        # 技能栏
        skill_bg = pygame.Surface((WIDTH, 50), pygame.SRCALPHA)
        skill_bg.fill((0, 0, 0, 150))
        surface.blit(skill_bg, (0, HEIGHT - 50))
        
        # 技能按钮
        for i, skill in enumerate(self.player.skills):
            x = 20 + i * 120
            y = HEIGHT - 45
            rect = pygame.Rect(x, y, 100, 35)
            
            # 按钮背景
            color = skill.color
            if skill.cooldown > 0:
                color = GRAY
            pygame.draw.rect(surface, color, rect, border_radius=5)
            pygame.draw.rect(surface, BLACK, rect, 2, border_radius=5)
            
            # 技能信息
            text = small_font.render(f"{skill.icon} {skill.name}", True, BLACK)
            text_rect = text.get_rect(center=(rect.centerx, rect.centery - 6))
            surface.blit(text, text_rect)
            
            cost_text = small_font.render(f"气{skill.cost}", True, BLACK)
            cost_rect = cost_text.get_rect(center=(rect.centerx, rect.centery + 14))
            surface.blit(cost_text, cost_rect)
            
            # 快捷键
            key_text = small_font.render(f"[{i+1}]", True, DARK_GRAY)
            surface.blit(key_text, (rect.right - 25, rect.y + 2))
            
            # 冷却显示
            if skill.cooldown > 0:
                cd_surf = pygame.Surface((100, 35), pygame.SRCALPHA)
                cd_surf.fill((0, 0, 0, 150))
                surface.blit(cd_surf, (x, y))
                cd_text = font.render(str(skill.cooldown), True, WHITE)
                cd_rect = cd_text.get_rect(center=(rect.centerx, rect.centery))
                surface.blit(cd_text, cd_rect)
        
        # 操作提示
        hint = small_font.render("WASD移动 | 数字键1-9技能 | R重新开始", True, (100, 100, 100))
        surface.blit(hint, (10, HEIGHT - 70))

# 主游戏函数
def main():
    game = Game()
    running = True
    
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_1:
                    game.use_skill(0)
                elif event.key == pygame.K_2 and len(game.player.skills) > 1:
                    game.use_skill(1)
                elif event.key == pygame.K_3 and len(game.player.skills) > 2:
                    game.use_skill(2)
                elif event.key == pygame.K_r:
                    game = Game()
            
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    # 检查技能按钮点击
                    for rect, idx, skill in game.skill_buttons:
                        if rect.collidepoint(event.pos):
                            game.use_skill(idx)
        
        keys = pygame.key.get_pressed()
        
        # 更新游戏
        game.update(keys)
        
        # 绘制
        game.draw(screen)
        pygame.display.flip()
        clock.tick(FPS)
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()