Today is 2022
The third day of , At this point in time , Some small partners have begun to recover the gains and losses of this year . For example, how many skill points have been added this year , How many books have you read , How many articles have been written or how much progress has been made in achieving small goals years ago ; Make a symbolic year-end summary to say goodbye 2021, meet 2022:

This article , Take everyone to use Python Make a cool fireworks show , To welcome the coming New Year's day . Take a look at the final effect before you start

Environment introduction :

language :Python;

library :Pygame;

<> Principle introduction

Before introducing the code , Let's introduce it first Pygame Basic principle of drawing fireworks , Fireworks are divided into three stages from launching to blooming :

1, Launch phase : At this stage, the shape of fireworks is linear upward , By setting a set of different sizes , Points with different colors to simulate “ Upward launch ” Movement of , During exercise
5 Points are given different accelerations , Over time , The point behind will catch up with the point ahead , Eventually all the points will come together , In bloom preparation stage ;

2, Fireworks bloom : Fireworks bloom at this stage , It is scattered by one point, and multiple points diverge in different directions , And the moving track of each point can be recorded , The purpose is to track the whole blooming track .

3, Fireworks wither
, This stage is responsible for depicting the effect of fireworks after blooming , Fireworks after blooming , And the falling speed and brightness at each time point ( Also called transparency in code ) It's different , So in the code , After the fireworks bloom, each point is given two attributes : Gravity vector and life cycle , To simulate the different display effects of fireworks in different periods ,

<> Code practice

The code part encapsulates fireworks into three classes :

Firework : Fireworks as a whole ;

Particle : Fireworks particles ( Include track )

Trail : Fireworks track , It is essentially a point .

The relationship between the three classes is : One Firework By multiple Particle constitute , And one Particle By multiple Trail constitute

First set the global variable , For example, gravity vector , Window size ,Trail Color list for ( Mostly gray or white ) And in different states Trail Interval between
gravity = vector(0, 0.3)DISPLAY_WIDTH = DISPLAY_HEIGHT = 800trail_colours =
[(45, 45, 45), (60, 60, 60), (75, 75, 75), (125, 125, 125), (150, 150,
150)]dynamic_offset = 1static_offset = 3
establish Trail class , definition show Method to draw a trajectory ,get_pos Real time acquisition of trajectory coordinates
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 core code
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)
# vector self.size = randint(2, 4) self.colour = choice(colour) # 5 individual tails total 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 core code
class Firework: def __init__(self): # Random color 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
last , Write one main Method to pygame Initialize environment , For example, background picture , written words , Set page refresh interval , Each set in the program 60ms Refresh once .
pygame.display.set_caption("Fireworks in Pygame") # title background =
pygame.image.load("img/1.png") # background myfont =
pygame.font.Font("img/simkai.ttf",80) myfont1 =
pygame.font.Font("img/simkai.ttf", 30) testsurface =
myfont.render(" Happy New Year's Day ",False,(255,255,255)) testsurface1 =
myfont1.render("By: Xiao Zhang 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)
In addition, the program will monitor your key commands :

* When the key is pressed 1 Time , A new will be generated immediately “ Fireworks ”;
* When the key is pressed 2 Time , Will be generated at the same time 10 individual “ Fireworks ” 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: # Press 1
fireworks.append(Firework()) if event.key == pygame.K_2: # Press 2 join 10 Fireworks for i
in range(10): fireworks.append(Firework())
in general , The amount of code in the whole small case is not very much , altogether 250 Line left and right , However, the case involves the encapsulation relationship between more complex drawing logic and abstract classes , Therefore, it will take some time to understand the code .

Write here , This article is basically over , The main introduction is how to use Pygame
To simulate a fireworks bloom , The core content is roughly two points : first , How to simulate the trajectory of fireworks blooming by drawing points ; second introduce Pygame
Some basic usage : Replace background , Draw text , Update status and other functions ;

Technology