-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdata.py
More file actions
96 lines (77 loc) · 2.89 KB
/
data.py
File metadata and controls
96 lines (77 loc) · 2.89 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import ujson
import os
import copy
import pygame
import yaml
import toml
from graphics import Sprite
from ecs import Entity
class DataLoader:
def __init__(self, directory):
self.root_dir = directory
self.sprites = {}
self.data = {}
class UnknownFileType(Exception):
''' Tried to parse a file with an unsupported or unknown
type'''
pass
def _get_cfg(self, name):
''' Gets data from a file in the data dir '''
# TODO: Add support for yaml, etc.
text = open(self._fname(name))
if name.endswith('.json'):
return json.load(text)
elif name.endswith('.yml') or name.endswith('.yaml'):
return yaml.safe_load(text)
elif name.endswith('.toml'):
return toml.load(text)
else:
print('unknown file type: ' + name)
#raise UnknownFileTypeException
def _fname(self, fname):
return os.path.join(self.root_dir, fname)
def preload(self):
''' This loads textual data, but does not load images.'''
for file_name in os.listdir(self.root_dir):
if os.path.isfile(os.path.join(self.root_dir, file_name)):
self.data[file_name.split('.')[0]] = self._get_cfg(file_name)
def load(self):
''' Loads images '''
for name, data in self.data['sprites'].items():
self.sprites[name] = self._get_sprite_with_defaults(data)
def _get_sprite_with_defaults(self, data):
''' Applies default derived values to sprite data
Intended to save a bunch of typing.'''
# TODO: Is there a more terse way to write this?
# You could probably make a really sophisticated prolog
# subsystem to determine all traits of a sprite from
# any minimal set of data.
image = pygame.image.load(
self._fname(data['file'])
).convert_alpha()
x_frames = 1
if 'x_frames' in data:
x_frames = data['x_frames']
y_frames = 1
if 'y_frames' in data:
y_frames = data['y_frames']
width = image.get_width() / x_frames
if 'width' in data:
width = data['width']
height = image.get_height() / y_frames
if 'height' in data:
height = data['height']
x_offset = width / 2
if 'x_offset' in data:
x_offset = data['x_offset']
y_offset = height / 2
if 'y_offset' in data:
y_offset = data['y_offset']
return Sprite(image, x_frames, y_frames,
width, height, x_offset, y_offset)
def spawn(self, utype, **kwargs):
mutable = copy.deepcopy({k: v for k, v in
self.data['units'][utype].items()
if not k.startswith('_')}) # Leading underscore = metadata
mutable.update(kwargs)
return Entity(mutable)