python烟花代码
时间: 2023-07-02 20:23:39 浏览: 83
以下是一个简单的Python烟花代码示例:
```python
import turtle
import random
# 设置画布
turtle.setup(800, 600)
turtle.bgcolor("black")
turtle.title("Fireworks")
# 定义烟花函数
def fireworks(x, y):
# 画笔属性
pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
pen.penup()
pen.color("white")
# 随机生成烟花颜色
colors = ["red", "orange", "yellow", "green", "blue", "purple", "white"]
color = random.choice(colors)
# 绘制烟花
for i in range(10):
pen.goto(x, y)
pen.pendown()
pen.dot(20, color)
pen.penup()
# 随机生成烟花爆炸范围
explode_x = x + random.randint(-100, 100)
explode_y = y + random.randint(-100, 100)
# 绘制烟花爆炸效果
for j in range(30):
pen.goto(explode_x, explode_y)
pen.pendown()
pen.dot(4, color)
pen.penup()
explode_x += random.randint(-15, 15)
explode_y += random.randint(-15, 15)
# 清除画布
pen.clear()
# 注册事件
turtle.onscreenclick(fireworks)
# 启动主循环
turtle.mainloop()
```
运行代码后,单击鼠标左键即可触发烟花效果。这个示例使用Turtle库来绘制烟花,并使用random库来随机生成烟花颜色和爆炸范围。
阅读全文