source: nagslang/world.py@ 256:2a0bad886956

Last change on this file since 256:2a0bad886956 was 252:73d6abf5ba22, checked in by Stefano Rivera <stefano@…>, 8 years ago

Save game state

File size: 1.7 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
8from nagslang.yamlish import dump, load
9
10
11class World(object):
12
13 def __init__(self):
14 self.reset()
15
16 def reset(self):
17 self.transformations = 0
18 self.kills = 0
19 self.rooms = 0
20
21 def _save_location(self):
22 app = 'nagslang'
23 if sys.platform.startswith('win'):
24 if 'APPDATA' in os.environ:
25 return os.path.join(os.environ['APPDATA'], app)
26 return os.path.join(os.path.expanduser('~'), '.' + app)
27 elif 'XDG_DATA_HOME' in os.environ:
28 return os.path.join(os.environ['XDG_DATA_HOME'], app)
29 return os.path.join(os.path.expanduser('~'), '.local', 'share', app)
30
31 def save(self):
32 data = {}
33 for attr in dir(self):
34 if attr.startswith('_'):
35 continue
36 value = getattr(self, attr)
37 if hasattr(value, '__name__'):
38 continue
39 data[attr] = value
40
41 fn = self._save_location()
42 if not os.path.isdir(os.path.dirname(fn)):
43 os.makedirs(os.path.dirname(fn))
44 with open(fn, 'w') as f:
45 dump(data, f)
46
47 def load(self):
48 fn = self._save_location()
49 if not os.path.exists(fn):
50 return False
51 with open(fn) as f:
52 data = load(f)
53 for k, v in data.iteritems():
54 setattr(self, k, v)
55 return True
56
57 def get_formatted_stats(self):
58 return "\n".join([
59 "Times transformed: %d" % self.transformations,
60 "Enemies killed: %d" % self.kills,
61 "Rooms entered: %d" % self.rooms
62 ])
Note: See TracBrowser for help on using the repository browser.