烟花代码编程python
时间: 2023-07-02 18:18:03 浏览: 91
烟花代码是一种基于 Python 编写的模拟烟花爆炸的程序,可以用来进行图形化的烟花效果展示。
具体的 Python 代码如下:
```python
import random
import turtle
# 定义画布
canvas = turtle.Screen()
canvas.bgcolor("black")
canvas.title("Fireworks")
# 定义烟花粒子
class Particle(turtle.Turtle):
def __init__(self, x, y, color):
turtle.Turtle.__init__(self)
self.penup()
self.speed(0)
self.color(color)
self.goto(x, y)
self.particles = []
self.life = 20
def move(self):
self.life -= 1
if self.life <= 0:
self.delete()
self.dy -= 0.2
self.goto(self.xcor() + self.dx, self.ycor() + self.dy)
if self.xcor() < -250 or self.xcor() > 250:
self.dx *= -1
if self.ycor() < -250:
self.dy *= -0.8
self.dx *= 0.9
self.sety(-250)
self.dy -= 0.2
def delete(self):
self.goto(1000, 1000)
self.particles.remove(self)
# 定义烟花
class Firework():
def __init__(self):
self.particles = []
self.color = ("red", "blue", "yellow", "white")[random.randint(0, 3)]
for i in range(50):
particle = Particle(0, -250, self.color)
particle.penup()
particle.speed(0)
particle.goto(0, -250)
particle.dy = random.randint(10, 30)
particle.dx = random.randint(-10, 10)
self.particles.append(particle)
def explode(self):
for particle in self.particles:
particle.dy += random.randint(0, 20)
particle.dx += random.randint(-10, 10)
particle.life = random.randint(10, 40)
particle.particles = self.particles
particle.move()
# 定义主函数
def main():
fireworks = []
while True:
if random.randint(0, 5) == 0:
fireworks.append(Firework())
for firework in fireworks:
firework.explode()
if not firework.particles:
fireworks.remove(firework)
turtle.update()
if __name__ == '__main__':
main()
```
运行上述代码后,即可在画布中展示出烟花效果。
阅读全文