How many particles you want? Yes

To add particles in a game is very important to make the game more attractive. So, here is some code to do it. This code has been optimezed for great performances. I will make it even faster in a next post.

https://pythonprogramming.altervista.org/wp-content/uploads/2021/08/Fireworks-2021-08-07-18-17-36.mp4
#!/usr/bin/python3.4
import pygame, sys, random
from pygame.locals import *


pygame.init()
clock = pygame.time.Clock()
pygame.display.set_caption('Fireworks')
screen = pygame.display.set_mode((1376, 900),0,32)
# [loc, velocity, timer]
particles = []
pygame.mouse.set_visible(False)

# ======================================= FPS ====
font = pygame.font.SysFont("Arial", 20)
def show_fps():
    "shows the frame rate on the screen"
    # global clock

    fr = str(int(clock.get_fps()))
    frt = font.render(fr, 1, pygame.Color("coral"))
    screen.blit(frt, (0, 0)) 


def particles_gen(pnum):
    for i in range(pnum):
        mx, my = pygame.mouse.get_pos()
        particles.append([[mx, my], [random.randint(0, 42) / 6 - 3.5, random.randint(0, 42) / 6 - 3.5], random.randint(4, 6)])
    return particles


def randrange():
    a, b, c = (random.randrange(0,255), random.randrange(0,255), random.randrange(0,255))
    return a, b, c


def move_particles(particles):
    for particle in particles:
        particle[0][0] += particle[1][0]
        particle[0][1] += particle[1][1]
        particle[2] -= 0.035
        particle[1][1] += 0.15
        # this conditions to remove unseen particles optimize the velocity
        conditions = particle[0][0] < 0 or particle[0][0] > 1376 or particle[0][1] > 900 or particle[0][1] < 0
        particles.remove(particle) if (particle[2] == 1 or conditions) else pygame.draw.circle(screen, randrange(), [int(particle[0][0]), int(particle[0][1])], int(particle[2]))


while True:
    
    screen.fill((0,0,0))
    particles = particles_gen(pnum=5)
    move_particles(particles)
    show_fps()
    # ========= FPS ============
    # Buttons ------------------- #
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()

    pygame.display.flip()
    clock.tick(60)

Subscribe to the newsletter for updates
Tkinter templates
My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts