python画烟花
时间: 2023-06-29 16:13:52 浏览: 103
以下是用Python实现画烟花的代码:
```python
import turtle
import random
# 设置画布大小和背景颜色
turtle.setup(800, 600)
turtle.bgcolor("black")
# 定义画烟花的函数
def draw_firework():
# 设置画笔颜色和粗细
turtle.pencolor(random.choice(["red", "orange", "yellow", "green", "blue", "purple", "white"]))
turtle.pensize(3)
# 画出烟花的花朵部分
for i in range(30):
turtle.forward(15)
turtle.left(12)
# 画出烟花的爆炸部分
turtle.pensize(6)
for i in range(15):
turtle.backward(30)
turtle.right(24)
turtle.pencolor(random.choice(["red", "orange", "yellow", "green", "blue", "purple", "white"]))
turtle.pensize(random.randint(2, 5))
turtle.forward(30)
# 循环画烟花
while True:
# 隐藏画笔
turtle.hideturtle()
# 设置画笔起点和方向
turtle.up()
turtle.goto(random.randint(-400, 400), random.randint(-300, 300))
turtle.down()
turtle.setheading(random.randint(0, 360))
# 画出一朵烟花
draw_firework()
# 点击关闭窗口
turtle.exitonclick()
```
运行代码后,会在窗口中随机画出多朵烟花。每朵烟花的花朵部分由30条线段组成,爆炸部分由15条线段组成,颜色和粗细随机生成。
阅读全文