Pygame’s sprite class makes it easy to animate and handle sprite easily without write the heavy complex code. You can create animation without pygame sprite class but build in features like sprite class will help you write clean code more easily.
Lets get started
Step 1: Project Setup
Create a dedicated folder for your project.
Inside your project folder, create a subfolder named “sprite_images“. This is where you’ll place the image files for your animation frames.
Step 2: Back to programming: Import necessary modules and initiate pygame also setup the screen
import pygame
import os
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
background_color = (255, 255, 255) # White
Step 3: Load Animation Images
If you are familiar with old frame by frame animation technique if will be more easy.
Public Domain, Link
If we run this images in sequence it will create the motion illusion. like the movie frame.
We load the image from the folder sprite_images. In the folder or images names are 1.png, 2.png, ……10.png .We have 10 image in sequence. For sprite animation its required the transparent png image format, So we will able to adjust that in any background.
animation_folder = "sprite_images"
animation_images = []
for i in range(1, 11): # Adjust if you have more or fewer frames
image_path = os.path.join(animation_folder, f"{i}.png")
image = pygame.image.load(image_path)
animation_images.append(image)
Step 4: Define the AnimatedSprite Class
As we said we will use pygame sprite class. So first we define our class first.
We like to show the animation in the center of the display. so added this line
self.rect.center = (screen_width // 2, screen_height // 2)
And this function. load the image on sequence and update when reach the end of the frame numbers.
def update(self):
self.current_frame += 1
if self.current_frame >= len(self.frames):
self.current_frame = 0
self.image = self.frames[self.current_frame]
class AnimatedSprite(pygame.sprite.Sprite):
def __init__(self, animation_frames):
super().__init__()
self.frames = animation_frames
self.current_frame = 0
self.image = self.frames[self.current_frame]
self.rect = self.image.get_rect()
self.rect.center = (screen_width // 2, screen_height // 2)
def update(self):
self.current_frame += 1
if self.current_frame >= len(self.frames):
self.current_frame = 0
self.image = self.frames[self.current_frame]
# Crete the sprite instance and sprite group
player_sprite = AnimatedSprite(animation_images)
all_sprites = pygame.sprite.Group()
all_sprites.add(player_sprite)
Step 5: Update and apply everything in the game loop
We added the frame rate here. You can control the animation speed by controlling the frame rate…
clock.tick(60)
running = True
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
all_sprites.update()
screen.fill(background_color)
all_sprites.draw(screen)
pygame.display.flip()
clock.tick(60) # Limit to 60 frames per second
pygame.quit()
The Complete Code
import pygame
import os
# Initialize Pygame
pygame.init()
# --- Screen setup ---
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
background_color = (255, 255, 255) # White
# --- Load animation images ---
animation_folder = "sprite_images" # We stored the animation frame images in this folder.
animation_images = []
for i in range(1, 11): # Our images are "1.png" to "10.png"
image_path = os.path.join(animation_folder, f"{i}.png")
image = pygame.image.load(image_path)
animation_images.append(image)
# --- Create the sprite ---
class AnimatedSprite(pygame.sprite.Sprite):
def __init__(self, animation_frames):
super().__init__()
self.frames = animation_frames
self.current_frame = 0 # Start with the first frame
self.image = self.frames[self.current_frame]
self.rect = self.image.get_rect()
self.rect.center = (screen_width // 2, screen_height // 2) # Center on screen.. You can apply responsive postion whatever the with or height is
def update(self):
# Cycle through animation frames
self.current_frame += 1
if self.current_frame >= len(self.frames):
self.current_frame = 0
self.image = self.frames[self.current_frame]
# Create an instance of our sprite
player_sprite = AnimatedSprite(animation_images)
# Group for easier drawing
all_sprites = pygame.sprite.Group()
all_sprites.add(player_sprite)
# --- Main game loop ---
running = True
clock = pygame.time.Clock() # To control frame rate
while running:
# --- Handle events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# --- Update the sprite's animation ---
all_sprites.update()
# --- Drawing ---
screen.fill(background_color)
all_sprites.draw(screen)
pygame.display.flip() # Update the display
clock.tick(60) # Limit to 60 frames per second
# Quit Pygame
pygame.quit()
Get this code and discover more Pygame examples on GitHub
I add this code on github on my pygame examples repository. So you can easily save the code from github easily.