python烟花代码
时间: 2023-07-02 22:07:37 浏览: 75
python程序烟花代码
5星 · 资源好评率100%
以下是一个简单的 Python 烟花代码实现:
```python
import random
import turtle
# 设置画布
turtle.setup(800, 600)
turtle.bgcolor('black')
turtle.title('烟花')
# 定义烟花粒子类
class FireworkParticle(turtle.Turtle):
def __init__(self, x, y, color):
turtle.Turtle.__init__(self)
self.penup()
self.speed(0)
self.color(color)
self.shape('circle')
self.shapesize(stretch_wid=0.2, stretch_len=0.2)
self.goto(x, y)
self.dx = random.uniform(-2, 2)
self.dy = random.uniform(10, 20)
self.gravity = -0.2
def move(self):
self.dy += self.gravity
self.setx(self.xcor() + self.dx)
self.sety(self.ycor() + self.dy)
# 定义烟花类
class Firework():
def __init__(self, x, y):
self.particles = []
self.color = random.choice(['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'white'])
for _ in range(50):
self.particles.append(FireworkParticle(x, y, self.color))
def explode(self):
while self.particles:
for particle in self.particles:
particle.move()
if particle.ycor() < 0:
particle.clear()
self.particles.remove(particle)
turtle.update()
# 点击画布创建烟花
def create_firework(x, y):
firework = Firework(x, y)
firework.explode()
turtle.onscreenclick(create_firework)
# 隐藏画笔
turtle.hideturtle()
# 显示画布
turtle.done()
```
运行代码后,点击画布即可创建烟花。可以尝试点击多次,观察不同颜色的烟花效果。
阅读全文