-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspritesheet.py
54 lines (46 loc) · 1.96 KB
/
spritesheet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 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_alpha()
self.sheet.set_colorkey(-1, pygame.RLEACCEL)
except pygame.error as e:
print(f"Unable to load spritesheet image: {filename}")
raise SystemExit(e)
def image_at(self, rectangle, colorkey=None, scale=1):
"""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)
image = pygame.transform.scale(
image,
(
rectangle[2]*scale,
rectangle[3]*scale,
)
)
if colorkey is not None:
if colorkey == -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, pygame.RLEACCEL)
return image
def images_at(self, rects, colorkey=None, scale=1):
"""Load a whole bunch of images and return them as a list."""
return [self.image_at(rect, colorkey, scale=scale) for rect in rects]
def load_strip(self, rect, image_count, colorkey=None, scale=1):
"""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, scale=scale)