Skip to content

Instantly share code, notes, and snippets.

@dchrzanowski
Last active July 14, 2023 23:39
Show Gist options
  • Save dchrzanowski/5739ed6d242f6dee1f5d to your computer and use it in GitHub Desktop.
Save dchrzanowski/5739ed6d242f6dee1f5d to your computer and use it in GitHub Desktop.
Sprite sheet cutter for the pygame library, python.
def sprite_sheet(size, file_name, pos=(0, 0)):
"""Loads a sprite sheet.
(tuple(num, num), string, tuple(num, num) -> list
This functions cuts the given image into pieces(sprites) and returns them as a list of images.
WARNING!!! It needs the pygame library to be imported and initialised to work.
Basically this piece of code is to be used preferably within an existing program.
size is the size in pixels of the sprite. eg. (64, 64) sprite size of 64 pixels, by 64 pixels.
file_name is the file name that contains the sprite sheet. preferable format is png.
pos is the starting point on the image. eg. (10, 10) think about it as an offset.
"""
len_sprt_x, len_sprt_y = size # sprite size
sprt_rect_x, sprt_rect_y = pos # where to find first sprite on sheet
sheet = pygame.image.load(file_name).convert_alpha() # Load the sheet
sheet_rect = sheet.get_rect() # assign a rect of the sheet's size
sprites = [] # make a list of sprites
for i in range(0, sheet_rect.height, size[1]): # rows
for ii in range(0, sheet_rect.width, size[0]): # columns
sheet.set_clip(pygame.Rect(sprt_rect_x, sprt_rect_y, len_sprt_x, len_sprt_y)) # clip the sprite
sprite = sheet.subsurface(sheet.get_clip()) # grab the sprite from the clipped area
sprites.append(sprite) # append the sprite to the list
sprt_rect_x += len_sprt_x # go to the next sprite on the x axis
sprt_rect_y += len_sprt_y # go to the next row (y axis)
sprt_rect_x = 0 # reset the sprite on the x axis back to 0
return sprites # return the sprites
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment