python turtle画烟花_没法去看烟花?用Python制作吧!
时间: 2024-03-26 14:40:17 浏览: 17
好的,下面是 Python turtle 绘制烟花的代码:
```python
import turtle
import random
# 设置画布大小和背景颜色
turtle.setup(800, 600)
turtle.bgcolor('black')
# 定义绘制烟花的函数
def draw_firework(x, y, color):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.color(color)
# 绘制烟花爆炸的星星
for i in range(25):
turtle.fd(50)
turtle.rt(144)
# 绘制烟花下落的尾巴
turtle.color('white')
for i in range(25):
turtle.fd(50)
turtle.rt(144)
turtle.penup()
# 定义主函数
def main():
# 设置画笔速度和粗细
turtle.speed(0)
turtle.pensize(3)
# 循环绘制烟花
while True:
# 随机生成烟花的颜色和位置
x = random.randint(-350, 350)
y = random.randint(-250, 250)
color = random.choice(['red', 'blue', 'yellow', 'green', 'purple', 'white'])
# 绘制烟花
draw_firework(x, y, color)
# 调用主函数
main()
```
代码中使用了 turtle 库,通过循环绘制烟花,每次随机生成烟花的位置和颜色,然后调用 draw_firework 函数绘制烟花。运行代码,即可在 turtle 画布上看到烟花的效果。