生成一段烟花绽放的代码
时间: 2023-07-10 07:08:23 浏览: 125
下面是一段使用Python Turtle库生成烟花绽放的代码:
```python
import turtle
import random
# 设置画布大小和背景颜色
canvas = turtle.Screen()
canvas.setup(800, 600)
canvas.bgcolor("#000000")
# 创建烟花粒子的类
class Particle(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self, visible=False)
self.speed(0)
self.penup()
self.color("white")
self.shape("circle")
self.shapesize(stretch_wid=0.1, stretch_len=0.1)
self.goto(0, 0)
self.showturtle()
# 粒子移动的方法
def move(self):
self.x += self.dx
self.y += self.dy - self.gravity
self.goto(self.x, self.y)
self.dy -= self.gravity
# 判断粒子是否在画布内的方法
def is_inside(self):
x, y = self.pos()
if abs(x) > canvas.window_width() / 2 or abs(y) > canvas.window_height() / 2:
return False
else:
return True
# 创建烟花的方法
def create_firework(x, y):
# 设置烟花的颜色和数量
colors = ["red", "orange", "yellow", "green", "blue", "purple", "white"]
num_particles = 100
# 创建烟花粒子
particles = []
for i in range(num_particles):
particle = Particle()
particle.x = x
particle.y = y
particle.gravity = 0.05
particle.setheading(random.randint(0, 360))
particle.color(random.choice(colors))
particle.speed(random.randint(1, 10))
particle.dx = particle.speed() * math.cos(particle.heading() * math.pi / 180.0)
particle.dy = particle.speed() * math.sin(particle.heading() * math.pi / 180.0)
particles.append(particle)
# 让粒子移动并绘制烟花
while any(p.is_inside() for p in particles):
for particle in particles:
particle.move()
canvas.update()
# 隐藏烟花粒子
for particle in particles:
particle.hideturtle()
# 注册鼠标点击事件
canvas.onclick(create_firework)
# 启动画布主循环
canvas.mainloop()
```
运行上面的代码,然后在画布上点击鼠标,就可以生成一朵绚丽的烟花了!
阅读全文