Menu
CoddyTech

A Burst of Particles

Part of the Sound and Game Feel section of Coddy's Pygame journey. Lesson 9 of 23.

One particle is a dot. A burst is many particles made in the same frame at the same point, each flying its own way. Make them with a for loop, and give each one a random velocity:

for i in range(20):
    particles.append({
        "x": x,
        "y": y,
        "vx": random.uniform(-3, 3),
        "vy": random.uniform(-3, 3),
        "life": random.randint(20, 40),
    })

random.uniform(-3, 3) is a random decimal number from -3 to 3, so a particle can move any way, slow or fast. randint would give whole numbers only, and the burst would fly out in a few straight lines.

The random calls must be inside the loop. Pick vx once before it and all 20 particles get the same velocity: they fly together as one dot.

A random life makes the burst fade out unevenly, which looks natural: the slow ones near the middle and the fast ones at the edge go out at different times.

A mouse click is a pygame.MOUSEBUTTONDOWN event, and event.pos is the point that was clicked.

challenge icon

Challenge

Medium

A click makes one particle that rises. Turn it into a burst:

  1. On a click, append 20 particles at the clicked point.
  2. Give each one vx and vy from random.uniform(-3, 3) and a life from random.randint(20, 40).

Try it yourself

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Fireworks")
clock = pygame.time.Clock()

particles = []

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            x, y = event.pos
            particles.append({"x": x, "y": y, "vx": 0, "vy": -2, "life": 30})

    for p in particles:
        p["x"] += p["vx"]
        p["y"] += p["vy"]
        p["life"] -= 1

    screen.fill((20, 20, 36))
    for p in particles:
        if p["life"] > 0:
            pygame.draw.circle(screen, (255, 160, 60), (p["x"], p["y"]), 3)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Sound and Game Feel

Practice on your own: Pygame playground