source: nagslang/world.py@ 374:150332d6c1fb

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

Move the inventory to world, to slightly reduce overall hackyness

File size: 2.3 KB
RevLine 
[238]1# The world object
2#
3# This is a global object for tracking state across scenes and all that
4
[252]5import os
6import sys
7
[276]8import pymunk
9
[342]10from nagslang.level import Level
11from nagslang.protagonist import Protagonist
[252]12from nagslang.yamlish import dump, load
13
[238]14
15class World(object):
16
17 def __init__(self):
[252]18 self.reset()
19
20 def reset(self):
[342]21 first_level = Level.list_levels()[0]
[345]22 starting_position = (350, 300)
[373]23 self.__dict__['_data'] = {
24 'attacks': 0,
25 'transformations': 0,
26 'kills': 0,
27 'rooms': 0,
28 'level': (first_level, starting_position),
29 'level_state': {},
[374]30 'inventory': set(),
[373]31 }
[374]32 self.__dict__['protagonist'] = Protagonist(
33 pymunk.Space(), self, starting_position)
[373]34
35 def __getattr__(self, name):
36 try:
37 return self._data[name]
38 except KeyError:
39 raise AttributeError()
40
41 def __setattr__(self, name, value):
42 if name not in self._data:
43 raise AttributeError("Worlds don't have a %s property" % name)
44 self._data[name] = value
[238]45
[252]46 def _save_location(self):
47 app = 'nagslang'
48 if sys.platform.startswith('win'):
49 if 'APPDATA' in os.environ:
50 return os.path.join(os.environ['APPDATA'], app)
51 return os.path.join(os.path.expanduser('~'), '.' + app)
52 elif 'XDG_DATA_HOME' in os.environ:
53 return os.path.join(os.environ['XDG_DATA_HOME'], app)
54 return os.path.join(os.path.expanduser('~'), '.local', 'share', app)
55
[238]56 def save(self):
[373]57 data = self._data.copy()
[374]58 data['inventory'] = sorted(data['inventory'])
[252]59 fn = self._save_location()
60 if not os.path.isdir(os.path.dirname(fn)):
61 os.makedirs(os.path.dirname(fn))
62 with open(fn, 'w') as f:
63 dump(data, f)
[238]64
65 def load(self):
[252]66 fn = self._save_location()
67 if not os.path.exists(fn):
68 return False
69 with open(fn) as f:
70 data = load(f)
[374]71 data['inventory'] = set(data['inventory'])
72 self.__dict__['_data'] = data
[252]73 return True
[238]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
[252]80 ])
Note: See TracBrowser for help on using the repository browser.