source: nagslang/world.py@ 345:4708e86a9a3c

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

Remember start position on a level (a bit hacky)

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