SoFunction
Updated on 2024-10-29

Python New Year Cool Fireworks Show Code

Let's start with the basics of how Pygame draws fireworks, which are divided into three stages, from launching to blooming:

1, launch phase: in this phase the shape of the fireworks is linear upward, by setting a group of different sizes and colors of points to simulate the movement of the "upward launch" movement, the movement of the process of the five points are given different sizes of the acceleration, with the passage of time, the back of the point will catch up with the front of the point, and ultimately all the points will be converged, in the preparation stage of the bloom; in the preparation stage of the bloom. In the Bloom Preparation stage;

2, fireworks bloom: fireworks bloom this stage, is scattered from a point to a number of points in different directions, and the trajectory of each point may need to be recorded, in order to track the entire bloom trajectory.

3, fireworks fade, this stage is responsible for depicting the effect of fireworks after the bloom, after the bloom of the fireworks, and at each moment in the point of the decline in speed and brightness (also known as transparency in the code) is not the same, so the code, the fireworks will be bloomed will be given to each point of the two attributes: respectively, for the gravity vector and the life cycle to simulate the fireworks in different periods of time when the different display effects.

Screenshots of the program running:

Full program code:

import pygame
from random import randint, uniform, choice
import math
 
vector = .Vector2
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
 
 
 
class Firework:
    def __init__(self):
        # Random colors
         = (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)),
            (randint(0, 255), randint(0, 255), randint(0, 255)))
         = Particle(randint(0, DISPLAY_WIDTH), DISPLAY_HEIGHT, True,
                                 )  # Creates the firework particle
         = False
         = []
        self.min_max_particles = vector(100, 225)
 
    def update(self, win):  # called every frame
        if not :
            .apply_force(gravity)
            ()
            for tf in :
                (win)
 
            (win)
 
            if  >= 0:
                 = True
                ()
        else:
            for particle in :
                particle.apply_force(vector( + uniform(-1, 1) / 20,  / 2 + (randint(1, 8) / 100)))
                ()
                for t in :
                    (win)
                (win)
 
    def explode(self):
        # amount Quantity
        amount = randint(self.min_max_particles.x, self.min_max_particles.y)
        for i in range(amount):
            (Particle(, , False, ))
 
    def show(self, win):
        (win, , (int(), int()), )
 
    def remove(self):
        if :
            for p in :
                if  is True:
                    (p)
 
            if len() == 0:
                return True
            else:
                return False
 
 
class Particle:
    def __init__(self, x, y, firework, colour):
         = firework
         = vector(x, y)
         = vector(x, y)
         = 20
         = False
        self.explosion_radius = randint(5, 18)
         = 0
         = vector(0, 0)
        # trail variables
         = []  # 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 :
             = vector(0, -randint(17, 20))
             = 5
             = colour
            for i in range(5):
                (Trail(i, , True))
        else:
             = vector(uniform(-1, 1), uniform(-1, 1))
             *= randint(7, self.explosion_radius + 2)
             *= randint(7, self.explosion_radius + 2)
            # Vector
             = randint(2, 4)
             = choice(colour)
            # 5 tails total
            for i in range(5):
                (Trail(i, , False))
 
    def apply_force(self, force):
         += force
 
    def move(self):
        if not :
             *= 0.8
             *= 0.8
         += 
         += 
         *= 0
 
        if  == 0 and not :  # check if particle is outside explosion radius
            distance = (( - ) ** 2 + ( - ) ** 2)
            if distance > self.explosion_radius:
                 = True
 
        ()
 
        self.trail_update()
 
         += 1
 
    def show(self, win):
        (win, ([0], [1], [2], 0), (int(), int()),
                           )
 
    def decay(self):  # random decay of the particles
        if 50 >  > 10:  # early stage their is a small chance of decay
            ran = randint(0, 30)
            if ran == 0:
                 = True
        elif  > 50:
            ran = randint(0, 5)
            if ran == 0:
                 = True
 
    def trail_update(self):
        self.prev_posx.pop()
        self.prev_posx.insert(0, int())
        self.prev_posy.pop()
        self.prev_posy.insert(0, int())
 
        for n, t in enumerate():
            if :
                t.get_pos(self.prev_posx[n + dynamic_offset], self.prev_posy[n + dynamic_offset])
            else:
                t.get_pos(self.prev_posx[n + static_offset], self.prev_posy[n + static_offset])
 
 
class Trail:
    def __init__(self, n, size, dynamic):
        self.pos_in_line = n
         = vector(-10, -10)
         = dynamic
 
        if :
             = trail_colours[n]
             = int(size - n / 2)
        else:
             = (255, 255, 200)
             = size - 2
            if  < 0:
                 = 0
 
    def get_pos(self, x, y):
         = vector(x, y)
 
    def show(self, win):
        (win, , (int(), int()), )
 
 
def update(win, fireworks):
    for fw in fireworks:
        (win)
        if ():
            (fw)
 
    ()
 
 
def main():
    ()
    ()
    .set_caption("Fireworks in Pygame") # Title
    background = ("img/") # Background
    myfont = ("img/",80)
    myfont1 = ("img/", 30)
 
    testsurface = ("Happy New Year.",False,(251, 59, 85))
    testsurface1 = ("By:Python Code Book.", False, (251, 59, 85))
 
    # ("")
    win = .set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
    # (background)
    clock = ()
 
    fireworks = [Firework() for i in range(2)]  # create the first fireworks
    running = True
 
    while running:
        (60)
        for event in ():
            if  == :
                running = False
            if  == :  # Change game speed with number keys
                if  == pygame.K_1: # Press 1
                    (Firework())
                if  == pygame.K_2: # Press 2 to add 10 fireworks
                    for i in range(10):
                        (Firework())
        ((20, 20, 30))  # draw background
        (background,(0,0))
        (testsurface,(200,30))
        (testsurface1, (520,80))
 
        if randint(0, 20) == 1:  # create new firework
            (Firework())
 
        update(win, fireworks)
        # stats for fun
        # total_particles = 0
        # for f in fireworks:
        #    total_particles += len()
 
        # print(f"Fireworks: {len(fireworks)}\nParticles: {total_particles}\n\n")
 
    ()
    quit()
 
main()

To this article on the Python New Year's cool fireworks show code is introduced to this article, more related Python New Year's fireworks show content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!