import pygame
import sys
import random
import math
import numpy as np
from pygame.locals import *

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

# 游戏设置
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 700
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (100, 100, 100)
LIGHT_GRAY = (200, 200, 200)
GOLD = (255, 215, 0)
SILVER = (192, 192, 192)
BRONZE = (205, 127, 50)

# 颜色定义
RED = (255, 50, 50)
BLUE = (50, 150, 255)
GREEN = (50, 255, 50)
PURPLE = (180, 50, 180)
YELLOW = (255, 255, 50)
CYAN = (50, 255, 255)
MAGENTA = (255, 50, 255)
ORANGE = (255, 165, 50)
PINK = (255, 105, 180)
TURQUOISE = (64, 224, 208)

# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("烟花盛宴 - 10种烟花任你玩")
clock = pygame.time.Clock()

# 加载字体
try:
    font_small = pygame.font.Font(None, 24)
    font_medium = pygame.font.Font(None, 36)
    font_large = pygame.font.Font(None, 48)
    font_huge = pygame.font.Font(None, 72)
except:
    font_small = pygame.font.SysFont("simhei", 24)
    font_medium = pygame.font.SysFont("simhei", 36)
    font_large = pygame.font.SysFont("simhei", 48)
    font_huge = pygame.font.SysFont("simhei", 72)

# 烟花粒子类
class FireworkParticle:
    def __init__(self, x, y, color, velocity, size=3, lifetime=60, particle_type="normal"):
        self.x = x
        self.y = y
        self.start_x = x
        self.start_y = y
        self.color = color
        self.vx, self.vy = velocity
        self.size = size
        self.lifetime = lifetime
        self.max_lifetime = lifetime
        self.alpha = 255
        self.glow = random.choice([True, False])
        self.type = particle_type
        self.trail = []
        self.rotation = random.uniform(0, 360)
        self.rotation_speed = random.uniform(-5, 5)
        
    def update(self):
        # 应用重力
        if self.type not in ["heart", "star", "flower"]:
            self.vy += 0.1
            
        # 阻力
        self.vx *= 0.99
        self.vy *= 0.99
        
        # 更新位置
        self.x += self.vx
        self.y += self.vy
        
        # 记录轨迹
        self.trail.append((self.x, self.y))
        if len(self.trail) > 5:
            self.trail.pop(0)
            
        # 更新生命周期
        self.lifetime -= 1
        self.alpha = int(255 * (self.lifetime / self.max_lifetime))
        
        # 特殊效果
        if self.type in ["heart", "star", "flower"]:
            self.rotation += self.rotation_speed
            
        return self.lifetime > 0
        
    def draw(self, surface):
        if self.alpha <= 0:
            return
            
        # 绘制轨迹
        for i, (trail_x, trail_y) in enumerate(self.trail):
            trail_alpha = int(self.alpha * 0.3 * (i / len(self.trail)))
            trail_size = int(self.size * 0.5 * (i / len(self.trail)))
            
            if trail_size > 0:
                trail_color = (*self.color[:3], trail_alpha)
                pygame.draw.circle(surface, trail_color, 
                                 (int(trail_x), int(trail_y)), trail_size)
        
        # 根据粒子类型绘制
        if self.type == "normal":
            pygame.draw.circle(surface, (*self.color[:3], self.alpha), 
                             (int(self.x), int(self.y)), self.size)
            if self.glow:
                glow_radius = self.size + 2
                glow_surf = pygame.Surface((glow_radius*2, glow_radius*2), pygame.SRCALPHA)
                pygame.draw.circle(glow_surf, (*self.color[:3], self.alpha//2), 
                                 (glow_radius, glow_radius), glow_radius)
                surface.blit(glow_surf, (int(self.x) - glow_radius, int(self.y) - glow_radius))
                
        elif self.type == "heart":
            # 心形粒子
            angle = math.radians(self.rotation)
            points = []
            for i in range(20):
                t = i * 0.314
                x = 16 * (math.sin(t) ** 3)
                y = 13 * math.cos(t) - 5 * math.cos(2*t) - 2 * math.cos(3*t) - math.cos(4*t)
                
                # 旋转
                rotated_x = x * math.cos(angle) - y * math.sin(angle)
                rotated_y = x * math.sin(angle) + y * math.cos(angle)
                
                points.append((self.x + rotated_x * 0.5, self.y + rotated_y * 0.5))
                
            if len(points) > 2:
                pygame.draw.polygon(surface, (*self.color[:3], self.alpha), points)
                
        elif self.type == "star":
            # 星星粒子
            angle = math.radians(self.rotation)
            points = []
            for i in range(5):
                outer_angle = math.radians(i * 72 + 90) + angle
                inner_angle = math.radians(i * 72 + 36 + 90) + angle
                
                outer_x = self.x + math.cos(outer_angle) * self.size
                outer_y = self.y + math.sin(outer_angle) * self.size
                inner_x = self.x + math.cos(inner_angle) * (self.size * 0.4)
                inner_y = self.y + math.sin(inner_angle) * (self.size * 0.4)
                
                points.extend([(outer_x, outer_y), (inner_x, inner_y)])
                
            if len(points) > 2:
                pygame.draw.polygon(surface, (*self.color[:3], self.alpha), points)
                
        elif self.type == "flower":
            # 花朵粒子
            petal_count = 8
            angle = math.radians(self.rotation)
            points = []
            
            for i in range(petal_count * 2):
                t = i * math.pi / petal_count
                r = self.size * (1 + 0.3 * math.sin(4 * t))
                x = r * math.cos(t + angle)
                y = r * math.sin(t + angle)
                points.append((self.x + x, self.y + y))
                
            if len(points) > 2:
                pygame.draw.polygon(surface, (*self.color[:3], self.alpha), points)

# 烟花类
class Firework:
    def __init__(self, x, y, firework_type, color_scheme=None):
        self.x = x
        self.y = y
        self.type = firework_type
        self.particles = []
        self.exploded = False
        self.timer = random.randint(20, 40)  # 爆炸前的飞行时间
        self.vx = random.uniform(-1, 1)
        self.vy = random.uniform(-8, -12)
        self.size = 3
        self.creation_time = pygame.time.get_ticks()
        
        # 设置颜色方案
        if color_scheme:
            self.colors = color_scheme
        else:
            self.colors = self.get_default_colors(firework_type)
            
    def get_default_colors(self, fw_type):
        """获取每种烟花的默认颜色方案"""
        color_schemes = {
            "normal": [RED, ORANGE, YELLOW],
            "circle": [BLUE, CYAN, TURQUOISE],
            "heart": [PINK, MAGENTA, PURPLE],
            "star": [YELLOW, GOLD, ORANGE],
            "spiral": [GREEN, TURQUOISE, BLUE],
            "flower": [MAGENTA, PINK, WHITE],
            "fountain": [RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE],
            "comet": [CYAN, BLUE, WHITE],
            "willow": [GOLD, YELLOW, ORANGE],
            "peony": [RED, PINK, MAGENTA, PURPLE]
        }
        return color_schemes.get(fw_type, [RED, ORANGE, YELLOW])
        
    def update(self):
        if not self.exploded:
            # 上升阶段
            self.x += self.vx
            self.y += self.vy
            self.vy += 0.2
            
            # 绘制上升轨迹
            if random.random() < 0.3:
                self.particles.append(FireworkParticle(
                    self.x, self.y + 5,
                    (255, 200, 100, 200),
                    (random.uniform(-0.5, 0.5), random.uniform(-0.5, 0.5)),
                    2, 20
                ))
            
            # 检查是否爆炸
            self.timer -= 1
            if self.timer <= 0 or self.vy >= 0:
                self.explode()
        else:
            # 爆炸后更新粒子
            for particle in self.particles[:]:
                if not particle.update():
                    self.particles.remove(particle)
                    
    def explode(self):
        self.exploded = True
        
        if self.type == "normal":
            # 标准爆炸
            for _ in range(100):
                angle = random.uniform(0, math.pi * 2)
                speed = random.uniform(2, 8)
                color = random.choice(self.colors)
                self.particles.append(FireworkParticle(
                    self.x, self.y,
                    (*color, 255),
                    (math.cos(angle) * speed, math.sin(angle) * speed),
                    random.uniform(2, 4)
                ))
                
        elif self.type == "circle":
            # 圆形爆炸
            for i in range(360 // 5):
                angle = math.radians(i * 5)
                speed = random.uniform(3, 6)
                color = self.colors[i % len(self.colors)]
                self.particles.append(FireworkParticle(
                    self.x, self.y,
                    (*color, 255),
                    (math.cos(angle) * speed, math.sin(angle) * speed),
                    3
                ))
                
        elif self.type == "heart":
            # 心形爆炸
            for _ in range(150):
                # 生成心形参数
                t = random.uniform(0, math.pi * 2)
                x = 16 * (math.sin(t) ** 3)
                y = 13 * math.cos(t) - 5 * math.cos(2*t) - 2 * math.cos(3*t) - math.cos(4*t)
                
                # 添加随机旋转
                angle = random.uniform(0, math.pi * 2)
                speed = random.uniform(2, 5)
                
                vx = (x * math.cos(angle) - y * math.sin(angle)) * 0.1
                vy = (x * math.sin(angle) + y * math.cos(angle)) * 0.1
                
                color = random.choice(self.colors)
                self.particles.append(FireworkParticle(
                    self.x, self.y,
                    (*color, 255),
                    (vx + random.uniform(-1, 1), vy + random.uniform(-1, 1)),
                    3, 80, "heart"
                ))
                
        elif self.type == "star":
            # 星星爆炸
            for _ in range(120):
                # 生成星星形状
                i = random.randint(0, 4)
                outer_angle = math.radians(i * 72)
                inner_angle = math.radians(i * 72 + 36)
                
                angle = random.choice([outer_angle, inner_angle])
                speed = random.uniform(2, 6)
                
                color = random.choice(self.colors)
                self.particles.append(FireworkParticle(
                    self.x, self.y,
                    (*color, 255),
                    (math.cos(angle) * speed, math.sin(angle) * speed),
                    3, 60, "star"
                ))
                
        elif self.type == "spiral":
            # 螺旋爆炸
            for i in range(200):
                t = i * 0.1
                angle = t * 2
                radius = t * 0.5
                speed = 3
                
                x = math.cos(t) * radius
                y = math.sin(t) * radius
                
                vx = math.cos(angle) * speed
                vy = math.sin(angle) * speed
                
                color = self.colors[i % len(self.colors)]
                self.particles.append(FireworkParticle(
                    self.x, self.y,
                    (*color, 255),
                    (vx, vy),
                    2, 40
                ))
                
        elif self.type == "flower":
            # 花朵爆炸
            petal_count = 8
            for _ in range(200):
                t = random.uniform(0, math.pi * 2)
                petal_factor = 4
                r = 1 + 0.3 * math.sin(petal_factor * t)
                angle = t
                speed = random.uniform(2, 5)
                
                vx = math.cos(angle) * r * speed
                vy = math.sin(angle) * r * speed
                
                color = random.choice(self.colors)
                self.particles.append(FireworkParticle(
                    self.x, self.y,
                    (*color, 255),
                    (vx, vy),
                    3, 70, "flower"
                ))
                
        elif self.type == "fountain":
            # 喷泉效果
            for _ in range(200):
                angle = random.uniform(math.pi * 0.3, math.pi * 0.7)
                speed = random.uniform(4, 10)
                
                color = random.choice(self.colors)
                self.particles.append(FireworkParticle(
                    self.x, self.y,
                    (*color, 255),
                    (math.cos(angle) * speed, math.sin(angle) * speed),
                    random.uniform(2, 4)
                ))
                
        elif self.type == "comet":
            # 彗星效果
            trail_length = 30
            for i in range(trail_length):
                angle = random.uniform(-0.3, 0.3)
                speed = random.uniform(5, 8) * (1 - i/trail_length)
                
                color = self.colors[0] if i < trail_length//2 else self.colors[1]
                alpha = 255 * (1 - i/trail_length)
                
                self.particles.append(FireworkParticle(
                    self.x - i * 2, self.y - i * 2,
                    (*color, int(alpha)),
                    (math.cos(angle) * speed, math.sin(angle) * speed),
                    3, 40
                ))
                
        elif self.type == "willow":
            # 柳树效果
            for _ in range(150):
                angle = random.uniform(math.pi * 0.7, math.pi * 1.3)
                speed_x = random.uniform(-3, 3)
                speed_y = random.uniform(1, 4)
                
                color = random.choice(self.colors)
                particle = FireworkParticle(
                    self.x, self.y,
                    (*color, 255),
                    (speed_x, speed_y),
                    3, 100
                )
                particle.vy = speed_y
                self.particles.append(particle)
                
        elif self.type == "peony":
            # 牡丹效果 - 多层爆炸
            layers = 3
            for layer in range(layers):
                layer_radius = (layer + 1) * 20
                particles_count = 80
                
                for i in range(particles_count):
                    angle = math.radians(i * 360 / particles_count)
                    offset_angle = random.uniform(-0.1, 0.1)
                    speed = random.uniform(2, 5) * (1 - layer * 0.3)
                    
                    start_x = self.x + math.cos(angle) * layer_radius
                    start_y = self.y + math.sin(angle) * layer_radius
                    
                    color = self.colors[layer % len(self.colors)]
                    self.particles.append(FireworkParticle(
                        start_x, start_y,
                        (*color, 255),
                        (math.cos(angle + offset_angle) * speed, 
                         math.sin(angle + offset_angle) * speed),
                        random.uniform(2, 4)
                    ))
                    
    def draw(self, surface):
        if not self.exploded:
            # 绘制上升的烟花
            pygame.draw.circle(surface, (255, 255, 200), (int(self.x), int(self.y)), self.size)
            pygame.draw.circle(surface, (255, 200, 100), (int(self.x), int(self.y)), self.size - 1)
        else:
            # 绘制爆炸粒子
            for particle in self.particles:
                particle.draw(surface)
                
    def is_finished(self):
        return self.exploded and len(self.particles) == 0

# 烟花商店类
class FireworkShop:
    def __init__(self):
        self.fireworks = [
            {"name": "普通烟花", "type": "normal", "cost": 100, "description": "基础爆炸效果", "color": RED},
            {"name": "圆形烟花", "type": "circle", "cost": 150, "description": "完美圆形爆炸", "color": BLUE},
            {"name": "心形烟花", "type": "heart", "cost": 200, "description": "浪漫心形图案", "color": PINK},
            {"name": "星星烟花", "type": "star", "cost": 180, "description": "闪烁的星星", "color": YELLOW},
            {"name": "螺旋烟花", "type": "spiral", "cost": 220, "description": "旋转螺旋效果", "color": GREEN},
            {"name": "花朵烟花", "type": "flower", "cost": 250, "description": "美丽的花朵图案", "color": MAGENTA},
            {"name": "喷泉烟花", "type": "fountain", "cost": 120, "description": "持续喷泉效果", "color": ORANGE},
            {"name": "彗星烟花", "type": "comet", "cost": 170, "description": "拖着长尾的彗星", "color": CYAN},
            {"name": "柳树烟花", "type": "willow", "cost": 190, "description": "柳枝般下垂效果", "color": GOLD},
            {"name": "牡丹烟花", "type": "peony", "cost": 300, "description": "多层华丽爆炸", "color": PURPLE}
        ]
        
        self.selected_index = 0
        self.preview_fireworks = []
        self.preview_timer = 0
        
    def draw(self, surface, money, x, y, width, height):
        # 绘制商店背景
        pygame.draw.rect(surface, (30, 30, 40, 220), (x, y, width, height))
        pygame.draw.rect(surface, (100, 100, 150), (x, y, width, height), 3)
        
        # 商店标题
        title = font_medium.render("烟花商店", True, GOLD)
        surface.blit(title, (x + width//2 - title.get_width()//2, y + 20))
        
        # 金钱显示
        money_text = font_medium.render(f"金钱: ${money}", True, GOLD)
        surface.blit(money_text, (x + width//2 - money_text.get_width()//2, y + 60))
        
        # 绘制烟花列表
        items_per_column = 5
        item_height = 50
        item_width = 200
        
        for i, firework in enumerate(self.fireworks):
            item_x = x + 20 + (i // items_per_column) * 220
            item_y = y + 120 + (i % items_per_column) * 60
            
            # 判断是否选中
            is_selected = (i == self.selected_index)
            is_affordable = (money >= firework["cost"])
            
            # 背景颜色
            bg_color = (60, 60, 80) if not is_selected else (80, 80, 100)
            if not is_affordable:
                bg_color = (50, 30, 30)  # 买不起的颜色
                
            pygame.draw.rect(surface, bg_color, (item_x, item_y, item_width, item_height))
            pygame.draw.rect(surface, firework["color"], (item_x, item_y, item_width, item_height), 2)
            
            # 烟花名称
            name_color = WHITE if is_affordable else (150, 150, 150)
            name_text = font_small.render(firework["name"], True, name_color)
            surface.blit(name_text, (item_x + 10, item_y + 5))
            
            # 价格
            cost_color = GOLD if is_affordable else RED
            cost_text = font_small.render(f"${firework['cost']}", True, cost_color)
            surface.blit(cost_text, (item_x + item_width - 60, item_y + 5))
            
            # 描述
            desc_text = font_small.render(firework["description"], True, LIGHT_GRAY)
            surface.blit(desc_text, (item_x + 10, item_y + 30))
            
        # 绘制预览区域
        preview_x = x + width - 300
        preview_y = y + 120
        preview_width = 260
        preview_height = 300
        
        pygame.draw.rect(surface, (20, 20, 30, 200), (preview_x, preview_y, preview_width, preview_height))
        pygame.draw.rect(surface, (100, 100, 150), (preview_x, preview_y, preview_width, preview_height), 2)
        
        # 预览标题
        preview_title = font_small.render("预览", True, WHITE)
        surface.blit(preview_title, (preview_x + preview_width//2 - preview_title.get_width()//2, preview_y + 10))
        
        # 在预览区域绘制烟花
        self.preview_timer += 1
        if self.preview_timer % 60 == 0:  # 每秒更新预览
            self.update_preview(preview_x, preview_y, preview_width, preview_height)
            
        for firework in self.preview_fireworks[:]:
            firework.update()
            firework.draw(surface)
            if firework.is_finished():
                self.preview_fireworks.remove(firework)
                
        # 操作提示
        tips = [
            "↑↓: 选择烟花",
            "空格/回车: 购买并发射",
            "1-0: 快速选择",
            "ESC: 返回游戏"
        ]
        
        for i, tip in enumerate(tips):
            tip_text = font_small.render(tip, True, LIGHT_GRAY)
            surface.blit(tip_text, (x + 20, y + height - 120 + i * 30))
            
    def update_preview(self, x, y, width, height):
        # 创建预览烟花
        if len(self.preview_fireworks) < 3:  # 最多3个预览烟花
            firework_type = self.fireworks[self.selected_index]["type"]
            preview_x = x + width//2
            preview_y = y + height//2
            
            self.preview_fireworks.append(Firework(preview_x, preview_y, firework_type))
            
    def handle_input(self, keys, money):
        # 上下选择
        if keys[K_UP]:
            self.selected_index = max(0, self.selected_index - 1)
        if keys[K_DOWN]:
            self.selected_index = min(len(self.fireworks) - 1, self.selected_index + 1)
            
        # 数字键快速选择
        for i in range(10):
            if keys[K_1 + i] and i < len(self.fireworks):
                self.selected_index = i
                
        # 购买烟花
        if keys[K_RETURN] or keys[K_SPACE]:
            selected = self.fireworks[self.selected_index]
            if money >= selected["cost"]:
                return selected["type"], selected["cost"]
                
        return None, 0

# 烟花游戏主类
class FireworkGame:
    def __init__(self):
        self.money = 1000
        self.score = 0
        self.fireworks = []
        self.background_particles = []
        self.shop = FireworkShop()
        self.in_shop = False
        self.mouse_pos = (0, 0)
        self.game_state = "playing"  # "playing", "shop", "game_over"
        self.selected_firework_type = "normal"
        self.last_firework_time = 0
        self.firework_cooldown = 500  # 毫秒
        self.auto_spawn_timer = 0
        self.sparkle_particles = []
        
        # 初始化背景
        self.create_background()
        
    def create_background(self):
        # 创建城市天际线
        self.buildings = []
        for i in range(20):
            x = i * 60
            height = random.randint(100, 300)
            width = random.randint(40, 80)
            color = random.choice([(30, 30, 40), (40, 30, 30), (30, 40, 30)])
            self.buildings.append({
                "rect": pygame.Rect(x, SCREEN_HEIGHT - height, width, height),
                "color": color,
                "windows": []
            })
            
            # 为建筑物添加窗户
            building = self.buildings[-1]
            for wy in range(building["rect"].top + 20, building["rect"].bottom - 20, 30):
                for wx in range(building["rect"].left + 10, building["rect"].right - 10, 20):
                    if random.random() < 0.3:  # 30%的窗户亮着
                        building["windows"].append({
                            "pos": (wx, wy),
                            "on": random.choice([True, False])
                        })
                        
        # 创建背景星星
        self.stars = []
        for _ in range(100):
            self.stars.append({
                "pos": (random.randint(0, SCREEN_WIDTH), random.randint(0, 300)),
                "size": random.uniform(0.5, 2),
                "brightness": random.uniform(0.3, 1.0)
            })
            
    def handle_events(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                return False
                
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    if self.in_shop:
                        self.in_shop = False
                    else:
                        self.in_shop = True
                        
                elif event.key == K_s:
                    self.in_shop = not self.in_shop
                    
                elif event.key == K_r:
                    # 重置游戏
                    self.__init__()
                    
                elif event.key == K_SPACE and not self.in_shop:
                    current_time = pygame.time.get_ticks()
                    if current_time - self.last_firework_time > self.firework_cooldown:
                        self.launch_firework(self.selected_firework_type)
                        self.last_firework_time = current_time
                        
                elif K_1 <= event.key <= K_0 and not self.in_shop:
                    index = event.key - K_1
                    if index < len(self.shop.fireworks):
                        self.selected_firework_type = self.shop.fireworks[index]["type"]
                        
            elif event.type == MOUSEBUTTONDOWN and not self.in_shop:
                if event.button == 1:  # 左键
                    current_time = pygame.time.get_ticks()
                    if current_time - self.last_firework_time > self.firework_cooldown:
                        self.launch_firework(self.selected_firework_type, event.pos[0])
                        self.last_firework_time = current_time
                        
            elif event.type == MOUSEMOTION:
                self.mouse_pos = event.pos
                
        return True
        
    def launch_firework(self, firework_type=None, x=None):
        if firework_type is None:
            firework_type = self.selected_firework_type
            
        if x is None:
            x = random.randint(100, SCREEN_WIDTH - 100)
            
        # 检查是否有足够的钱
        cost = 0
        for fw in self.shop.fireworks:
            if fw["type"] == firework_type:
                cost = fw["cost"]
                break
                
        if self.money >= cost:
            self.money -= cost
            self.fireworks.append(Firework(x, SCREEN_HEIGHT, firework_type))
            
            # 添加发射音效视觉效果
            for _ in range(20):
                angle = random.uniform(math.pi, math.pi * 1.2)
                speed = random.uniform(1, 3)
                self.sparkle_particles.append(FireworkParticle(
                    x, SCREEN_HEIGHT,
                    (255, 200, 100, 200),
                    (math.cos(angle) * speed, math.sin(angle) * speed),
                    2, 30
                ))
                
            return True
        return False
        
    def update(self):
        current_time = pygame.time.get_ticks()
        
        # 自动生成免费小烟花
        self.auto_spawn_timer += 1
        if self.auto_spawn_timer > 120 and not self.in_shop:  # 每2秒
            if random.random() < 0.3:  # 30%几率
                x = random.randint(100, SCREEN_WIDTH - 100)
                self.fireworks.append(Firework(x, SCREEN_HEIGHT, "normal"))
                self.auto_spawn_timer = 0
                
        # 更新烟花
        for firework in self.fireworks[:]:
            firework.update()
            if firework.is_finished():
                self.fireworks.remove(firework)
                # 烟花结束后增加金钱
                self.money += 10
                self.score += 1
                
        # 更新商店预览烟花
        if self.in_shop:
            selected_fw = self.shop.fireworks[self.shop.selected_index]
            if self.money >= selected_fw["cost"] and current_time - self.last_firework_time > 1000:
                # 在商店中自动演示烟花
                if random.random() < 0.02:  # 2%几率
                    self.shop.preview_fireworks.append(
                        Firework(
                            random.randint(100, SCREEN_WIDTH - 100),
                            SCREEN_HEIGHT,
                            selected_fw["type"]
                        )
                    )
                    self.last_firework_time = current_time
                    
        # 更新背景粒子
        for particle in self.background_particles[:]:
            if not particle.update():
                self.background_particles.remove(particle)
                
        # 添加新的背景粒子
        if random.random() < 0.1:
            self.background_particles.append(FireworkParticle(
                random.randint(0, SCREEN_WIDTH),
                SCREEN_HEIGHT + 10,
                (random.randint(50, 100), random.randint(50, 100), random.randint(100, 150), 100),
                (random.uniform(-0.5, 0.5), random.uniform(-3, -1)),
                2, 60
            ))
            
        # 更新商店
        if self.in_shop:
            keys = pygame.key.get_pressed()
            firework_type, cost = self.shop.handle_input(keys, self.money)
            if firework_type:
                self.selected_firework_type = firework_type
                self.money -= cost
                
        # 更新闪烁粒子
        for particle in self.sparkle_particles[:]:
            if not particle.update():
                self.sparkle_particles.remove(particle)
                
    def draw_background(self, surface):
        # 深色天空背景
        for y in range(SCREEN_HEIGHT):
            # 渐变天空
            sky_color = (
                max(0, 10 + y // 20),
                max(0, 5 + y // 30),
                max(0, 20 + y // 15)
            )
            pygame.draw.line(surface, sky_color, (0, y), (SCREEN_WIDTH, y))
            
        # 绘制星星
        for star in self.stars:
            brightness = star["brightness"] * (0.8 + 0.2 * math.sin(pygame.time.get_ticks() * 0.001))
            star_color = (int(255 * brightness), int(255 * brightness), int(200 * brightness))
            pygame.draw.circle(surface, star_color, 
                             (int(star["pos"][0]), int(star["pos"][1])), 
                             star["size"])
            
        # 绘制建筑物
        for building in self.buildings:
            pygame.draw.rect(surface, building["color"], building["rect"])
            
            # 绘制窗户
            for window in building["windows"]:
                if window["on"]:
                    window_color = (random.randint(200, 255), random.randint(200, 255), 100)
                else:
                    window_color = (50, 50, 30)
                    
                pygame.draw.rect(surface, window_color, 
                               (window["pos"][0], window["pos"][1], 8, 12))
                
        # 绘制地面
        pygame.draw.rect(surface, (20, 20, 10), (0, SCREEN_HEIGHT - 20, SCREEN_WIDTH, 20))
        
        # 绘制背景粒子
        for particle in self.background_particles:
            particle.draw(surface)
            
    def draw(self, surface):
        # 绘制背景
        self.draw_background(surface)
        
        # 绘制烟花
        for firework in self.fireworks:
            firework.draw(surface)
            
        # 绘制闪烁粒子
        for particle in self.sparkle_particles:
            particle.draw(surface)
            
        # 绘制UI
        self.draw_ui(surface)
        
        # 绘制商店
        if self.in_shop:
            self.shop.draw(surface, self.money, 50, 50, SCREEN_WIDTH - 100, SCREEN_HEIGHT - 100)
            
    def draw_ui(self, surface):
        # 半透明UI背景
        ui_bg = pygame.Surface((SCREEN_WIDTH, 100), pygame.SRCALPHA)
        ui_bg.fill((0, 0, 0, 150))
        surface.blit(ui_bg, (0, 0))
        
        # 金钱显示
        money_text = font_large.render(f"金钱: ${self.money}", True, GOLD)
        surface.blit(money_text, (20, 20))
        
        # 分数显示
        score_text = font_medium.render(f"分数: {self.score}", True, WHITE)
        surface.blit(score_text, (20, 60))
        
        # 当前选择的烟花
        selected_name = ""
        for fw in self.shop.fireworks:
            if fw["type"] == self.selected_firework_type:
                selected_name = fw["name"]
                break
                
        selected_text = font_medium.render(f"当前: {selected_name}", True, LIGHT_GRAY)
        surface.blit(selected_text, (SCREEN_WIDTH - 300, 20))
        
        # 操作提示
        tips = [
            "鼠标点击: 发射烟花",
            "空格: 快速发射",
            "1-0: 切换烟花类型",
            "S: 打开商店",
            "ESC: 暂停/返回"
        ]
        
        for i, tip in enumerate(tips):
            tip_text = font_small.render(tip, True, LIGHT_GRAY)
            surface.blit(tip_text, (SCREEN_WIDTH - 300, 50 + i * 20))
            
        # 绘制烟花选择快捷栏
        self.draw_quickbar(surface)
        
    def draw_quickbar(self, surface):
        bar_y = SCREEN_HEIGHT - 50
        bar_width = SCREEN_WIDTH
        bar_height = 50
        
        # 快捷栏背景
        pygame.draw.rect(surface, (0, 0, 0, 150), (0, bar_y, bar_width, bar_height))
        pygame.draw.line(surface, (100, 100, 100), (0, bar_y), (bar_width, bar_y))
        
        # 烟花快捷项
        item_width = 80
        for i, firework in enumerate(self.shop.fireworks):
            item_x = 20 + i * (item_width + 10)
            
            # 判断是否选中
            is_selected = (firework["type"] == self.selected_firework_type)
            is_affordable = (self.money >= firework["cost"])
            
            # 背景
            bg_color = (40, 40, 50) if not is_selected else (60, 60, 80)
            if not is_affordable:
                bg_color = (50, 30, 30)
                
            pygame.draw.rect(surface, bg_color, (item_x, bar_y + 5, item_width, 40))
            pygame.draw.rect(surface, firework["color"], (item_x, bar_y + 5, item_width, 40), 2)
            
            # 烟花名称缩写
            name_text = font_small.render(firework["name"][:2], True, WHITE)
            surface.blit(name_text, (item_x + 5, bar_y + 10))
            
            # 快捷键数字
            key_text = font_small.render(str(i+1), True, LIGHT_GRAY)
            surface.blit(key_text, (item_x + item_width - 20, bar_y + 10))
            
            # 价格
            price_text = font_small.render(f"${firework['cost']}", True, GOLD if is_affordable else RED)
            surface.blit(price_text, (item_x + 5, bar_y + 30))

# 主游戏循环
def main():
    game = FireworkGame()
    
    # 创建标题界面
    show_title = True
    title_alpha = 0
    title_direction = 1
    
    while True:
        # 处理事件
        if not game.handle_events():
            break
            
        # 更新游戏
        if not show_title:
            game.update()
            
        # 绘制
        screen.fill(BLACK)
        
        if show_title:
            # 绘制标题界面
            title_alpha += title_direction * 3
            if title_alpha >= 255:
                title_alpha = 255
                title_direction = -1
            elif title_alpha <= 0:
                title_alpha = 0
                title_direction = 1
                
            # 标题背景
            screen.fill((10, 5, 20))
            
            # 标题烟花效果
            title_time = pygame.time.get_ticks() * 0.001
            for i in range(5):
                x = SCREEN_WIDTH // 2 + math.sin(title_time + i * 1.2) * 200
                y = 200 + math.cos(title_time + i * 0.8) * 50
                
                # 绘制标题背景烟花
                for j in range(20):
                    angle = (i + j) * 0.3
                    radius = 100 + math.sin(title_time + j * 0.2) * 30
                    color_index = (i + j) % 3
                    colors = [(255, 50, 50), (50, 150, 255), (50, 255, 50)]
                    
                    point_x = x + math.cos(angle) * radius
                    point_y = y + math.sin(angle) * radius
                    
                    pygame.draw.circle(screen, colors[color_index], 
                                     (int(point_x), int(point_y)), 2)
                    
            # 游戏标题
            title = font_huge.render("烟花盛宴", True, (255, 255, 200))
            title_shadow = font_huge.render("烟花盛宴", True, (150, 100, 50))
            screen.blit(title_shadow, (SCREEN_WIDTH//2 - title.get_width()//2 + 3, 203))
            screen.blit(title, (SCREEN_WIDTH//2 - title.get_width()//2, 200))
            
            # 副标题
            subtitle = font_large.render("10种绚丽烟花任你燃放", True, (200, 200, 255))
            screen.blit(subtitle, (SCREEN_WIDTH//2 - subtitle.get_width()//2, 300))
            
            # 开始按钮
            button_color = (255, 215, 0) if title_alpha > 150 else (150, 150, 150)
            button_rect = pygame.Rect(SCREEN_WIDTH//2 - 100, 400, 200, 60)
            pygame.draw.rect(screen, button_color, button_rect, border_radius=10)
            pygame.draw.rect(screen, (255, 255, 255), button_rect, 3, border_radius=10)
            
            start_text = font_large.render("开始游戏", True, BLACK)
            screen.blit(start_text, (SCREEN_WIDTH//2 - start_text.get_width()//2, 415))
            
            # 闪烁提示
            if title_alpha > 150:
                prompt = font_medium.render("点击开始按钮或按任意键开始", True, (200, 255, 200, title_alpha))
                screen.blit(prompt, (SCREEN_WIDTH//2 - prompt.get_width()//2, 500))
                
            # 操作说明
            instructions = [
                "游戏说明:",
                "• 鼠标点击发射烟花",
                "• 数字键1-0选择不同烟花",
                "• 烟花需要花费金钱",
                "• 观看烟花获得金钱奖励",
                "• 按S键打开商店购买更多烟花"
            ]
            
            for i, instruction in enumerate(instructions):
                inst_text = font_small.render(instruction, True, (200, 200, 200))
                screen.blit(inst_text, (50, 550 + i * 25))
                
            # 检查开始游戏
            mouse_buttons = pygame.mouse.get_pressed()
            if mouse_buttons[0]:
                mouse_pos = pygame.mouse.get_pos()
                if button_rect.collidepoint(mouse_pos):
                    show_title = False
                    
            keys = pygame.key.get_pressed()
            if any(keys):
                show_title = False
                
        else:
            # 绘制游戏
            game.draw(screen)
            
        # 更新显示
        pygame.display.flip()
        clock.tick(FPS)
        
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()