python烟花完整代码
时间: 2023-09-24 18:08:48 浏览: 249
以下是一个完整的Python烟花代码示例:
```python
import random
import tkinter as tk
maxFireworks = 10
width = 800
height = 600
Fireworks = []
class firework:
def __init__(self, color, radius, width, height):
self.center = [random.randint(0, width), random.randint(0, height)] # 烟花中心坐标
self.radius = radius # 烟花半径
self.color = color # 烟花颜色
self.curParticle = [] # 烟花粒子列表
self.status = 0 # 烟花状态
def explode(self):
self.status = 1 # 设置烟花状态为爆炸
for i in range(360): # 生成360个粒子
angle = 2 * 3.1415926 * i / 360
self.curParticle.append((self.radius * math.cos(angle), self.radius * math.sin(angle)))
def appendFirework(n=1):
if n > maxFireworks or len(Fireworks) > maxFireworks:
pass
elif n == 1:
cl = '#{0:0>6}'.format(hex(int(random.randint(0, 16777215)))[2:])
a = firework(cl, random.uniform(1.5, 3.5), width, height)
Fireworks.append({'particle': a, 'points': []})
a.explode()
else:
appendFirework()
appendFirework(n-1)
def show(c):
for p in Fireworks:
for pp in p['points']:
c.delete(pp)
for p in Fireworks:
oneP = p['particle']
if oneP.status == 100:
Fireworks.remove(p)
appendFirework()
continue
else:
li = [[int(cp * 2) + oneP.center * 2) + oneP.center - oneP.radius, pp - oneP.radius, pp + oneP.radius, pp + oneP.radius, fill=color))
root.after(50, show, c)
if __name__ == 'main':
appendFirework(maxFireworks)
root = tk.Tk()
cv = tk.Canvas(root, height=height, width=width)
cv.create_rectangle(0, 0, width, height, fill="black")
cv.pack()
root.after(50, show, cv)
root.mainloop()
```
这段代码使用了tkinter库来创建一个窗口,并在窗口中显示烟花效果。烟花的生成和爆炸过程通过递归和循环实现,并使用了随机数和颜色来增加多样性。每个烟花对象包含了烟花的中心坐标、半径、颜色、粒子列表和状态。通过定时器和画布的操作,实现了烟花的动态效果。
阅读全文