1 """ World and player state. """
3 from .scenes.base import WorldEvent
7 """ World and player state. """
10 self._state = self._build_initial_state()
14 return self._state["level"]
18 return self._state["roaches"]
20 def _build_initial_state(self):
23 self._build_roach("roachel", intelligence=3),
24 self._build_roach("roeginald", strength=3),
25 self._build_roach("roichard", quickness=3),
29 "available": ["walking"],
36 def _build_roach(self, name, **kw):
46 "attributes": attributes,
49 def _apply_set(self, updates):
50 for name, value in updates.items():
51 parts = name.split(".")
54 if isinstance(obj, dict):
56 elif isinstance(obj, list):
59 raise KeyError("%r not found in world" % (name,))
60 obj[parts[-1]] = value
63 return WorldDictProxy(self._state)
65 def apply_event(self, action, *args, **kw):
67 return self._apply_set(*args, **kw)
68 raise ValueError("Unknown world event action: %r" % (action,))
71 def _maybe_subproxy(proxy, name, value):
72 """ Return a sub world proxy if appropriate. """
73 if isinstance(value, dict):
74 prefix = "%s%s." % (proxy._prefix, name)
75 return WorldDictProxy(value, _prefix=prefix, _top=proxy._top)
76 elif isinstance(value, list):
77 prefix = "%s%s." % (proxy._prefix, name)
78 return WorldListProxy(value, _prefix=prefix, _top=proxy._top)
83 """ Base for world proxies. """
85 def __init__(self, state, _prefix='', _top=None):
91 self.__dict__.update({
98 def _record_change(self, fullname, value):
99 self._events.append(WorldEvent("set", {
103 def pop_events(self):
104 events, self._events = self._events, []
108 class WorldDictProxy(WorldBaseProxy):
109 """ World dictionary proxy that records changes and produces events. """
113 (k, _maybe_subproxy(self, k, v)) for k, v in self._state.items())
115 def __setattr__(self, name, value):
116 self._top._record_change("%s%s" % (self._prefix, name), value)
118 def __getattr__(self, name):
119 return _maybe_subproxy(self, name, self._state[name])
122 class WorldListProxy(WorldBaseProxy):
123 """ World list proxy that records changes and produces events. """
125 def __setitem__(self, index, value):
126 self._top._record_change("%s%s" % (self._prefix, index), value)
128 def __getitem__(self, index):
129 return _maybe_subproxy(self, index, self._state[index])