Python: File: Spritesheets.py

Return to the Python resources page.

Using this code to work with spritesheets is explained in this video: Learning Python 14: Sprite maps with PyGame

import pygame

def load_sprite_sheet_array(filename, rows, cols, offsetx, offsety):
    images = []
    SS = pygame.image.load(filename).convert_alpha()
    for col in range(0, cols):
        for row in range(0, rows):
            x = row*offsetx
            y = col*offsety
            image = pygame.Surface((offsetx,offsety), pygame.SRCALPHA).convert_alpha()
            image.blit(SS, (0, 0), (x,y,offsetx,offsety))
            images.append( image )
    return images

Copy and paste the above code into an empty Python file. Save it as spritesheet.py. To then use in your main program, add the following line at the top:

from spritesheet import load_sprite_sheet_array