新年烟花的python代码
时间: 2024-01-01 11:23:40 浏览: 179
以下是一个简单的新年烟花的Python代码示例:
```python
import turtle
import random
# 创建画布
canvas = turtle.Screen()
canvas.bgcolor("black")
# 创建烟花粒子类
class FireworkParticle(turtle.Turtle):
def __init__(self, color):
turtle.Turtle.__init__(self)
self.shape("circle")
self.color(color)
self.penup()
self.speed(0)
self.gravity = random.randint(1, 5) / 10
self.lifespan = random.randint(10, 30)
def move(self):
self.lifespan -= 1
self.goto(self.xcor(), self.ycor() - self.gravity)
# 创建烟花函数
def create_firework():
particles = []
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
# 创建烟花粒子
for _ in range(50):
particle = FireworkParticle(random.choice(colors))
particle.goto(0, 0)
particle.shapesize(stretch_wid=0.1, stretch_len=0.1)
particle.setheading(random.randint(0, 360))
particles.append(particle)
# 烟花爆炸效果
while any(p.lifespan > 0 for p in particles):
for particle in particles:
if particle.lifespan > 0:
particle.move()
# 清除烟花粒子
for particle in particles:
particle.clear()
# 创建烟花
create_firework()
# 结束程序
turtle.done()
```
阅读全文