python 3 烟花代码
时间: 2023-07-23 20:01:17 浏览: 47
以下是一个简单的 Python 3 烟花代码示例:
```python
import random
import turtle
def create_firework():
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
# 创建一个乌龟对象
firework = turtle.Turtle()
firework.shape("circle")
firework.color(random.choice(colors))
firework.penup()
# 设置随机初始位置和速度
x = random.randint(-200, 200)
y = random.randint(-200, 200)
firework.goto(x, y)
# 设置随机速度
speed_x = random.randint(-3, 3)
speed_y = random.randint(10, 15)
while True:
# 更新位置
x = firework.xcor() + speed_x
y = firework.ycor() - speed_y
firework.goto(x, y)
# 更新速度
speed_y -= 1
# 烟花消失的条件
if y < -300:
break
# 隐藏烟花对象
firework.hideturtle()
# 初始化画布
screen = turtle.Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
# 关闭动画效果
screen.tracer(0)
# 创建烟花
for _ in range(10):
create_firework()
# 更新画布
while True:
screen.update()
```
这段代码使用了 `turtle` 模块来实现烟花的效果。通过创建多个烟花对象并设置随机的位置和速度,然后在循环中不断更新烟花的位置和速度,最终达到烟花升空然后消失的效果。运行代码后,你将看到屏幕上多个烟花随机升空的效果。