source: nagslang/world.py@ 437:d087dfb10896

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

Replace menu and death screen with the starting level

File size: 2.4 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.__dict__['_data'] = {
22 'attacks': 0,
23 'deaths': 0,
24 'transformations': 0,
25 'kills': 0,
26 'rooms': 0,
27 'level': Level.game_starting_point(),
28 'level_state': {},
29 'inventory': set(),
30 }
31 self.__dict__['protagonist'] = Protagonist(
32 pymunk.Space(), self, self.level[1])
33
34 def __getattr__(self, name):
35 try:
36 return self._data[name]
37 except KeyError:
38 raise AttributeError()
39
40 def __setattr__(self, name, value):
41 if name not in self._data:
42 raise AttributeError("Worlds don't have a %s property" % name)
43 self._data[name] = value
44
45 def _save_location(self):
46 app = 'nagslang'
47 if sys.platform.startswith('win'):
48 if 'APPDATA' in os.environ:
49 return os.path.join(os.environ['APPDATA'], app)
50 return os.path.join(os.path.expanduser('~'), '.' + app)
51 elif 'XDG_DATA_HOME' in os.environ:
52 return os.path.join(os.environ['XDG_DATA_HOME'], app)
53 return os.path.join(os.path.expanduser('~'), '.local', 'share', app)
54
55 def save(self):
56 data = self._data.copy()
57 data['inventory'] = sorted(data['inventory'])
58 fn = self._save_location()
59 if not os.path.isdir(os.path.dirname(fn)):
60 os.makedirs(os.path.dirname(fn))
61 with open(fn, 'w') as f:
62 dump(data, f)
63
64 def load(self):
65 fn = self._save_location()
66 if not os.path.exists(fn):
67 return False
68 with open(fn) as f:
69 data = load(f)
70 data['inventory'] = set(data['inventory'])
71 data['level'] = (data['level'][0], tuple(data['level'][1]))
72 self.__dict__['_data'].update(data)
73 return True
74
75 def get_formatted_stats(self):
76 return (('Times transformed: %(transformations)d\n'
77 'Shots fired/claws drawn: %(attacks)d\n'
78 'Enemies killed: %(kills)d\n'
79 'Rooms entered: %(rooms)d\n'
80 ) % self._data)
Note: See TracBrowser for help on using the repository browser.