how do i use sprite sheets in pygame?

  • Last Update :
  • Techknowledgy :

This file contains a class called SpriteSheet that can help us work with sprite sheets. The method we’re most interested in is image_at(). To use this, we’ll make an object from the SpriteSheet class, passing it the location of our sprite sheet file. We’ll figure out which rectangular portion of the sprite sheet we want to load - the coordinates of its top left corner, and the width and height of the region we want to load. We’ll call image_at() with these four values.,As mentioned earlier, it’s possible to load all of the images we need from the spritesheet at once, and then assign each one to the appropriate piece. This can be much easier than figuring out the coordinates by hand for each individual piece, especially if you’re working with multiple sprite sheets.,There are many ways we could have done this. You can create the piece first, and then load the image, or you can load the image and assign it to the piece in one line. I’m doing it the way you see here because in a little bit I’m going to show you how to load all the images at once, and then write a loop that creates the pieces all at once as well.,The Piece class allows us to assign each piece an image, a name, and a color. Each piece will start off at the top left corner, but we can move it wherever it needs to go. The only argument needed to create a piece initially is a reference to the overall game object. When we’re ready to draw a piece to the screen, we can do so by calling blitme().

""
"Chess game, for learning to grab images from a sprite sheet."
""

import sys

import pygame

from settings
import Settings

class ChessGame:
   ""
"Overall class to manage game assets and behavior."
""

def __init__(self):
   ""
"Initialize the game, and create resources."
""
pygame.init()
self.settings = Settings()

self.screen = pygame.display.set_mode(
   (self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption("Chess")

def run_game(self):
   ""
"Start the main loop for the game."
""
while True:
   self._check_events()
self._update_screen()

def _check_events(self):
   for event in pygame.event.get():
   if event.type == pygame.QUIT:
   sys.exit()
elif event.type == pygame.KEYDOWN:
   if event.key == pygame.K_q:
   sys.exit()

def _update_screen(self):
   self.screen.fill(self.settings.bg_color)
pygame.display.flip()

if __name__ == '__main__':
   chess_game = ChessGame()
chess_game.run_game()
class Settings:

   def __init__(self):
   self.screen_width, self.screen_height = 1200, 800
self.bg_color = (225, 225, 225)
""
"Module to represent a chess set, and individual pieces."
""

class Piece:
   ""
"Represents a chess piece."
""

def __init__(self, chess_game):
   ""
"Initialize attributes to represent a ches piece."
""
self.image = None
self.name = ''
self.color = ''

self.screen = chess_game.screen

# Start each piece off at the top left corner.
self.x, self.y = 0.0, 0.0

def blitme(self):
   ""
"Draw the piece at its current location."
""
self.rect = self.image.get_rect()
self.rect.topleft = self.x, self.y
self.screen.blit(self.image, self.rect)
""
"Module to represent a chess set, and individual pieces."
""

class ChessSet:
   ""
"Represents a set of chess pieces.
Each piece is an object of the Piece class.
""
"

def __init__(self, chess_game):
   ""
"Initialize attributes to represent the overall set of pieces."
""

self.chess_game = chess_game
self.pieces = []
self._load_pieces()

def _load_pieces(self):
   ""
"Builds the overall set: -
Loads images from the sprite sheet. -
   Creates a Piece object, and sets appropriate attributes
for that piece. -
   Adds each piece to the group self.pieces.
""
"
pass

class Piece:
   --snip--
# This class handles sprite sheets
# This was taken from www.scriptefun.com / transcript - 2 - using
# sprite - sheets - and - drawing - the - background
# I 've added some code to fail if the file wasn'
t found..
# Note: When calling images_at the rect is the format:
   #(x, y, x + offset, y + offset)

# Additional notes
# - Further adaptations from https: //www.pygame.org/wiki/Spritesheet
   # - Cleaned up overall formatting.
# - Updated from Python 2 - > Python 3.

import pygame

class SpriteSheet:

   def __init__(self, filename):
   ""
"Load the sheet."
""
try:
self.sheet = pygame.image.load(filename).convert()
except pygame.error as e:
   print(f "Unable to load spritesheet image: {filename}")
raise SystemExit(e)

def image_at(self, rectangle, colorkey = None):
   ""
"Load a specific image from a specific rectangle."
""
# Loads image from x, y, x + offset, y + offset.
rect = pygame.Rect(rectangle)
image = pygame.Surface(rect.size).convert()
image.blit(self.sheet, (0, 0), rect)
if colorkey is not None:
   if colorkey is - 1:
   colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, pygame.RLEACCEL)
return image

def images_at(self, rects, colorkey = None):
   ""
"Load a whole bunch of images and return them as a list."
""
return [self.image_at(rect, colorkey) for rect in rects]

def load_strip(self, rect, image_count, colorkey = None):
   ""
"Load a whole strip of images, and return them as a list."
""
tups = [(rect[0] + rect[2] * x, rect[1], rect[2], rect[3])
   for x in range(image_count)
]
return self.images_at(tups, colorkey)
""
"Module to represent a chess set, and individual pieces."
""

from spritesheet
import SpriteSheet

class ChessSet:
   --snip--

def _load_pieces(self):
   ""
"Builds the overall set: -
Loads images from the sprite sheet. -
   Creates a Piece object, and sets appropriate attributes
for that piece. -
   Adds each piece to the list self.pieces.
""
"
filename = 'images/chess_pieces.bmp'
piece_ss = SpriteSheet(filename)

# Create a black king.
b_king_rect = (68, 70, 85, 85)
b_king_image = piece_ss.image_at(b_king_rect)

b_king = Piece(self.chess_game)
b_king.image = b_king_image
b_king.name = 'king'
b_king.color = 'black'
self.pieces.append(b_king)

class Piece:
   --snip--

Suggestion : 2

Here is a sprite strip animation iterator built on spritesheet.spritesheet,function to load a strip of images.,to handle sprite sheets. After some digging on the internet I came across a class,And an example usage of sprite_strip_anim.SpriteStripAnim

# This class handles sprite sheets
# This was taken from www.scriptefun.com / transcript - 2 - using
# sprite - sheets - and - drawing - the - background
# I 've added some code to fail if the file wasn'
t found..
# Note: When calling images_at the rect is the format:
   #(x, y, x + offset, y + offset)

import pygame

class spritesheet(object):
   def __init__(self, filename):
   try:
   self.sheet = pygame.image.load(filename).convert()
except pygame.error, message:
   print 'Unable to load spritesheet image:', filename
raise SystemExit, message
# Load a specific image from a specific rectangle
def image_at(self, rectangle, colorkey = None):
   "Loads image from x,y,x+offset,y+offset"
rect = pygame.Rect(rectangle)
image = pygame.Surface(rect.size).convert()
image.blit(self.sheet, (0, 0), rect)
if colorkey is not None:
   if colorkey is - 1:
   colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, pygame.RLEACCEL)
return image
# Load a whole bunch of images and
return them as a list
def images_at(self, rects, colorkey = None):
   "Loads multiple images, supply a list of coordinates"
return [self.image_at(rect, colorkey) for rect in rects]
# Load a whole strip of images
def load_strip(self, rect, image_count, colorkey = None):
   "Loads a strip of images and returns them as a list"
tups = [(rect[0] + rect[2] * x, rect[1], rect[2], rect[3])
   for x in range(image_count)
]
return self.images_at(tups, colorkey)
import spritesheet
   ...
   ss = spritesheet.spriteshee('somespritesheet.png')
# Sprite is 16 x16 pixels at location 0, 0 in the file...
   image = ss.image_at((0, 0, 16, 16))
images = []
# Load two images into an array, their transparent bit is(255, 255, 255)
images = ss.images_at((0, 0, 16, 16), (17, 0, 16, 16), colorkey = (255, 255, 255))
   ...
import spritesheet

class SpriteStripAnim(object):
   ""
"sprite strip animator

This class provides an iterator(iter() and next() methods), and a
__add__() method
for joining strips which comes in handy when a
strip wraps to the next row.
""
"
def __init__(self, filename, rect, count, colorkey = None, loop = False, frames = 1):
   ""
"construct a SpriteStripAnim

filename, rect, count, and colorkey are the same arguments used
by spritesheet.load_strip.

loop is a boolean that, when True, causes the next() method to
loop.If False, the terminal
case raises StopIteration.

frames is the number of ticks to
return the same image before
the iterator advances to the next image.
""
"
self.filename = filename
ss = spritesheet.spritesheet(filename)
self.images = ss.load_strip(rect, count, colorkey)
self.i = 0
self.loop = loop
self.frames = frames
self.f = frames
def iter(self):
   self.i = 0
self.f = self.frames
return self
def next(self):
   if self.i >= len(self.images):
   if not self.loop:
   raise StopIteration
else:
   self.i = 0
image = self.images[self.i]
self.f -= 1
if self.f == 0:
   self.i += 1
self.f = self.frames
return image
def __add__(self, ss):
   self.images.extend(ss.images)
return self
""
"
Sprite strip animator demo

Requires spritesheet.spritesheet and the Explode1.bmp through Explode5.bmp
found in the sprite pack at
http: //lostgarden.com/2005/03/download-complete-set-of-sweet-8-bit.html

   I had to make the following addition to method spritesheet.image_at in
   order to provide the means to handle sprite strip cells with borders:

   elif type(colorkey) not in (pygame.Color, tuple, list):
   colorkey = image.get_at((colorkey, colorkey))
""
"
import sys
import pygame
from pygame.locals
import Color, KEYUP, K_ESCAPE, K_RETURN
import spritesheet
from sprite_strip_anim
import SpriteStripAnim

surface = pygame.display.set_mode((100, 100))
FPS = 120
frames = FPS / 12
strips = [
   SpriteStripAnim('Explode1.bmp', (0, 0, 24, 24), 8, 1, True, frames),
   SpriteStripAnim('Explode2.bmp', (0, 0, 12, 12), 7, 1, True, frames),
   SpriteStripAnim('Explode3.bmp', (0, 0, 48, 48), 4, 1, True, frames) +
   SpriteStripAnim('Explode3.bmp', (0, 48, 48, 48), 4, 1, True, frames),
   SpriteStripAnim('Explode4.bmp', (0, 0, 24, 24), 6, 1, True, frames),
   SpriteStripAnim('Explode5.bmp', (0, 0, 48, 48), 4, 1, True, frames) +
   SpriteStripAnim('Explode5.bmp', (0, 48, 48, 48), 4, 1, True, frames),
]
black = Color('black')
clock = pygame.time.Clock()
n = 0
strips[n].iter()
image = strips[n].next()
while True:
   for e in pygame.event.get():
   if e.type == KEYUP:
   if e.key == K_ESCAPE:
   sys.exit()
elif e.key == K_RETURN:
   n += 1
if n >= len(strips):
   n = 0
strips[n].iter()
surface.fill(black)
surface.blit(image, (0, 0))
pygame.display.flip()
image = strips[n].next()
clock.tick(FPS)

Suggestion : 3

So, you can start off by just using that. I'd give you an example tailored to your use case, but you haven't given us any idea what your code looks like or what you want to do, so I can't possibly give you anything better than is already on that page, so:

import spritesheet
   ...
   ss = spritesheet.spritesheet('somespritesheet.png')
# Sprite is 16 x16 pixels at location 0, 0 in the file...
   image = ss.image_at((0, 0, 16, 16))
images = []
# Load two images into an array, their transparent bit is(255, 255, 255)
images = ss.images_at((0, 0, 16, 16), (17, 0, 16, 16), colorkey = (255, 255, 255))…

Suggestion : 4

Last Updated : 22 Jun, 2022

Package Requirement

pip install pygame