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"),
27 "smart", "strong", "fast",
33 "roachel", None, "roeginald",
37 "robot": {"seating": []},
38 "roomba": {"seating": []},
39 "quadcopter": {"seating": []},
49 def _get_obj(self, name):
50 parts = name.split(".")
53 if isinstance(obj, dict):
55 elif isinstance(obj, list):
58 raise KeyError("%r not found in world" % (name,))
61 def _apply_set(self, action, updates):
62 for name, value in updates.items():
63 obj, key = self._get_obj(name)
66 def _apply_append(self, action, updates):
67 for name, value in updates.items():
68 obj, key = self._get_obj(name)
71 def _apply_reset(self, action):
72 self._state = self._build_initial_state()
74 def _apply_unknown(self, action, *args, **kw):
75 raise ValueError("Unknown world event action: %r" % (action,))
78 return WorldDictProxy(self._state)
80 def apply_event(self, action, *args, **kw):
81 handler = getattr(self, "_apply_%s" % (action,))
82 return handler(action, *args, **kw)
85 def _maybe_subproxy(proxy, name, value):
86 """ Return a sub world proxy if appropriate. """
87 if isinstance(value, dict):
88 prefix = "%s%s." % (proxy._prefix, name)
89 return WorldDictProxy(value, _prefix=prefix, _top=proxy._top)
90 elif isinstance(value, list):
91 prefix = "%s%s." % (proxy._prefix, name)
92 return WorldListProxy(value, _prefix=prefix, _top=proxy._top)
97 """ Base for world proxies. """
99 def __init__(self, state, _prefix='', _top=None):
105 self.__dict__.update({
112 def _record_change(self, fullname, value, action="set"):
113 self._events.append(WorldEvent(action, {
117 def pop_events(self):
118 events, self._events = self._events, []
122 class WorldDictProxy(WorldBaseProxy):
123 """ World dictionary proxy that records changes and produces events. """
125 def __setattr__(self, name, value):
126 self._top._record_change("%s%s" % (self._prefix, name), value)
128 def __getattr__(self, name):
129 # return None for attributes that don't exist
130 value = self._state.get(name)
131 return _maybe_subproxy(self, name, value)
133 def __setitem__(self, name, value):
134 return self.__setattr__(name, value)
136 def __getitem__(self, name):
137 return self.__getattr__(name)
141 (k, _maybe_subproxy(self, k, v)) for k, v in self._state.items())
144 class WorldListProxy(WorldBaseProxy):
145 """ World list proxy that records changes and produces events. """
147 def __setitem__(self, index, value):
148 self._top._record_change("%s%s" % (self._prefix, index), value)
150 def __getitem__(self, index):
151 return _maybe_subproxy(self, index, self._state[index])
154 return len(self._state)
157 return bool(self._state)
159 def append(self, value):
160 self._top._record_change(self._prefix, value, action="append")