用python写一个烟花特效
时间: 2023-05-19 08:04:06 浏览: 116
好的,以下是一个简单的Python烟花特效代码:
```python
import random
import turtle
# 设置画布大小和背景颜色
turtle.setup(800, 600)
turtle.bgcolor("black")
# 定义烟花粒子类
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.shape("circle")
self.shapesize(stretch_wid=0.1, stretch_len=0.1)
self.dx = random.uniform(-2, 2)
self.dy = random.uniform(5, 15)
self.gravity = -0.1
def move(self):
self.dy += self.gravity
self.setx(self.xcor() + self.dx)
self.sety(self.ycor() + self.dy)
if self.ycor() < -300:
self.clear()
self.hideturtle()
# 定义烟花类
class Firework():
def __init__(self):
self.particles = []
self.color = random.choice(["red", "orange", "yellow", "green", "blue", "purple"])
self.create_particles()
def create_particles(self):
for i in range(50):
particle = Particle(0, 0, self.color)
self.particles.append(particle)
def explode(self):
for particle in self.particles:
particle.move()
# 判断是否所有粒子都已经落地
landed_particles = [particle for particle in self.particles if particle.ycor() < -300]
if len(landed_particles) == len(self.particles):
self.clear()
def clear(self):
for particle in self.particles:
particle.clear()
particle.hideturtle()
self.particles.clear()
# 创建烟花并让其爆炸
fireworks = []
while True:
if random.random() < 0.05:
fireworks.append(Firework())
for firework in fireworks:
firework.explode()
fireworks = [firework for firework in fireworks if len(firework.particles) > 0]
turtle.update()
```
这个代码使用了turtle库来绘制烟花,每个烟花由多个粒子组成,每个粒子都有一个随机的速度和重力加速度,当粒子落地后就会被清除。程序会不断地创建新的烟花,直到程序结束。
阅读全文