下面是一个简单的 Python 烟花代码,可以通过编写程序来模拟烟花的绽放过程:
import turtleimport random# 设置窗口大小和标题screen = turtle.Screen()screen.setup(800, 600)screen.title("Python Fireworks")# 定义烟花的颜色和数量colors = ["red", "orange", "yellow", "green", "blue", "purple", "white"]num_fireworks = 10# 定义烟花的形状firework_shape = turtle.Shape("compound")circle = turtle.Circle(10)trail = turtle.Turtle()trail.penup()trail.setposition(0, -10)trail.pendown()trail.pensize(3)trail.pencolor("white")trail.circle(10, 180)firework_shape.addcomponent(circle, "red")firework_shape.addcomponent(trail, "white")# 注册烟花的形状turtle.register_shape("firework", firework_shape)# 定义烟花类class Firework(turtle.Turtle):def __init__(self, x, y):turtle.Turtle.__init__(self)self.penup()self.setposition(x, y)self.pendown()self.color(random.choice(colors))self.shape("firework")self.shapesize(0.5)self.speed(0)self.setheading(random.randint(0, 360))self.vx = random.uniform(0.5, 2.0) * 6self.vy = random.uniform(0.5, 2.0) * 8self.gravity = 0.1def update(self):self.vy -= self.gravityself.setx(self.xcor() + self.vx)self.sety(self.ycor() + self.vy)if self.ycor() < -300:self.clear()self.hideturtle()return Trueelse:return False# 创建烟花fireworks = []for i in range(num_fireworks):x = random.randint(-400, 400)y = random.randint(-200, 200)f = Firework(x, y)fireworks.append(f)# 动画循环while True:for f in fireworks:if f.update():fireworks.remove(f)if len(fireworks) == 0:breakscreen.update()turtle.done()
该代码使用 turtle 库来绘制烟花的效果。首先,设置窗口大小和标题,定义烟花的颜色和数量。然后,定义烟花的形状,采用 turtle.Shape 的方式来定义,包括圆形和尾迹。接着,注册烟花的形状,采用 turtle.register_shape 的方式来注册。然后,定义烟花类 Firework,包括初始化位置、颜色、速度等属性,以及更新位置的方法 update。接着,创建烟花,将其添加到 fireworks 列表中。最后,进入动画循环,不断更新烟花的位置,直到所有烟花都绽放完毕。