手把手教你用 Python 制作一场炫酷烟花秀

简介: 本篇文章,带大家用 Python 制作一个炫酷烟花秀,来迎接即将到来的元旦佳节。开始之前先看一下最终效果

明天是元旦,小张在这里先提前祝大家元旦快乐~,本篇文章,带大家用 Python 制作一个炫酷烟花秀,来迎接即将到来的元旦佳节。开始之前先看一下最终效果



环境介绍:

语言:Python;

库:Pygame;


原理介绍


在介绍代码之前,先介绍下  Pygame 绘制烟花的基本原理,烟花从发射到绽放一共分为三个阶段:


1,发射阶段:在这一阶段烟花的形状是线性向上,通过设定一组大小不同、颜色不同的点来模拟“向上发射” 的运动运动,运动过程中 5个点被赋予不同大小的加速度,随着时间推移,后面的点会赶上前面的点,最终所有点会汇聚在一起,处于 绽放准备阶段


微信图片_20220520102958.gif

2,烟花绽放:烟花绽放这个阶段,是由一个点分散多个点向不同方向发散,并且每个点的移动轨迹可需要被记录,目的是为了追踪整个绽放轨迹。


微信图片_20220520103027.gif

3,烟花凋零,此阶段负责描绘绽放后烟花的效果,绽放后的烟花,而在每一时刻点的下降速度和亮度(代码中也叫透明度)是不一样的,因此在代码里,将烟花绽放后将每个点赋予两个属性:分别为重力向量和生命周期,来模拟烟花在不同时期时不同的展现效果,

微信图片_20220520103019.gif


代码实操


代码部分将烟花封装为三个类:

Firework : 烟花整体;

Particle:烟花粒子(包含轨迹)

Trail:烟花轨迹,本质上是一个点 。

三个类之间的关系为:一个Firework 由多个 Particle 构成,而一个 Particle 由多个 Trail 构成


首先设置全局变量,例如重力向量,窗口大小,Trail 的颜色列表(多为灰色或白色)以及不同状态下 Trail 之间间隔


gravity = vector(0, 0.3)
DISPLAY_WIDTH = DISPLAY_HEIGHT = 800
trail_colours = [(45, 45, 45), (60, 60, 60), (75, 75, 75), (125, 125, 125), (150, 150, 150)]
dynamic_offset = 1
static_offset = 3


创建 Trail 类,定义 show 方法绘制轨迹 、get_pos  实时获取轨迹坐标

class Trail:
    def __init__(self, n, size, dynamic):
        self.pos_in_line = n
        self.pos = vector(-10, -10)
        self.dynamic = dynamic
        if self.dynamic:
            self.colour = trail_colours[n]
            self.size = int(size - n / 2)
        else:
            self.colour = (255, 255, 200)
            self.size = size - 2
            if self.size < 0:
                self.size = 0
    def get_pos(self, x, y):
        self.pos = vector(x, y)
    def show(self, win):
        pygame.draw.circle(win, self.colour, (int(self.pos.x), int(self.pos.y)), self.size)


Particle 类核心代码

class Particle:
    def __init__(self, x, y, firework, colour):
        self.firework = firework
        self.pos = vector(x, y)
        self.origin = vector(x, y)
        self.radius = 20
        self.remove = False
        self.explosion_radius = randint(5, 18)
        self.life = 0
        self.acc = vector(0, 0)
        # trail variables
        self.trails = []  # stores the particles trail objects
        self.prev_posx = [-10] * 10  # stores the 10 last positions
        self.prev_posy = [-10] * 10  # stores the 10 last positions
        if self.firework:
            self.vel = vector(0, -randint(17, 20))
            self.size = 5
            self.colour = colour
            for i in range(5):
                self.trails.append(Trail(i, self.size, True))
        else:
            self.vel = vector(uniform(-1, 1), uniform(-1, 1))
            self.vel.x *= randint(7, self.explosion_radius + 2)
            self.vel.y *= randint(7, self.explosion_radius + 2)
            # 向量
            self.size = randint(2, 4)
            self.colour = choice(colour)
            # 5 个 tails总计
            for i in range(5):
                self.trails.append(Trail(i, self.size, False))
    def apply_force(self, force):
        self.acc += force
    def move(self):
        if not self.firework:
            self.vel.x *= 0.8
            self.vel.y *= 0.8
        self.vel += self.acc
        self.pos += self.vel
        self.acc *= 0
        if self.life == 0 and not self.firework:  # check if particle is outside explosion radius
            distance = math.sqrt((self.pos.x - self.origin.x) ** 2 + (self.pos.y - self.origin.y) ** 2)
            if distance > self.explosion_radius:
                self.remove = True
        self.decay()
        self.trail_update()
        self.life += 1
    def show(self, win):
        pygame.draw.circle(win, (self.colour[0], self.colour[1], self.colour[2], 0), (int(self.pos.x), int(self.pos.y)),
                           self.size)
    def decay(self):  # random decay of the particles
        if 50 > self.life > 10:  # early stage their is a small chance of decay
            ran = randint(0, 30)
            if ran == 0:
                self.remove = True
        elif self.life > 50:
            ran = randint(0, 5)
            if ran == 0:
                self.remove = True


Firework 类核心代码

class Firework:
    def __init__(self):
        # 随机颜色
        self.colour = (randint(0, 255), randint(0, 255), randint(0, 255))
        self.colours = (
            (randint(0, 255), randint(0, 255), randint(0, 255)),
            (randint(0, 255), randint(0, 255), randint(0, 255)),
            (randint(0, 255), randint(0, 255), randint(0, 255)))
        self.firework = Particle(randint(0, DISPLAY_WIDTH), DISPLAY_HEIGHT, True,
                                 self.colour)  # Creates the firework particle
        self.exploded = False
        self.particles = []
        self.min_max_particles = vector(100, 225)
    def update(self, win):  # called every frame
        if not self.exploded:
            self.firework.apply_force(gravity)
            self.firework.move()
            for tf in self.firework.trails:
                tf.show(win)
            self.show(win)
            if self.firework.vel.y >= 0:
                self.exploded = True
                self.explode()
        else:
            for particle in self.particles:
                particle.apply_force(vector(gravity.x + uniform(-1, 1) / 20, gravity.y / 2 + (randint(1, 8) / 100)))
                particle.move()
                for t in particle.trails:
                    t.show(win)
                particle.show(win)
    def remove(self):
        if self.exploded:
            for p in self.particles:
                if p.remove is True:
                    self.particles.remove(p)
            if len(self.particles) == 0:
                return True
            else:
                return False


最后,写一个 main 方法来对 pygame 环境进行初始化,例如背景图片,文字,设置页面刷新间隔,程序中设置的每 60ms 刷新一次。

pygame.display.set_caption("Fireworks in Pygame") # 标题
    background = pygame.image.load("img/1.png") # 背景
    myfont = pygame.font.Font("img/simkai.ttf",80)
    myfont1 = pygame.font.Font("img/simkai.ttf", 30)
    testsurface = myfont.render("元旦快乐",False,(255,255,255))
    testsurface1 = myfont1.render("By:小张Python", False, (255, 255, 255))
    # pygame.image.load("")
    win = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
    # win.blit(background)
    clock = pygame.time.Clock()
    fireworks = [Firework() for i in range(2)]  # create the first fireworks
    running = True
    while running:
        clock.tick(60)
        win.fill((20, 20, 30))  # draw background
        win.blit(background,(0,0))
        win.blit(testsurface,(200,200))
        win.blit(testsurface1, (300,200))
        if randint(0, 20) == 1:  # create new firework
            fireworks.append(Firework())
        update(win, fireworks)


另外程序中会对你的按键命令进行监控:

  • 当按下键 1时 ,会立即生成一个新的 “烟花”;
  • 当按下键 2时,会同时生成 10 个 “烟花”

for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:  # Change game speed with number keys
                if event.key == pygame.K_1: # 按下 1
                    fireworks.append(Firework())
                if event.key == pygame.K_2: # 按下 2 加入10个烟花
                    for i in range(10):
                        fireworks.append(Firework())


总的来说,整个小案例的代码量不算很多,一共250行左右,但案例中涉及到较为复杂的绘制逻辑和抽象的类之间的封装关系,因此大家理解代码相对会需要耗费点时间。


小结


写到这里,本篇文章算基本结束了,主要介绍就是如何用 Pygame 来模拟一个烟花绽放过程,核心内容大致两点:第一,如何用绘制点的方式来模拟烟花绽放运动轨迹;第二 介绍Pygame 一些基础用法:替换背景,绘制文字,更新状态等功能

相关文章
|
7月前
|
Python
Python跨年烟花秀
Python跨年烟花秀
173 0
|
6月前
|
前端开发 Python
Python烟花秀
Python烟花秀
98 1
|
7月前
|
存储 前端开发 Python
Python新春烟花盛宴
Python新春烟花盛宴
|
7月前
|
Python
过年了,让GPT用Python给你写个放烟花的程序吧!
过年了,让GPT用Python给你写个放烟花的程序吧!
95 0
|
7月前
|
Python
python烟花绘制,春节祝福
python烟花绘制,春节祝福
51 0
|
7月前
|
存储 前端开发 Python
Python新春烟花盛宴
Python新春烟花盛宴
60 0
|
Python
Python烟花(有源码)
Python烟花(有源码)
198 0
|
Python Windows
用 Python 实现一场环保无污染的烟花秀
用 Python 实现一场环保无污染的烟花秀
155 1
用 Python 实现一场环保无污染的烟花秀
|
Python
【兔年烟花】旖旎风景——浪漫烟花(Python实现)
【兔年烟花】旖旎风景——浪漫烟花(Python实现)
142 0
|
Python
Python烟花秀
Python跨年烟花表演。
153 0
Python烟花秀