Menu
CoddyTech

A One-Shot Explosion

Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 28 of 36.

Some animations play once and end: an explosion shows explosion_1.png to explosion_4.png and is gone. As a sprite it can run its own counter and remove itself when it runs out of pictures:

def update(self):
    self.timer += 1
    if self.timer == 5:
        self.timer = 0
        self.index += 1
        if self.index == len(explosion_frames):
            self.kill()
        else:
            self.image = explosion_frames[self.index]

Each explosion has its own timer and index, so ten explosions started at different moments each play from the start. Changing self.image is all it takes: the group draws whatever picture the sprite holds now.

Test for the end before reading the list: explosion_frames[4] does not exist, and once the last picture has shown its 5 frames, kill() takes the explosion out of the group. Click anywhere in the window to set one off.

challenge icon

Challenge

Medium

Give Explosion an update method: every 5 frames it moves to the next picture in explosion_frames, and after the fourth picture has shown for 5 frames it calls self.kill().

Try it yourself

import pygame

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

explosion_frames = []
for n in range(1, 5):
    explosion_frames.append(pygame.image.load(f"assets/images/explosion_{n}.png").convert_alpha())


class Explosion(pygame.sprite.Sprite):
    def __init__(self, center):
        super().__init__()
        self.index = 0
        self.timer = 0
        self.image = explosion_frames[0]
        self.rect = self.image.get_rect(center=center)


explosions = pygame.sprite.Group()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            explosions.add(Explosion(event.pos))

    explosions.update()

    screen.fill((20, 22, 40))
    explosions.draw(screen)
    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 Sprites and Images

Practice on your own: Pygame playground