使用Python制作烟花可以通过多种方式实现,以下是使用`turtle`模块和`pygame`库的两种方法:
方法一:使用`turtle`模块
import turtleimport 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))循环调用绘制烟花while True:draw_firework()screen.update()
方法二:使用`pygame`库

import pygameimport random初始化pygamepygame.init()设置窗口大小width, height = 800, 600screen = pygame.display.set_mode((width, height))pygame.display.set_caption("Fireworks")设置颜色BLACK = (0, 0, 0)WHITE = (255, 255, 255)COLORS = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]定义烟花类class Firework:def __init__(self, x, y):self.x = xself.y = yself.color = random.choice(COLORS)self.radius = 2self.speed = random.randint(1, 5)def explode(self):self.radius += self.speed绘制烟花def draw_fireworks():for _ in range(10): 绘制10个烟花效果firework = Firework(random.randint(0, width), random.randint(0, height))while firework.radius > 0:screen.fill(BLACK)firework.draw()pygame.display.flip()pygame.time.delay(100)firework.explode()主循环draw_fireworks()pygame.quit()
以上代码展示了如何使用`turtle`和`pygame`库来制作烟花效果。你可以根据自己的需求调整参数和效果。
