Images and sprites

Load PNG images, make them fast with convert_alpha(), and organise game objects with pygame.sprite.Sprite and Group.

Beginner3 min readUpdated
On this page

What you'll learn

  • How to load an image and find it reliably on disk
  • Why convert() and convert_alpha() make games faster
  • Scaling and flipping images
  • Writing Sprite classes and using Groups to update and draw them

Prerequisites: Keyboard input.

Download the code and images (ZIP)

Loading an image#

Python
image = pygame.image.load("player.png").convert_alpha()
screen.blit(image, (100, 200))

pygame.image.load reads PNG, JPEG, GIF (first frame), BMP and several other formats and returns a Surface. blit copies it onto the screen with its top-left corner at the given position.

Find files next to your script#

"player.png" is looked up relative to the current working directory, which is wherever you launched Python from, not necessarily your script's folder. Running from an editor or another folder then fails with FileNotFoundError. Build paths from the script's own location instead:

Python
from pathlib import Path
ASSETS = Path(__file__).parent / "assets"
image = pygame.image.load(ASSETS / "player.png").convert_alpha()

Why convert_alpha() matters#

A freshly loaded image is stored in the file's pixel format. Every time you blit it, Pygame converts each pixel to the screen's format, which is slow. convert() converts once up front; convert_alpha() does the same but keeps per-pixel transparency, which you want for PNG sprites. On a busy screen this can make blitting several times faster.

Both need a display mode, so call them after pygame.display.set_mode(), otherwise you get pygame.error: No video mode has been set.

Scaling and flipping#

Python
big = pygame.transform.scale_by(image, 3)                 # 3x larger, crisp pixels
small = pygame.transform.smoothscale(image, (16, 16))     # filtered, smoother result
facing_left = pygame.transform.flip(image, True, False)   # mirror horizontally

Transform once when you load, not every frame. Each call creates a new Surface. For pixel art, scale and scale_by keep hard edges; smoothscale blurs them. More in pixel art in Pygame.

Sprites and Groups#

A Sprite is a game object with two required attributes: image (what it looks like) and rect (where it is). A Group holds sprites and can update and draw all of them in one call.

sprites_basics.pyDownload
"""Loading images, convert_alpha(), blitting and a Sprite class with a Group."""
from pathlib import Path

import pygame

ASSETS = Path(__file__).parent / "assets"     # images live next to this file
WIDTH, HEIGHT = 640, 480

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

# convert_alpha() must be called after set_mode(); it makes blitting much faster.
player_image = pygame.image.load(ASSETS / "player.png").convert_alpha()
player_image = pygame.transform.scale_by(player_image, 3)     # 32x32 -> 96x96
coin_image = pygame.image.load(ASSETS / "coin.png").convert_alpha()
coin_image = pygame.transform.scale_by(coin_image, 2)


class Player(pygame.sprite.Sprite):
    def __init__(self, pos):
        super().__init__()
        self.image_right = player_image
        self.image_left = pygame.transform.flip(player_image, True, False)
        self.image = self.image_right
        self.rect = self.image.get_rect(midbottom=pos)

    def update(self, dt):
        keys = pygame.key.get_pressed()
        dx = (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * 250 * dt
        self.rect.x += round(dx)
        self.rect.clamp_ip(screen.get_rect())                 # keep it on screen
        if dx < 0:
            self.image = self.image_left
        elif dx > 0:
            self.image = self.image_right


class Coin(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = coin_image
        self.rect = self.image.get_rect(center=(x, y))


player = Player((WIDTH // 2, 420))
coins = pygame.sprite.Group(Coin(x, 380) for x in range(80, 600, 90))
all_sprites = pygame.sprite.Group(player, *coins)

running = True
while running:
    dt = clock.tick(60) / 1000
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    all_sprites.update(dt)                                    # calls update() on every sprite
    pygame.sprite.spritecollide(player, coins, dokill=True)   # touching a coin removes it

    screen.fill((180, 215, 250))
    pygame.draw.rect(screen, (100, 170, 90), (0, 420, WIDTH, 60))
    all_sprites.draw(screen)                                  # blits each sprite.image at sprite.rect
    pygame.display.flip()

pygame.quit()
A pixel-art character standing on grass between gold coins
sprites_basics.py with the player.png and coin.png images from the ZIP

What the Group does for you:

  • all_sprites.update(dt) calls update(dt) on every sprite in the group.
  • all_sprites.draw(screen) blits each sprite's image at its rect.
  • pygame.sprite.spritecollide(player, coins, dokill=True) returns the coins touching the player and, with dokill=True, removes them from all their groups.
  • A sprite can be in several groups. Keep one for drawing everything and others for logic, such as coins and enemies.

Call super().__init__() first in your sprite's __init__. Forgetting it causes AttributeError: ... has no attribute '_Sprite__g' when the sprite is added to a group.

Getting images#

Make your own with the pixel art editor, or use assets with a clear license. Many free game asset packs are released under CC0 (public domain) or CC BY (attribution required). Always keep a note of where each file came from and what its license requires.

Common mistakes#

  • convert_alpha() before set_mode() raises an error. Load images after opening the window.
  • Loading images inside the game loop reads the file from disk every frame. Load once at the start.
  • Rotating or scaling the same image repeatedly degrades it. Always transform from the original.
  • Black boxes around sprites: the image has no alpha channel. Use PNG with transparency and convert_alpha(), or set a colour key with image.set_colorkey((255, 0, 255)).

Practice exercises#

  1. Make coins respawn at a random position when collected and show a score.
  2. Add an Enemy sprite class that walks back and forth and ends the game on contact.
  3. Draw your own 16 × 16 character in the pixel art editor and use it as the player.
  4. Use pygame.sprite.LayeredUpdates so the player always draws in front of coins.
↑ ↓ to moveEnter to openEsc to close