source: nagslang/world.py

Last change on this file was 530:bc053b9ab53f, checked in by Stefano Rivera <stefano@…>, 8 years ago

Load on startup

File size: 2.5 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(load=True)
21
22 def reset(self, load=False):
23 self.__dict__['_data'] = {
24 'attacks': 0,
25 'deaths': 0,
26 'transformations': 0,
27 'kills': 0,
28 'rooms': 0,
29 'level': (None, (None, None)),
30 'level_state': {},
31 'inventory': set(),
32 }
33 if load:
34 self.load()
35 else:
36 self.save()
37
38 def __getattr__(self, name):
39 try:
40 return self._data[name]
41 except KeyError:
42 raise AttributeError()
43
44 def __setattr__(self, name, value):
45 if name not in self._data:
46 raise AttributeError("Worlds don't have a %s property" % name)
47 self._data[name] = value
48
49 def _save_location(self):
50 app = 'nagslang'
51 if sys.platform.startswith('win'):
52 if 'APPDATA' in os.environ:
53 return os.path.join(os.environ['APPDATA'], app)
54 return os.path.join(os.path.expanduser('~'), '.' + app)
55 elif 'XDG_DATA_HOME' in os.environ:
56 return os.path.join(os.environ['XDG_DATA_HOME'], app)
57 return os.path.join(os.path.expanduser('~'), '.local', 'share', app)
58
59 def save(self):
60 data = self._data.copy()
61 data['inventory'] = sorted(data['inventory'])
62 fn = self._save_location()
63 if not os.path.isdir(os.path.dirname(fn)):
64 os.makedirs(os.path.dirname(fn))
65 with open(fn, 'w') as f:
66 dump(data, f)
67
68 def load(self):
69 fn = self._save_location()
70 if not os.path.exists(fn):
71 return False
72 with open(fn) as f:
73 data = load(f)
74 data['inventory'] = set(data['inventory'])
75 data['level'] = (data['level'][0], tuple(data['level'][1]))
76 self.__dict__['_data'].update(data)
77 return True
78
79 def get_formatted_stats(self):
80 return (('Times transformed: %(transformations)d\n'
81 'Shots fired/claws drawn: %(attacks)d\n'
82 'Enemies killed: %(kills)d\n'
83 'Rooms entered: %(rooms)d\n'
84 ) % self._data)
Note: See TracBrowser for help on using the repository browser.