source: nagslang/world.py@ 346:282113d86d75

Last change on this file since 346:282113d86d75 was 346:282113d86d75, checked in by Jeremy Thurgood <firxen@…>, 8 years ago

Save door and lever state.

File size: 2.2 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 self.attacks = 0
22 self.transformations = 0
23 self.kills = 0
24 self.rooms = 0
25 first_level = Level.list_levels()[0]
26 starting_position = (350, 300)
27 self.protagonist = Protagonist(pymunk.Space(), self, starting_position)
28 self.level = (first_level, starting_position)
29 self.level_state = {}
30
31 def _save_location(self):
32 app = 'nagslang'
33 if sys.platform.startswith('win'):
34 if 'APPDATA' in os.environ:
35 return os.path.join(os.environ['APPDATA'], app)
36 return os.path.join(os.path.expanduser('~'), '.' + app)
37 elif 'XDG_DATA_HOME' in os.environ:
38 return os.path.join(os.environ['XDG_DATA_HOME'], app)
39 return os.path.join(os.path.expanduser('~'), '.local', 'share', app)
40
41 def save(self):
42 data = {}
43 for attr in dir(self):
44 if attr.startswith('_'):
45 continue
46 value = getattr(self, attr)
47 if hasattr(value, '__name__'):
48 continue
49 # Hack until we save protagonist state
50 if hasattr(value, 'update') and not isinstance(value, dict):
51 continue
52 data[attr] = value
53
54 fn = self._save_location()
55 if not os.path.isdir(os.path.dirname(fn)):
56 os.makedirs(os.path.dirname(fn))
57 with open(fn, 'w') as f:
58 dump(data, f)
59
60 def load(self):
61 fn = self._save_location()
62 if not os.path.exists(fn):
63 return False
64 with open(fn) as f:
65 data = load(f)
66 for k, v in data.iteritems():
67 setattr(self, k, v)
68 return True
69
70 def get_formatted_stats(self):
71 return "\n".join([
72 "Times transformed: %d" % self.transformations,
73 "Enemies killed: %d" % self.kills,
74 "Rooms entered: %d" % self.rooms
75 ])
Note: See TracBrowser for help on using the repository browser.