import tkinter as tk
import random
import math

# 定义粒子类，每个烟花由多个粒子组成
class Particle:
    def __init__(self, x, y, color):
        self.x = x          # 粒子初始x坐标
        self.y = y          # 粒子初始y坐标
        self.speed = random.uniform(1, 4)  # 粒子初始速度
        self.angle = random.uniform(0, 2 * math.pi)  # 粒子运动角度
        self.gravity = 0.05 # 重力加速度
        self.vx = math.cos(self.angle) * self.speed  # x方向速度分量
        self.vy = math.sin(self.angle) * self.speed  # y方向速度分量
        self.life = 100      # 粒子生命周期
        self.color = color   # 粒子颜色

    def update(self):
        """更新粒子的位置和状态"""
        # 应用重力（y方向速度逐渐增加）
        self.vy += self.gravity
        # 更新位置
        self.x += self.vx
        self.y += self.vy
        # 速度衰减
        self.vx *= 0.98
        self.vy *= 0.98
        # 生命周期减少
        self.life -= 1

    def is_alive(self):
        """判断粒子是否还存活"""
        return self.life > 0

# 主烟花动画类
class FireworkAnimation:
    def __init__(self, root):
        self.root = root
        self.root.title("动态烟花效果")
        self.root.geometry("800x600")
        
        # 创建画布
        self.canvas = tk.Canvas(root, width=800, height=600, bg="black")
        self.canvas.pack(fill=tk.BOTH, expand=True)
        
        # 存储所有活跃的粒子
        self.particles = []
        
        # 绑定鼠标点击事件（点击位置生成烟花）
        self.canvas.bind("<Button-1>", self.create_firework)
        
        # 启动动画循环
        self.animate()

    def create_firework(self, event):
        """在鼠标点击位置创建新的烟花"""
        # 随机选择烟花颜色（红、橙、黄、绿、蓝、紫、粉）
        colors = ["#ff0000", "#ff7f00", "#ffff00", "#00ff00", 
                  "#0000ff", "#8b00ff", "#ff69b4"]
        color = random.choice(colors)
        
        # 生成100个粒子组成一个烟花
        for _ in range(100):
            particle = Particle(event.x, event.y, color)
            self.particles.append(particle)

    def animate(self):
        """动画主循环"""
        # 清除画布（保留黑色背景）
        self.canvas.delete("all")
        
        # 存储存活的粒子
        alive_particles = []
        
        # 更新并绘制每个粒子
        for particle in self.particles:
            if particle.is_alive():
                particle.update()
                # 绘制粒子（圆形，大小随生命周期减小）
                size = max(1, particle.life / 10)
                self.canvas.create_oval(
                    particle.x - size, particle.y - size,
                    particle.x + size, particle.y + size,
                    fill=particle.color, outline="")
                alive_particles.append(particle)
        
        # 更新粒子列表（只保留存活的）
        self.particles = alive_particles
        
        # 每隔20ms刷新一次（约50帧/秒）
        self.root.after(20, self.animate)

# 程序入口
if __name__ == "__main__":
    root = tk.Tk()
    app = FireworkAnimation(root)
    root.mainloop()
