Remove Dead Particles
Part of the Sound and Game Feel section of Coddy's Pygame journey. Lesson 11 of 23.
A dead particle is not drawn, but it is still in the list. Every frame the loop moves it and lowers its life again. Click 100 times and the list holds 2000 particles that nobody can see, and the game gets slower and slower. The counter at the top shows it.
Remove the dead ones once a frame, after the update. The clearest way builds a new list of the particles that are still alive:
particles = [p for p in particles if p["life"] > 0]That reads: the list of every p in particles whose life is above 0.
Do not remove items from a list while a for loop runs over that same list:
for p in particles:
if p["life"] <= 0:
particles.remove(p)When an item is removed, the next one moves into its place, and the loop steps past it without looking. Here every particle of a burst dies in the same frame, so half of them stay behind each time. Building a new list never skips anything.
Challenge
MediumEach click makes 20 particles that live 30 frames, and the counter never goes down. After the update loop, replace particles with a list of only the particles whose life is above 0, so the counter reads Particles: 0 once a burst is over.
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()
font = pygame.font.Font(None, 28)
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
for i in range(20):
particles.append({
"x": x,
"y": y,
"vx": random.uniform(-3, 3),
"vy": random.uniform(-3, 3),
"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)
label = font.render(f"Particles: {len(particles)}", True, (240, 240, 240))
screen.blit(label, (10, 10))
pygame.display.flip()
clock.tick(60)
pygame.quit()
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