2023年的最后时刻,希望小伙伴们都能找到属于自己的答案,找到自己激情的源泉,找到自己成长的机会。
2024即将到来,快学会这个烟花代码送给自己吧!
新年福利:基于python的电子烟花实现
import pygame as pg
import random as ra
import math
pg.init()
pg.display.set_caption("🎇")
winScreen = pg.display.Info()
screenWidth = winScreen.current_w
screenHeight = winScreen.current_h
vector = pg.math.Vector2
trail_colors = [(45, 45, 45), (60, 60, 60), (75, 75, 75), (125, 125, 125), (150, 150, 150)]
# 烟花类
class Firework:
def __init__(self):
# 随机生成颜色
self.colour = (ra.randint(0, 255), ra.randint(0, 255), ra.randint(0, 255))
# 随机生成三种颜色
self.colours = (
(ra.randint(0, 255), ra.randint(0, 255), ra.randint(0, 255)),
(ra.randint(0, 255), ra.randint(0, 255), ra.randint(0, 255)),
(ra.randint(0, 255), ra.randint(0, 255), ra.randint(0, 255))
)
# 生成一个表示发射出的火花的粒子对象
self.firework = Particle(ra.randint(0,screenWidth), screenHeight, True, self.colour)
# 初始化爆炸状态为 False
self.exploded = False
self.particles = []
# 爆炸产生的粒子数量范围
self.min_max_particles = vector(666, 999)
def update(self, win):
g = vector(0, ra.uniform(0.15, 0.4))
if not self.exploded:
# 给发射出的火花施加重力
self.firework.apply_force(g)
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(g.x + ra.uniform(-1, 1) / 20, g.y / 2 + (ra.randint(1, 8) / 100)))
particle.move()
for t in particle.trails:
t.show(win)
particle.show(win)
def explode(self):