1 | # The world object |
---|
2 | # |
---|
3 | # This is a global object for tracking state across scenes and all that |
---|
4 | |
---|
5 | import os |
---|
6 | import sys |
---|
7 | |
---|
8 | import pymunk |
---|
9 | |
---|
10 | from nagslang.level import Level |
---|
11 | from nagslang.protagonist import Protagonist |
---|
12 | from nagslang.yamlish import dump, load |
---|
13 | |
---|
14 | |
---|
15 | class World(object): |
---|
16 | |
---|
17 | def __init__(self): |
---|
18 | self.reset() |
---|
19 | |
---|
20 | def reset(self): |
---|
21 | first_level = Level.list_levels()[0] |
---|
22 | starting_position = (350, 300) |
---|
23 | self.__dict__['_data'] = { |
---|
24 | 'attacks': 0, |
---|
25 | 'deaths': 0, |
---|
26 | 'transformations': 0, |
---|
27 | 'kills': 0, |
---|
28 | 'rooms': 0, |
---|
29 | 'level': (first_level, starting_position), |
---|
30 | 'level_state': {}, |
---|
31 | 'inventory': set(), |
---|
32 | } |
---|
33 | self.__dict__['protagonist'] = Protagonist( |
---|
34 | pymunk.Space(), self, starting_position) |
---|
35 | |
---|
36 | def __getattr__(self, name): |
---|
37 | try: |
---|
38 | return self._data[name] |
---|
39 | except KeyError: |
---|
40 | raise AttributeError() |
---|
41 | |
---|
42 | def __setattr__(self, name, value): |
---|
43 | if name not in self._data: |
---|
44 | raise AttributeError("Worlds don't have a %s property" % name) |
---|
45 | self._data[name] = value |
---|
46 | |
---|
47 | def _save_location(self): |
---|
48 | app = 'nagslang' |
---|
49 | if sys.platform.startswith('win'): |
---|
50 | if 'APPDATA' in os.environ: |
---|
51 | return os.path.join(os.environ['APPDATA'], app) |
---|
52 | return os.path.join(os.path.expanduser('~'), '.' + app) |
---|
53 | elif 'XDG_DATA_HOME' in os.environ: |
---|
54 | return os.path.join(os.environ['XDG_DATA_HOME'], app) |
---|
55 | return os.path.join(os.path.expanduser('~'), '.local', 'share', app) |
---|
56 | |
---|
57 | def save(self): |
---|
58 | data = self._data.copy() |
---|
59 | data['inventory'] = sorted(data['inventory']) |
---|
60 | fn = self._save_location() |
---|
61 | if not os.path.isdir(os.path.dirname(fn)): |
---|
62 | os.makedirs(os.path.dirname(fn)) |
---|
63 | with open(fn, 'w') as f: |
---|
64 | dump(data, f) |
---|
65 | |
---|
66 | def load(self): |
---|
67 | fn = self._save_location() |
---|
68 | if not os.path.exists(fn): |
---|
69 | return False |
---|
70 | with open(fn) as f: |
---|
71 | data = load(f) |
---|
72 | data['inventory'] = set(data['inventory']) |
---|
73 | self.__dict__['_data'].update(data) |
---|
74 | return True |
---|
75 | |
---|
76 | def get_formatted_stats(self): |
---|
77 | return "\n".join([ |
---|
78 | "Times transformed: %d" % self.transformations, |
---|
79 | "Enemies killed: %d" % self.kills, |
---|
80 | "Rooms entered: %d" % self.rooms |
---|
81 | ]) |
---|