source: nagslang/world.py@ 505:80c452f348dc

Last change on this file since 505:80c452f348dc was 505:80c452f348dc, checked in by Stefano Rivera <stefano@…>, 8 years ago

Rearrange progress saving, to happen on room entrance

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