source: nagslang/world.py@ 342:11febdb72296

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

Resume from the previous level

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