2024年就快要到了,提前用python代码给自己做一个烟花秀庆祝一下。本次介绍的python实例是实现一个简易的烟花秀。
一、步骤分析
总的来说,要实现烟花秀的效果,需要以下几个步骤:
1.1、创建一个类,包含烟花各项粒子的轨迹的操作
1.2、创建一个类,包含烟花轨迹的各项操作
1.3、创建一个类,包含烟花相关的操作
1.4、在主函数文件中创建一个窗体
1.5、在窗体上绘制烟花及文字
二、步骤实现
2.1、前期准备
在前期我们需要将编程需要的素材准备好。这里编程平台使用的是pycharm,用到的pygame、sys、random包下面的相关类和方法已经自有的类和方法。
2.2、烟花粒子轨迹类实现代码
# 导入包
from pygame.math import Vector2 as vector
from pygame import display, draw, font
"""
粒子轨迹类
"""
class Trail:
# 全局变量
# 粒子颜色
trail_colours = [(45, 45, 45), (60, 60, 60), (75, 75, 75), (125, 125, 125), (150, 150, 150)]
def __init__(self, n, size, dynamic):
self.pos_in_line = n
self.pos = vector(-10, -10)
self.dynamic = dynamic
# 确定颜色和大小
if self.dynamic:
self.colour = self.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):
draw.circle(win, self.colour, (int(self.pos.x), int(self.pos.y)), self.size)
# 烟花更新
def update(win, fireworks):
# 实现烟花的显示
for fw in fireworks:
fw.update(win)
if fw.remove():
fireworks.remove(fw)
# 在屏幕上添加文字
snowFont = font.Font("./YuGothM.TTF", 100) # 导入字体文件,并设置字体
str1 = snowFont.render("元旦快乐", True, (235, 215, 245))
win.blit(str1, (200, 325))
display.update()
2.3、烟花轨迹类实现代码
# 导入包
import math
from random import randint, uniform, choice
from pygame import draw
from pygame.math import Vector2 as vector
# 自有文件
from litao.fire.Trail import Trail
"""
烟花轨迹类
"""
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)
# 跟踪变量
self.trails = [] # 存储粒子轨迹对象
self.prev_posx = [-10] * 10 # 存储x轴最后10个位置
self.prev_posy = [-10] * 10 # 存储y轴最后10个位置
# 根据是否有烟花,做不同的操作
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: # 检查粒子的爆炸范围
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):
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):
# 根据存活时间来控制衰变效果
if 50 > self.life > 10:
ran = randint(0, 30)
if ran == 0:
self.remove = True
elif self.life > 50:
ran = randint(0, 5)
if ran == 0:
self.remove = True
# 粒子更新方法
def trail_update(self):
self.prev_posx.pop()
self.prev_posx.insert(0, int(self.pos.x))
self.prev_posy.pop()
self.prev_posy.insert(0, int(self.pos.y))
for n, t in enumerate(self.trails):
if t.dynamic:
t.get_pos(self.prev_posx[n + 1], self.prev_posy[n + 1])
else:
t.get_pos(self.prev_posx[n + 3], self.prev_posy[n + 3])
2.4、烟花类实现代码
# 导入包
from random import randint, uniform
from pygame.math import Vector2 as vector
from pygame import draw
# 自有文件
from litao.fire.Particle import Particle
"""
烟花类
"""
class Firework:
# 全局变量
gravity = vector(0, 0.3)
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, 800), 700, True,
self.colour) # Creates the firework particle
self.exploded = False # 用于判断烟花是否分裂
self.particles = [] # 存储烟花轨迹对象
self.min_max_particles = vector(100, 225)
# 更新烟花
def update(self, win): # 每帧调用
if not self.exploded:
# 爆炸前效果
self.firework.apply_force(self.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(self.gravity.x + uniform(-1, 1) / 20, self.gravity.y / 2 + (randint(1, 8) / 100)))
particle.move()
for t in particle.trails:
t.show(win)
particle.show(win)
def explode(self):
# amount 数量
amount = randint(self.min_max_particles.x, self.min_max_particles.y)
for i in range(amount):
self.particles.append(Particle(self.firework.pos.x, self.firework.pos.y, False, self.colours))
# 烟花展示部分
def show(self, win):
draw.circle(win, self.colour, (int(self.firework.pos.x), int(self.firework.pos.y)), self.firework.size)
# 烟花移除部分
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
2.5、烟花秀实现代码
# 导入包
import pygame
import sys
from random import randint
from pygame import display, time
# 自有文件
from litao.fire.FireWorks import Firework
from litao.fire.Trail import update
"""
主函数
"""
# 创建窗口
pygame.init()
win = pygame.display.set_mode((800, 700)) # 设置窗口大小
display.set_caption("烟花秀") # 设置窗口标题
# 创建用于延时的对象
clock = time.Clock()
# 创建烟花集合
fireworks = [Firework() for i in range(2)]
while True:
clock.tick(60) # 延时60毫秒
# 设置鼠标和键盘监听事件,当鼠标点击X或者键盘按下esc时程序退出
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_ESCAPE]:
sys.exit()
win.fill((20, 20, 30)) # 重新绘制背景
# 如果产生的随机数为1,则添加一朵新的烟花
if randint(0, 20) == 1: # 创建新的烟花
fireworks.append(Firework())
# 刷新烟花
update(win, fireworks)
运行结果
最后这里免费分享给大家一份Python学习资料,包含视频、源码。课件,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。
编程资料、学习路线图、源代码、软件安装包等!
① Python所有方向的学习路线图
,清楚各个方向要学什么东西
② 100多节Python课程视频
,涵盖必备基础、爬虫和数据分析
③ 100多个Python实战案例
,学习不再是只会理论
④ 华为出品独家Python漫画教程
,手机也能学习
⑤ 历年互联网企业Python面试真题
,复习时非常方便****