import tkinter as tk
import random
import math

# 基础设置
WIDTH = 800
HEIGHT = 600

class Particle:
    def __init__(self, canvas, x, y, color):
        self.canvas = canvas
        # 随机速度和角度
        angle = random.uniform(0, 2 * math.pi)
        speed = random.uniform(2, 7)
        self.vx = math.cos(angle) * speed
        self.vy = math.sin(angle) * speed
        # 创建粒子图像
        size = random.randint(2, 4)
        self.id = canvas.create_oval(x, y, x+size, y+size, fill=color, outline="")
        self.life = 1.0 # 生命值

    def update(self):
        self.vy += 0.15  # 重力
        self.vx *= 0.97  # 阻力
        self.vy *= 0.97
        self.canvas.move(self.id, self.vx, self.vy)
        self.life -= 0.02
        if self.life <= 0:
            self.canvas.delete(self.id)
            return False
        return True

class Firework:
    def __init__(self, canvas):
        self.canvas = canvas
        self.x = random.randint(100, WIDTH-100)
        self.y = HEIGHT
        self.target_y = random.randint(50, 250)
        self.color = random.choice(['#FF0000','#00FF00','#FFFF00','#00FFFF','#FF00FF','#FFFFFF'])
        self.shell = canvas.create_oval(self.x, self.y, self.x+3, self.y+3, fill="white")
        self.particles = []
        self.exploded = False

    def update(self):
        if not self.exploded:
            self.canvas.move(self.shell, 0, -10)
            pos = self.canvas.coords(self.shell)
            if pos[1] <= self.target_y:
                self.explode(pos[0], pos[1])
                self.canvas.delete(self.shell)
                self.exploded = True
            return True
        else:
            self.particles = [p for p in self.particles if p.update()]
            return len(self.particles) > 0

    def explode(self, x, y):
        for _ in range(50):
            self.particles.append(Particle(self.canvas, x, y, self.color))

# 全局列表存储烟花
fireworks = []

def run_animation():
    # 随机生成新烟花
    if random.random() < 0.08:
        fireworks.append(Firework(canvas))
    
    # 倒序遍历删除完成的烟花
    for f in fireworks[:]:
        if not f.update():
            fireworks.remove(f)
            
    root.after(30, run_animation)

# 创建窗口
root = tk.Tk()
root.title("动态烟花")
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="black")
canvas.pack()

# 启动
run_animation()
root.mainloop()