python烟花粒子
时间: 2023-12-08 13:39:31 浏览: 41
以下是使用Python和Tkinter模拟烟花粒子的代码示例:
```python
import tkinter as tk
import random
class Particle:
def __init__(self, canvas, x, y, size, color):
self.canvas = canvas
self.id = canvas.create_oval(x, y, x+size, y+size, fill=color)
self.vx = random.randint(-10, 10)
self.vy = random.randint(-10, 10)
self.canvas_height = self.canvas.winfo_height()
self.canvas_width = self.canvas.winfo_width()
self.size = size
def move(self):
self.canvas.move(self.id, self.vx, self.vy)
x, y, x1, y1 = self.canvas.coords(self.id)
if x < 0 or x1 > self.canvas_width:
self.vx = -self.vx
if y < 0 or y1 > self.canvas_height:
self.vy = -self.vy
class Firework:
def __init__(self, canvas, x, y):
self.canvas = canvas
self.particles = []
self.x = x
self.y = y
self.create_particles()
def create_particles(self):
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
for i in range(50):
size = random.randint(2, 5)
color = random.choice(colors)
particle = Particle(self.canvas, self.x, self.y, size, color)
self.particles.append(particle)
def explode(self):
for particle in self.particles:
particle.move()
def firework(canvas, x, y):
firework = Firework(canvas, x, y)
while True:
firework.explode()
canvas.update()
if all(particle.vy >= 1 for particle in firework.particles):
break
canvas.after(50)
firework.canvas.delete("all")
root = tk.Tk()
root.title("Fireworks")
canvas = tk.Canvas(root, width=500, height=500)
canvas.pack()
firework(canvas, 250, 250)
root.mainloop()
```
这段代码使用了Python的Tkinter库来创建一个画布,并在画布上模拟了烟花粒子的运动。具体来说,代码定义了两个类:Particle和Firework。Particle类表示一个烟花粒子,包含了粒子的位置、速度、大小和颜色等属性,以及粒子的移动方法。Firework类表示一个烟花,包含了多个粒子,并定义了烟花爆炸的方法。最后,代码使用一个while循环来不断更新画布,直到所有粒子的垂直速度都大于等于1为止。