1 """ World and player state. """
3 from .scenes.base import WorldEvent
4 from .roaches import build_roach
8 """ World and player state. """
11 self._state = self._build_initial_state()
15 return self._state["level"]
19 return self._state["roaches"]
21 def _build_initial_state(self):
24 build_roach(self, "roupert"),
31 "roachel", None, "roeginald",
35 "robot": {"seating": []},
36 "roomba": {"seating": []},
37 "quadcopter": {"seating": []},
47 def _get_obj(self, name):
48 parts = name.split(".")
51 if isinstance(obj, dict):
53 elif isinstance(obj, list):
56 raise KeyError("%r not found in world" % (name,))
59 def _apply_set(self, action, updates):
60 for name, value in updates.items():
61 obj, key = self._get_obj(name)
64 def _apply_append(self, action, updates):
65 for name, value in updates.items():
66 obj, key = self._get_obj(name)
69 def _apply_reset(self, action):
70 self._state = self._build_initial_state()
72 def _apply_unknown(self, action, *args, **kw):
73 raise ValueError("Unknown world event action: %r" % (action,))
76 return WorldDictProxy(self._state)
78 def apply_event(self, action, *args, **kw):
79 handler = getattr(self, "_apply_%s" % (action,))
80 return handler(action, *args, **kw)
83 def _maybe_subproxy(proxy, name, value):
84 """ Return a sub world proxy if appropriate. """
85 if isinstance(value, dict):
86 prefix = "%s%s." % (proxy._prefix, name)
87 return WorldDictProxy(value, _prefix=prefix, _top=proxy._top)
88 elif isinstance(value, list):
89 prefix = "%s%s." % (proxy._prefix, name)
90 return WorldListProxy(value, _prefix=prefix, _top=proxy._top)
95 """ Base for world proxies. """
97 def __init__(self, state, _prefix='', _top=None):
103 self.__dict__.update({
110 def _record_change(self, fullname, value, action="set"):
111 self._events.append(WorldEvent(action, {
115 def pop_events(self):
116 events, self._events = self._events, []
120 class WorldDictProxy(WorldBaseProxy):
121 """ World dictionary proxy that records changes and produces events. """
123 def __setattr__(self, name, value):
124 self._top._record_change("%s%s" % (self._prefix, name), value)
126 def __getattr__(self, name):
127 # return None for attributes that don't exist
128 value = self._state.get(name)
129 return _maybe_subproxy(self, name, value)
131 def __setitem__(self, name, value):
132 return self.__setattr__(name, value)
134 def __getitem__(self, name):
135 return self.__getattr__(name)
139 (k, _maybe_subproxy(self, k, v)) for k, v in self._state.items())
142 class WorldListProxy(WorldBaseProxy):
143 """ World list proxy that records changes and produces events. """
145 def __setitem__(self, index, value):
146 self._top._record_change("%s%s" % (self._prefix, index), value)
148 def __getitem__(self, index):
149 return _maybe_subproxy(self, index, self._state[index])
152 return len(self._state)
155 return bool(self._state)
157 def append(self, value):
158 self._top._record_change(self._prefix, value, action="append")