How to Create Sprite Animation with Pygame’s Sprite Class
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
If we run this images in sequence it will create the motion illusion. like the movie frame.
So the inspiration and technique from this we will also load wheel image that will create the motion illusion in our example code As we have separate images that will create the motion . So we will load the image first and store that in a list. So will be easy for us to call the images sequence.
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
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.
For notification handling we will use plyer library We will add this functionality in our pygame code The complete code import pygame import sys from pygame.locals import * from plyer import notification pygame.init() clock = pygame.time.Clock() user_display = pygame.display.Info() width, height = 800, 600 screen = pygame.display.set_mode((width, height)) background = (255, 255, 255) red = […]
We will use python datetime module for our clock; We get the current time and separate the time into hour minutes and second. First get the current time Get the time in hour, minute and second Now got our clock time components. It will be like this import datetime current_time = datetime.datetime.now() hour = current_time.hour […]
Bird flocking is a wonderful example of how simple behaviors can lead to complex, beautiful patterns in nature. We’ll learn the key principles behind this flocking behavior and write a python program to simulate this wonderful phenomenon. The principles Bird Flocking Simulation Algorithm Setting Up the Simulation Each Frame of the Simulation The pygame example […]