-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspritesheet.py
27 lines (24 loc) · 1.13 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
import xml.etree.ElementTree as ET
import pygame as pg
class SpriteSheet:
# load an atlas image
# can also pass an associated XML file (ref. Kenney art)
def __init__(self, img_file, data_file=None):
self.spritesheet = pg.image.load(img_file).convert_alpha()
if data_file:
tree = ET.parse(data_file)
self.map = {}
for node in tree.iter():
if node.attrib.get('name'):
name = node.attrib.get('name')
self.map[name] = {}
self.map[name]['x'] = int(node.attrib.get('x'))
self.map[name]['y'] = int(node.attrib.get('y'))
self.map[name]['width'] = int(node.attrib.get('width'))
self.map[name]['height'] = int(node.attrib.get('height'))
def get_image_rect(self, x, y, w, h):
return self.spritesheet.subsurface(pg.Rect(x, y, w, h))
def get_image_name(self, name):
rect = pg.Rect(self.map[name]['x'], self.map[name]['y'],
self.map[name]['width'], self.map[name]['height'])
return self.spritesheet.subsurface(rect)