import pygame
import sys
import random
import math
from typing import List, Tuple, Optional

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

# 屏幕设置
WIDTH, HEIGHT = 1000, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("二维移动射击")
clock = pygame.time.Clock()

# 颜色定义
BACKGROUND = (15, 10, 25)
PLAYER_COLORS = {
    "body": (0, 200, 255),
    "outline": (255, 255, 255),
    "gun": (180, 180, 200)
}
ENEMY_COLORS = {
    "basic": (255, 80, 80),
    "fast": (80, 180, 255),
    "tank": (80, 255, 100),
    "shooter": (200, 80, 255)
}
BULLET_COLORS = {
    "player": (255, 255, 150),
    "enemy": (255, 100, 100)
}
UI_COLORS = {
    "health": (255, 50, 50),
    "health_bg": (100, 0, 0),
    "exp": (100, 200, 255),
    "exp_bg": (30, 60, 100),
    "text": (240, 240, 240),
    "text_dark": (150, 150, 170)
}
PARTICLE_COLORS = [
    (255, 255, 200),  # 黄色
    (255, 200, 100),  # 橙色
    (255, 100, 100),  # 红色
    (255, 255, 255)   # 白色
]

# 尝试加载中文字体
try:
    # 尝试常见中文字体
    font_names = ["msyh.ttc", "simhei.ttf", "simsun.ttc", "Deng.ttf", None]
    font_large = font_medium = font_small = None
    
    for font_name in font_names:
        try:
            if font_name is None:
                font_large = pygame.font.Font(None, 48)
                font_medium = pygame.font.Font(None, 32)
                font_small = pygame.font.Font(None, 20)
                break
            
            font_large = pygame.font.Font(font_name, 48)
            font_medium = pygame.font.Font(font_name, 32)
            font_small = pygame.font.Font(font_name, 20)
            
            # 测试能否显示中文
            test_surface = font_small.render("测试", True, (255, 255, 255))
            if test_surface.get_width() > 0:
                break
        except:
            continue
except:
    font_large = pygame.font.Font(None, 48)
    font_medium = pygame.font.Font(None, 32)
    font_small = pygame.font.Font(None, 20)

class Vector2:
    """二维向量"""
    def __init__(self, x=0.0, y=0.0):
        self.x = x
        self.y = y
    
    def __add__(self, other):
        return Vector2(self.x + other.x, self.y + other.y)
    
    def __sub__(self, other):
        return Vector2(self.x - other.x, self.y - other.y)
    
    def __mul__(self, scalar):
        return Vector2(self.x * scalar, self.y * scalar)
    
    def length(self):
        return math.sqrt(self.x * self.x + self.y * self.y)
    
    def normalize(self):
        length = self.length()
        if length > 0:
            return Vector2(self.x / length, self.y / length)
        return Vector2(0, 0)
    
    def rotate(self, angle):
        """旋转向量（角度制）"""
        rad = math.radians(angle)
        cos_a = math.cos(rad)
        sin_a = math.sin(rad)
        return Vector2(
            self.x * cos_a - self.y * sin_a,
            self.x * sin_a + self.y * cos_a
        )
    
    def to_tuple(self):
        return (int(self.x), int(self.y))

class Particle:
    """粒子效果"""
    def __init__(self, pos, velocity, color, size=3, lifetime=1.0):
        self.pos = Vector2(pos.x, pos.y)
        self.velocity = Vector2(velocity.x, velocity.y)
        self.color = color
        self.size = size
        self.lifetime = lifetime
        self.max_lifetime = lifetime
    
    def update(self, dt):
        self.lifetime -= dt
        if self.lifetime <= 0:
            return False
        
        # 物理更新
        self.pos = self.pos + self.velocity * dt * 60
        self.velocity = self.velocity * 0.95  # 空气阻力
        
        return True
    
    def draw(self, surface):
        alpha = int(255 * (self.lifetime / self.max_lifetime))
        if alpha > 0:
            temp_surf = pygame.Surface((int(self.size * 2), int(self.size * 2)), pygame.SRCALPHA)
            pygame.draw.circle(temp_surf, (*self.color[:3], alpha), 
                             (int(self.size), int(self.size)), int(self.size))
            surface.blit(temp_surf, (int(self.pos.x - self.size), int(self.pos.y - self.size)))

class Explosion:
    """爆炸效果"""
    def __init__(self, pos, color=(255, 200, 50), size=30):
        self.pos = Vector2(pos.x, pos.y)
        self.particles = []
        self.size = size
        
        # 创建爆炸粒子
        for _ in range(20):
            angle = random.uniform(0, math.pi * 2)
            speed = random.uniform(2, 6)
            velocity = Vector2(math.cos(angle), math.sin(angle)) * speed
            particle_color = random.choice(PARTICLE_COLORS)
            self.particles.append(
                Particle(self.pos, velocity, particle_color, 
                        random.uniform(2, 5), random.uniform(0.5, 1.0))
            )
    
    def update(self, dt):
        for particle in self.particles[:]:
            if not particle.update(dt):
                self.particles.remove(particle)
        return len(self.particles) > 0
    
    def draw(self, surface):
        for particle in self.particles:
            particle.draw(surface)

class Player:
    """玩家类"""
    def __init__(self):
        self.pos = Vector2(WIDTH // 2, HEIGHT // 2)
        self.velocity = Vector2(0, 0)
        self.speed = 5.0
        self.radius = 20
        self.health = 100
        self.max_health = 100
        self.level = 1
        self.exp = 0
        self.exp_to_next = 100
        
        # 射击属性
        self.shoot_delay = 0.2
        self.shoot_timer = 0
        self.bullet_damage = 10
        self.bullet_speed = 12
        
        # 状态
        self.invincible = False
        self.invincible_timer = 0
        self.trail = []  # 轨迹点
        self.trail_length = 8
        
        # 特殊能力
        self.special_active = False
        self.special_timer = 0
        self.special_type = None  # "rapid", "shield", "explosive"
    
    def update(self, dt, keys, mouse_pos, mouse_buttons):
        """更新玩家状态"""
        # 移动控制
        self.velocity = Vector2(0, 0)
        
        if keys[pygame.K_w] or keys[pygame.K_UP]:
            self.velocity.y -= 1
        if keys[pygame.K_s] or keys[pygame.K_DOWN]:
            self.velocity.y += 1
        if keys[pygame.K_a] or keys[pygame.K_LEFT]:
            self.velocity.x -= 1
        if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
            self.velocity.x += 1
        
        # 标准化速度
        if self.velocity.length() > 0:
            self.velocity = self.velocity.normalize() * self.speed
        
        # 更新位置
        self.pos = self.pos + self.velocity * dt * 60
        
        # 边界限制
        self.pos.x = max(self.radius, min(WIDTH - self.radius, self.pos.x))
        self.pos.y = max(self.radius, min(HEIGHT - self.radius, self.pos.y))
        
        # 更新轨迹
        self.trail.append(Vector2(self.pos.x, self.pos.y))
        if len(self.trail) > self.trail_length:
            self.trail.pop(0)
        
        # 更新射击计时器
        if self.shoot_timer > 0:
            self.shoot_timer -= dt
        
        # 更新无敌时间
        if self.invincible:
            self.invincible_timer -= dt
            if self.invincible_timer <= 0:
                self.invincible = False
        
        # 更新特殊能力
        if self.special_active:
            self.special_timer -= dt
            if self.special_timer <= 0:
                self.special_active = False
                self.special_type = None
        
        # 自动射击
        if mouse_buttons[0]:  # 左键
            return self.shoot(mouse_pos)
        return []
    
    def shoot(self, mouse_pos):
        """射击，返回子弹列表"""
        if self.shoot_timer > 0:
            return []
        
        direction = Vector2(mouse_pos[0] - self.pos.x, 
                          mouse_pos[1] - self.pos.y)
        
        if direction.length() == 0:
            return []
        
        direction = direction.normalize()
        
        # 根据特殊能力调整射击
        bullets = []
        if self.special_active and self.special_type == "rapid":
            # 快速射击模式
            self.shoot_timer = self.shoot_delay * 0.3
            bullet_count = 3
        else:
            self.shoot_timer = self.shoot_delay
            bullet_count = 1
        
        for _ in range(bullet_count):
            bullet_pos = self.pos + direction * (self.radius + 5)
            bullet = Bullet(bullet_pos, direction, "player", 
                          self.bullet_speed, self.bullet_damage)
            
            if self.special_active and self.special_type == "explosive":
                bullet.explosive = True
            
            bullets.append(bullet)
        
        return bullets
    
    def take_damage(self, damage):
        """受到伤害"""
        if self.invincible or self.special_active and self.special_type == "shield":
            return False
        
        self.health -= damage
        self.invincible = True
        self.invincible_timer = 1.0
        return self.health <= 0
    
    def heal(self, amount):
        """治疗"""
        self.health = min(self.max_health, self.health + amount)
    
    def add_exp(self, amount):
        """增加经验"""
        self.exp += amount
        if self.exp >= self.exp_to_next:
            self.level_up()
    
    def level_up(self):
        """升级"""
        self.exp -= self.exp_to_next
        self.level += 1
        self.exp_to_next = int(self.exp_to_next * 1.5)
        
        # 升级奖励
        self.max_health += 20
        self.health = self.max_health
        self.bullet_damage += 2
        self.shoot_delay = max(0.1, self.shoot_delay * 0.9)
    
    def activate_special(self, special_type, duration=5.0):
        """激活特殊能力"""
        self.special_active = True
        self.special_type = special_type
        self.special_timer = duration
        
        if special_type == "shield":
            self.invincible = True
    
    def draw(self, surface):
        """绘制玩家"""
        # 绘制轨迹
        for i, pos in enumerate(self.trail):
            alpha = int(100 * (i / len(self.trail)))
            radius = int(self.radius * 0.5 * (i / len(self.trail)))
            pygame.draw.circle(surface, (*PLAYER_COLORS["body"][:3], alpha), 
                             pos.to_tuple(), radius)
        
        # 绘制玩家主体
        if self.invincible and int(pygame.time.get_ticks() / 100) % 2 == 0:
            color = (255, 255, 255)  # 闪烁
        elif self.special_active and self.special_type == "shield":
            color = (100, 200, 255)  # 护盾颜色
        else:
            color = PLAYER_COLORS["body"]
        
        # 主体
        pygame.draw.circle(surface, color, self.pos.to_tuple(), self.radius)
        pygame.draw.circle(surface, PLAYER_COLORS["outline"], 
                          self.pos.to_tuple(), self.radius, 2)
        
        # 绘制方向指示器
        mouse_pos = pygame.mouse.get_pos()
        direction = Vector2(mouse_pos[0] - self.pos.x, 
                          mouse_pos[1] - self.pos.y)
        if direction.length() > 0:
            direction = direction.normalize()
            gun_tip = self.pos + direction * (self.radius + 10)
            pygame.draw.line(surface, PLAYER_COLORS["gun"], 
                           self.pos.to_tuple(), gun_tip.to_tuple(), 4)
            
            # 绘制准星
            cross_size = 8
            pygame.draw.line(surface, (255, 255, 200, 150),
                           (gun_tip.x - cross_size, gun_tip.y),
                           (gun_tip.x + cross_size, gun_tip.y), 2)
            pygame.draw.line(surface, (255, 255, 200, 150),
                           (gun_tip.x, gun_tip.y - cross_size),
                           (gun_tip.x, gun_tip.y + cross_size), 2)
        
        # 特殊能力指示
        if self.special_active:
            # 绘制特殊能力光环
            ring_radius = self.radius + 5 + math.sin(pygame.time.get_ticks() * 0.01) * 3
            if self.special_type == "rapid":
                ring_color = (255, 255, 100, 100)
            elif self.special_type == "shield":
                ring_color = (100, 200, 255, 150)
            else:  # explosive
                ring_color = (255, 100, 100, 100)
            
            temp_surf = pygame.Surface((int(ring_radius * 2), int(ring_radius * 2)), pygame.SRCALPHA)
            pygame.draw.circle(temp_surf, ring_color, 
                             (int(ring_radius), int(ring_radius)), 
                             int(ring_radius), 3)
            surface.blit(temp_surf, (int(self.pos.x - ring_radius), int(self.pos.y - ring_radius)))

class Bullet:
    """子弹类"""
    def __init__(self, pos, direction, owner, speed=10, damage=10):
        self.pos = Vector2(pos.x, pos.y)
        self.direction = direction.normalize()
        self.speed = speed
        self.damage = damage
        self.owner = owner  # "player" 或 "enemy"
        self.radius = 4 if owner == "player" else 5
        self.explosive = False
        self.trail = []
        self.trail_length = 5
    
    def update(self, dt):
        """更新子弹位置"""
        # 保存轨迹
        self.trail.append(Vector2(self.pos.x, self.pos.y))
        if len(self.trail) > self.trail_length:
            self.trail.pop(0)
        
        # 移动
        self.pos = self.pos + self.direction * self.speed * dt * 60
        
        # 检查边界
        if (self.pos.x < -50 or self.pos.x > WIDTH + 50 or
            self.pos.y < -50 or self.pos.y > HEIGHT + 50):
            return False
        
        return True
    
    def draw(self, surface):
        """绘制子弹"""
        # 绘制轨迹
        for i, pos in enumerate(self.trail):
            alpha = int(150 * (i / len(self.trail)))
            radius = int(self.radius * 0.5 * (i / len(self.trail)))
            if radius > 0:
                color = BULLET_COLORS[self.owner]
                pygame.draw.circle(surface, (*color[:3], alpha), 
                                 pos.to_tuple(), radius)
        
        # 绘制子弹主体
        color = BULLET_COLORS[self.owner]
        if self.explosive:
            # 爆炸子弹特殊效果
            pulse = 1 + math.sin(pygame.time.get_ticks() * 0.01) * 0.3
            radius = int(self.radius * pulse)
            pygame.draw.circle(surface, (255, 200, 100), 
                             self.pos.to_tuple(), radius)
            pygame.draw.circle(surface, (255, 100, 50), 
                             self.pos.to_tuple(), radius, 1)
        else:
            pygame.draw.circle(surface, color, self.pos.to_tuple(), self.radius)
            pygame.draw.circle(surface, (255, 255, 255), 
                             self.pos.to_tuple(), self.radius, 1)
            
            # 子弹尖端
            tip_pos = self.pos + self.direction * self.radius
            pygame.draw.circle(surface, (255, 255, 200), 
                             tip_pos.to_tuple(), self.radius // 2)

class Enemy:
    """敌人类"""
    def __init__(self, enemy_type="basic", level=1):
        self.type = enemy_type
        self.level = level
        
        # 在屏幕边缘生成
        side = random.choice(['top', 'bottom', 'left', 'right'])
        if side == 'top':
            self.pos = Vector2(random.randint(0, WIDTH), -50)
        elif side == 'bottom':
            self.pos = Vector2(random.randint(0, WIDTH), HEIGHT + 50)
        elif side == 'left':
            self.pos = Vector2(-50, random.randint(0, HEIGHT))
        else:  # right
            self.pos = Vector2(WIDTH + 50, random.randint(0, HEIGHT))
        
        self.velocity = Vector2(0, 0)
        
        # 根据类型设置属性
        self.set_attributes()
        
        self.health = self.max_health
        self.shoot_timer = random.uniform(0, self.shoot_delay)
        self.score_value = self.base_score * level
        self.active = True
        
        # 特殊行为
        self.special_timer = 0
        self.special_cooldown = 0
    
    def set_attributes(self):
        """设置敌人属性"""
        level_mult = 1 + (self.level - 1) * 0.2
        
        if self.type == "basic":
            self.radius = 18
            self.max_health = 30 * level_mult
            self.speed = 2.0
            self.damage = 10
            self.shoot_delay = 999  # 不射击
            self.color = ENEMY_COLORS["basic"]
            self.base_score = 10
        elif self.type == "fast":
            self.radius = 14
            self.max_health = 20 * level_mult
            self.speed = 3.5
            self.damage = 8
            self.shoot_delay = 999
            self.color = ENEMY_COLORS["fast"]
            self.base_score = 15
        elif self.type == "tank":
            self.radius = 30
            self.max_health = 100 * level_mult
            self.speed = 1.2
            self.damage = 20
            self.shoot_delay = 999
            self.color = ENEMY_COLORS["tank"]
            self.base_score = 30
        elif self.type == "shooter":
            self.radius = 16
            self.max_health = 25 * level_mult
            self.speed = 1.8
            self.damage = 12
            self.shoot_delay = 2.0
            self.color = ENEMY_COLORS["shooter"]
            self.base_score = 20
    
    def update(self, dt, player_pos):
        """更新敌人"""
        if not self.active:
            return False
        
        # 计算移动方向
        direction = player_pos - self.pos
        distance = direction.length()
        
        if distance > 0:
            direction = direction.normalize()
            
            # 不同类型有不同的移动策略
            if self.type == "fast":
                # 快速敌人有随机移动
                jitter = Vector2(random.uniform(-0.3, 0.3), 
                               random.uniform(-0.3, 0.3))
                direction = (direction + jitter).normalize()
            elif self.type == "shooter":
                # 射击者保持距离
                if distance < 200:
                    direction = -direction
            
            self.velocity = direction * self.speed
        else:
            self.velocity = Vector2(0, 0)
        
        # 更新位置
        self.pos = self.pos + self.velocity * dt * 60
        
        # 更新射击计时器
        if self.shoot_timer > 0:
            self.shoot_timer -= dt
        
        # 检查是否出界
        margin = 100
        if (self.pos.x < -margin or self.pos.x > WIDTH + margin or
            self.pos.y < -margin or self.pos.y > HEIGHT + margin):
            return False
        
        return self.health > 0
    
    def shoot(self, player_pos):
        """射击，返回子弹列表"""
        if self.shoot_timer > 0 or self.type not in ["shooter"]:
            return []
        
        direction = (player_pos - self.pos).normalize()
        bullet = Bullet(self.pos, direction, "enemy", 8, self.damage)
        self.shoot_timer = self.shoot_delay
        
        return [bullet]
    
    def take_damage(self, damage):
        """受到伤害"""
        self.health -= damage
        if self.health <= 0:
            self.active = False
            return True
        return False
    
    def draw(self, surface):
        """绘制敌人"""
        if not self.active:
            return
        
        # 主体
        pygame.draw.circle(surface, self.color, self.pos.to_tuple(), self.radius)
        pygame.draw.circle(surface, (255, 255, 255), 
                          self.pos.to_tuple(), self.radius, 2)
        
        # 类型标识
        if self.type == "shooter":
            # 瞄准器
            pygame.draw.circle(surface, (255, 255, 255), 
                             self.pos.to_tuple(), self.radius - 5, 2)
            pygame.draw.line(surface, (255, 255, 255),
                           (self.pos.x - 4, self.pos.y),
                           (self.pos.x + 4, self.pos.y), 2)
            pygame.draw.line(surface, (255, 255, 255),
                           (self.pos.x, self.pos.y - 4),
                           (self.pos.x, self.pos.y + 4), 2)
        elif self.type == "tank":
            # 装甲板
            for angle in [0, 90, 180, 270]:
                dir_vec = Vector2(math.cos(math.radians(angle)), 
                                math.sin(math.radians(angle)))
                armor_pos = self.pos + dir_vec * (self.radius - 5)
                pygame.draw.circle(surface, (150, 150, 150), 
                                 armor_pos.to_tuple(), 6)
        
        # 生命条
        if self.health < self.max_health:
            bar_width = self.radius * 2
            bar_height = 6
            bar_x = self.pos.x - bar_width / 2
            bar_y = self.pos.y - self.radius - 10
            
            # 背景
            pygame.draw.rect(surface, UI_COLORS["health_bg"], 
                           (bar_x, bar_y, bar_width, bar_height))
            
            # 生命值
            health_width = int(bar_width * (self.health / self.max_health))
            health_color = (50, 255, 100) if self.health > self.max_health * 0.3 else (255, 200, 50)
            pygame.draw.rect(surface, health_color, 
                           (bar_x, bar_y, health_width, bar_height))

class PowerUp:
    """强化道具"""
    def __init__(self, pos, power_type):
        self.pos = Vector2(pos.x, pos.y)
        self.type = power_type
        self.radius = 12
        self.lifetime = 10.0
        self.float_offset = 0
        
        # 设置颜色和值
        if power_type == "health":
            self.color = (255, 50, 50)
            self.value = 30
        elif power_type == "rapid":
            self.color = (255, 200, 50)
            self.value = 5.0
        elif power_type == "shield":
            self.color = (50, 150, 255)
            self.value = 5.0
        elif power_type == "explosive":
            self.color = (255, 100, 100)
            self.value = 5.0
    
    def update(self, dt):
        """更新道具"""
        self.lifetime -= dt
        if self.lifetime <= 0:
            return False
        
        # 浮动效果
        self.float_offset += dt * 3
        self.pos.y += math.sin(self.float_offset) * 0.5
        
        return True
    
    def draw(self, surface):
        """绘制道具"""
        # 主体
        pygame.draw.circle(surface, self.color, self.pos.to_tuple(), self.radius)
        
        # 发光效果
        glow_size = int(self.radius + 3 + math.sin(pygame.time.get_ticks() * 0.01) * 2)
        pygame.draw.circle(surface, (*self.color[:3], 100), 
                          self.pos.to_tuple(), glow_size, 2)
        
        # 图标
        if self.type == "health":
            # 加号
            pygame.draw.rect(surface, (255, 255, 255), 
                           (self.pos.x - 4, self.pos.y - 1, 8, 2))
            pygame.draw.rect(surface, (255, 255, 255), 
                           (self.pos.x - 1, self.pos.y - 4, 2, 8))
        elif self.type == "rapid":
            # 子弹
            pygame.draw.circle(surface, (255, 255, 255), 
                             self.pos.to_tuple(), 4)
        elif self.type == "shield":
            # 盾牌
            pygame.draw.circle(surface, (255, 255, 255), 
                             self.pos.to_tuple(), 8, 2)
        else:  # explosive
            # 爆炸
            for angle in [0, 45, 90, 135]:
                dir_vec = Vector2(math.cos(math.radians(angle)), 
                                math.sin(math.radians(angle)))
                tip = self.pos + dir_vec * 6
                pygame.draw.line(surface, (255, 255, 255), 
                               self.pos.to_tuple(), tip.to_tuple(), 2)

class Game:
    """游戏主类"""
    def __init__(self):
        self.player = Player()
        self.enemies = []
        self.bullets = []
        self.enemy_bullets = []
        self.explosions = []
        self.powerups = []
        
        self.score = 0
        self.wave = 1
        self.enemies_per_wave = 5
        self.enemies_spawned = 0
        self.enemy_spawn_timer = 0
        self.enemy_spawn_delay = 1.0
        
        self.game_over = False
        self.paused = False
        
        # 背景星星
        self.stars = []
        for _ in range(150):
            self.stars.append({
                'x': random.randint(0, WIDTH),
                'y': random.randint(0, HEIGHT),
                'size': random.uniform(0.5, 2),
                'speed': random.uniform(0.1, 0.8),
                'brightness': random.randint(100, 255)
            })
        
        # 波次提示
        self.wave_text_timer = 0
    
    def spawn_enemy(self):
        """生成敌人"""
        if self.enemies_spawned >= self.enemies_per_wave:
            return
        
        # 根据波次决定敌人类型
        enemy_types = ["basic", "fast", "tank", "shooter"]
        weights = [0.4, 0.3, 0.2, 0.1]
        
        # 随着波次增加，提高高级敌人权重
        for i in range(1, len(weights)):
            weights[i] += (self.wave - 1) * 0.05
        
        # 归一化
        total = sum(weights)
        weights = [w / total for w in weights]
        
        enemy_type = random.choices(enemy_types, weights=weights, k=1)[0]
        enemy = Enemy(enemy_type, self.wave)
        self.enemies.append(enemy)
        self.enemies_spawned += 1
    
    def spawn_powerup(self, pos, chance=0.2):
        """生成强化道具"""
        if random.random() < chance:
            power_types = ["health", "rapid", "shield", "explosive"]
            weights = [0.4, 0.2, 0.2, 0.2]
            power_type = random.choices(power_types, weights=weights, k=1)[0]
            self.powerups.append(PowerUp(pos, power_type))
    
    def check_collisions(self):
        """检查碰撞"""
        player_rect = pygame.Rect(
            self.player.pos.x - self.player.radius,
            self.player.pos.y - self.player.radius,
            self.player.radius * 2,
            self.player.radius * 2
        )
        
        # 玩家子弹 vs 敌人
        for bullet in self.bullets[:]:
            bullet_rect = pygame.Rect(
                bullet.pos.x - bullet.radius,
                bullet.pos.y - bullet.radius,
                bullet.radius * 2,
                bullet.radius * 2
            )
            
            for enemy in self.enemies[:]:
                if not enemy.active:
                    continue
                    
                enemy_rect = pygame.Rect(
                    enemy.pos.x - enemy.radius,
                    enemy.pos.y - enemy.radius,
                    enemy.radius * 2,
                    enemy.radius * 2
                )
                
                if bullet_rect.colliderect(enemy_rect):
                    if enemy.take_damage(bullet.damage):
                        # 敌人死亡
                        self.score += enemy.score_value
                        self.player.add_exp(enemy.score_value)
                        self.explosions.append(Explosion(enemy.pos))
                        
                        # 生成强化道具
                        self.spawn_powerup(enemy.pos)
                        
                        self.enemies.remove(enemy)
                    
                    # 爆炸子弹产生范围伤害
                    if bullet.explosive:
                        self.explosions.append(Explosion(bullet.pos, (255, 150, 50), 40))
                    
                    if bullet in self.bullets:
                        self.bullets.remove(bullet)
                    break
        
        # 敌人子弹 vs 玩家
        for bullet in self.enemy_bullets[:]:
            bullet_rect = pygame.Rect(
                bullet.pos.x - bullet.radius,
                bullet.pos.y - bullet.radius,
                bullet.radius * 2,
                bullet.radius * 2
            )
            
            if bullet_rect.colliderect(player_rect):
                if self.player.take_damage(bullet.damage):
                    self.game_over = True
                    self.explosions.append(Explosion(self.player.pos, size=50))
                
                if bullet in self.enemy_bullets:
                    self.enemy_bullets.remove(bullet)
        
        # 敌人 vs 玩家
        for enemy in self.enemies[:]:
            if not enemy.active:
                continue
                
            enemy_rect = pygame.Rect(
                enemy.pos.x - enemy.radius,
                enemy.pos.y - enemy.radius,
                enemy.radius * 2,
                enemy.radius * 2
            )
            
            if enemy_rect.colliderect(player_rect):
                if self.player.take_damage(enemy.damage):
                    self.game_over = True
                    self.explosions.append(Explosion(self.player.pos, size=50))
                
                # 敌人反弹
                direction = enemy.pos - self.player.pos
                if direction.length() > 0:
                    enemy.velocity = direction.normalize() * 3
        
        # 强化道具 vs 玩家
        for powerup in self.powerups[:]:
            powerup_rect = pygame.Rect(
                powerup.pos.x - powerup.radius,
                powerup.pos.y - powerup.radius,
                powerup.radius * 2,
                powerup.radius * 2
            )
            
            if powerup_rect.colliderect(player_rect):
                self.apply_powerup(powerup)
                self.powerups.remove(powerup)
    
    def apply_powerup(self, powerup):
        """应用强化道具"""
        if powerup.type == "health":
            self.player.heal(powerup.value)
        elif powerup.type == "rapid":
            self.player.activate_special("rapid", powerup.value)
        elif powerup.type == "shield":
            self.player.activate_special("shield", powerup.value)
        elif powerup.type == "explosive":
            self.player.activate_special("explosive", powerup.value)
    
    def next_wave(self):
        """下一波"""
        self.wave += 1
        self.enemies_spawned = 0
        self.enemies_per_wave = 5 + self.wave * 2
        self.wave_text_timer = 3.0
        
        # 每5波增加难度
        if self.wave % 5 == 0:
            self.enemies_per_wave += 5
    
    def update(self, dt, keys, mouse_pos, mouse_buttons):
        """更新游戏"""
        if self.game_over or self.paused:
            return
        
        # 更新玩家
        new_bullets = self.player.update(dt, keys, mouse_pos, mouse_buttons)
        self.bullets.extend(new_bullets)
        
        # 生成敌人
        if self.enemies_spawned < self.enemies_per_wave:
            self.enemy_spawn_timer += dt
            if self.enemy_spawn_timer >= self.enemy_spawn_delay:
                self.spawn_enemy()
                self.enemy_spawn_timer = 0
        
        # 波次完成检查
        elif len(self.enemies) == 0:
            self.next_wave()
        
        # 更新波次文本计时器
        if self.wave_text_timer > 0:
            self.wave_text_timer -= dt
        
        # 更新敌人
        for enemy in self.enemies[:]:
            if not enemy.update(dt, self.player.pos):
                self.enemies.remove(enemy)
            else:
                # 敌人射击
                enemy_bullets = enemy.shoot(self.player.pos)
                self.enemy_bullets.extend(enemy_bullets)
        
        # 更新玩家子弹
        for bullet in self.bullets[:]:
            if not bullet.update(dt):
                self.bullets.remove(bullet)
        
        # 更新敌人子弹
        for bullet in self.enemy_bullets[:]:
            if not bullet.update(dt):
                self.enemy_bullets.remove(bullet)
        
        # 更新爆炸效果
        for explosion in self.explosions[:]:
            if not explosion.update(dt):
                self.explosions.remove(explosion)
        
        # 更新强化道具
        for powerup in self.powerups[:]:
            if not powerup.update(dt):
                self.powerups.remove(powerup)
        
        # 检查碰撞
        self.check_collisions()
        
        # 更新星星背景
        for star in self.stars:
            star['y'] += star['speed']
            if star['y'] > HEIGHT:
                star['y'] = 0
                star['x'] = random.randint(0, WIDTH)
    
    def draw_background(self, surface):
        """绘制背景"""
        # 深色背景
        surface.fill(BACKGROUND)
        
        # 星星
        for star in self.stars:
            brightness = star['brightness']
            color = (brightness, brightness, brightness)
            pygame.draw.circle(surface, color, 
                             (int(star['x']), int(star['y'])), 
                             star['size'])
        
        # 网格
        grid_color = (30, 25, 40, 30)
        for x in range(0, WIDTH, 50):
            pygame.draw.line(surface, grid_color, (x, 0), (x, HEIGHT), 1)
        for y in range(0, HEIGHT, 50):
            pygame.draw.line(surface, grid_color, (0, y), (WIDTH, y), 1)
    
    def draw_ui(self, surface):
        """绘制UI"""
        # 分数
        score_text = font_medium.render(f"分数: {self.score}", True, UI_COLORS["text"])
        surface.blit(score_text, (20, 20))
        
        # 波次
        wave_text = font_medium.render(f"波次: {self.wave}", True, UI_COLORS["text"])
        surface.blit(wave_text, (20, 60))
        
        # 等级
        level_text = font_medium.render(f"等级: {self.player.level}", True, UI_COLORS["text"])
        surface.blit(level_text, (20, 100))
        
        # 生命条
        health_bar_width = 200
        health_bar_height = 20
        health_x = WIDTH - health_bar_width - 20
        health_y = 20
        
        # 背景
        pygame.draw.rect(surface, UI_COLORS["health_bg"], 
                        (health_x, health_y, health_bar_width, health_bar_height))
        
        # 生命值
        health_width = int(health_bar_width * (self.player.health / self.player.max_health))
        health_color = (50, 255, 100) if self.player.health > self.player.max_health * 0.3 else (255, 200, 50)
        pygame.draw.rect(surface, health_color, 
                        (health_x, health_y, health_width, health_bar_height))
        
        # 生命值文字
        health_text = font_small.render(f"{int(self.player.health)}/{self.player.max_health}", 
                                       True, UI_COLORS["text"])
        surface.blit(health_text, (health_x + health_bar_width // 2 - health_text.get_width() // 2, 
                                 health_y + 2))
        
        # 经验条
        exp_bar_width = 200
        exp_bar_height = 10
        exp_x = WIDTH - exp_bar_width - 20
        exp_y = 50
        
        # 背景
        pygame.draw.rect(surface, UI_COLORS["exp_bg"], 
                        (exp_x, exp_y, exp_bar_width, exp_bar_height))
        
        # 经验值
        exp_width = int(exp_bar_width * (self.player.exp / self.player.exp_to_next))
        pygame.draw.rect(surface, UI_COLORS["exp"], 
                        (exp_x, exp_y, exp_width, exp_bar_height))
        
        # 经验值文字
        exp_text = font_small.render(f"经验: {self.player.exp}/{self.player.exp_to_next}", 
                                    True, UI_COLORS["text"])
        surface.blit(exp_text, (exp_x + exp_bar_width // 2 - exp_text.get_width() // 2, exp_y - 18))
        
        # 伤害显示
        damage_text = font_small.render(f"伤害: {self.player.bullet_damage}", 
                                       True, UI_COLORS["text_dark"])
        surface.blit(damage_text, (20, HEIGHT - 60))
        
        # 射速显示
        fire_rate = 1 / self.player.shoot_delay
        fire_rate_text = font_small.render(f"射速: {fire_rate:.1f}/秒", 
                                         True, UI_COLORS["text_dark"])
        surface.blit(fire_rate_text, (20, HEIGHT - 30))
        
        # 特殊能力显示
        if self.player.special_active:
            special_name = {
                "rapid": "快速射击",
                "shield": "护盾",
                "explosive": "爆炸子弹"
            }.get(self.player.special_type, "")
            
            special_text = font_small.render(f"{special_name}: {self.player.special_timer:.1f}s", 
                                           True, (255, 255, 100))
            surface.blit(special_text, (WIDTH - special_text.get_width() - 20, 100))
        
        # 控制提示
        controls = [
            "WASD/方向键: 移动",
            "鼠标左键: 射击",
            "P: 暂停游戏",
            "R: 重新开始"
        ]
        
        for i, text in enumerate(controls):
            control_text = font_small.render(text, True, UI_COLORS["text_dark"])
            surface.blit(control_text, (WIDTH - control_text.get_width() - 20, 
                                      HEIGHT - 100 + i * 25))
    
    def draw_wave_text(self, surface):
        """绘制波次文本"""
        if self.wave_text_timer > 0:
            alpha = min(255, int(self.wave_text_timer * 150))
            wave_text = font_large.render(f"第 {self.wave} 波", True, (255, 255, 255, alpha))
            surface.blit(wave_text, (WIDTH // 2 - wave_text.get_width() // 2, 
                                   HEIGHT // 2 - wave_text.get_height() // 2))
    
    def draw_game_over(self, surface):
        """绘制游戏结束界面"""
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 150))
        surface.blit(overlay, (0, 0))
        
        # 游戏结束文字
        game_over_text = font_large.render("游戏结束", True, (255, 50, 50))
        surface.blit(game_over_text, (WIDTH // 2 - game_over_text.get_width() // 2, 
                                    HEIGHT // 2 - 60))
        
        # 最终分数
        score_text = font_medium.render(f"最终分数: {self.score}", True, UI_COLORS["text"])
        surface.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, 
                                HEIGHT // 2))
        
        # 最终波次
        wave_text = font_medium.render(f"到达波次: {self.wave}", True, UI_COLORS["text"])
        surface.blit(wave_text, (WIDTH // 2 - wave_text.get_width() // 2, 
                               HEIGHT // 2 + 40))
        
        # 重新开始提示
        restart_text = font_medium.render("按R键重新开始", True, UI_COLORS["text"])
        surface.blit(restart_text, (WIDTH // 2 - restart_text.get_width() // 2, 
                                  HEIGHT // 2 + 100))
    
    def draw_pause_menu(self, surface):
        """绘制暂停菜单"""
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 150))
        surface.blit(overlay, (0, 0))
        
        # 暂停文字
        pause_text = font_large.render("游戏暂停", True, UI_COLORS["text"])
        surface.blit(pause_text, (WIDTH // 2 - pause_text.get_width() // 2, 
                                HEIGHT // 2 - 50))
        
        # 继续提示
        continue_text = font_medium.render("按P键继续游戏", True, UI_COLORS["text"])
        surface.blit(continue_text, (WIDTH // 2 - continue_text.get_width() // 2, 
                                   HEIGHT // 2 + 20))
    
    def draw(self, surface):
        """绘制游戏"""
        # 绘制背景
        self.draw_background(surface)
        
        # 绘制爆炸效果
        for explosion in self.explosions:
            explosion.draw(surface)
        
        # 绘制强化道具
        for powerup in self.powerups:
            powerup.draw(surface)
        
        # 绘制敌人子弹
        for bullet in self.enemy_bullets:
            bullet.draw(surface)
        
        # 绘制玩家子弹
        for bullet in self.bullets:
            bullet.draw(surface)
        
        # 绘制敌人
        for enemy in self.enemies:
            enemy.draw(surface)
        
        # 绘制玩家
        self.player.draw(surface)
        
        # 绘制UI
        self.draw_ui(surface)
        
        # 绘制波次文本
        self.draw_wave_text(surface)
        
        # 绘制暂停菜单
        if self.paused:
            self.draw_pause_menu(surface)
        
        # 绘制游戏结束界面
        if self.game_over:
            self.draw_game_over(surface)

def main():
    """主函数"""
    game = Game()
    running = True
    
    while running:
        # 计算增量时间
        dt = clock.tick(60) / 1000.0
        
        # 获取输入
        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()
        keys = pygame.key.get_pressed()
        
        # 处理事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                
                elif event.key == pygame.K_r and game.game_over:
                    # 重新开始游戏
                    game = Game()
                
                elif event.key == pygame.K_p:
                    # 暂停/继续
                    game.paused = not game.paused
        
        # 更新游戏
        if not game.paused:
            game.update(dt, keys, mouse_pos, mouse_buttons)
        
        # 绘制游戏
        game.draw(screen)
        
        # 更新显示
        pygame.display.flip()
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()