使用Python绘制烟花可以通过多种方法实现,以下是使用`turtle`模块和`PIL`(Python Imaging Library)库的两种方法:
方法一:使用`turtle`模块
import turtle
import random
创建一个海龟对象
t = turtle.Turtle()
设置画布大小和背景色
screen = turtle.Screen()
screen.setup(800, 600)
screen.bgcolor("black")
烟花颜色列表
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
定义绘制烟花的函数
def draw_firework():
随机选择烟花颜色
color = random.choice(colors)
绘制烟花爆炸的圆形
t.penup()
t.goto(random.randint(-400, 400), random.randint(-250, 250))
t.pendown()
t.color(color)
t.begin_fill()
t.circle(5)
t.end_fill()
绘制烟花爆炸的线条
for _ in range(8):
t.pensize(random.randint(1, 3))
t.penup()
t.goto(0, 0)
t.pendown()
t.color(color)
t.setheading(random.randint(0, 360))
t.forward(random.randint(100, 300))
t.backward(random.randint(100, 300))
循环绘制烟花
for x in range(180):
step = 300
if x % 2 == 0:
pen.color("red")
step = 300
elif x % 3 == 0:
pen.color("green")
step = 250
elif x % 5 == 0:
pen.color("yellow")
step = 150
else:
pen.color("pink")
step = 100
pen.forward(step)
pen.dot(6)
pen.backward(step)
pen.right(2)
结束
turtle.done()
方法二:使用`PIL`库