source: nagslang/world.py@ 373:8c7c5db5f0d3

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

Change the flavour of magic in World

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