1 """ World and player state. """
3 from .scenes.base import WorldEvent
34 """ World and player state. """
37 self._state = self._build_initial_state()
41 return self._state["level"]
45 return self._state["roaches"]
47 def _build_initial_state(self):
50 #self._build_roach("roachel", smart=True),
51 #self._build_roach("roeginald", strong=True),
52 #self._build_roach("roichard", fast=True),
53 self._build_roach("roupert"),
56 "smart", "strong", "fast",
62 "roachel", None, "roeginald",
66 "robot": {"seating": []},
67 "roomba": {"seating": []},
68 "quadcopter": {"seating": []},
75 def _build_roach(self, name, health=5, **kw):
83 def _apply_set(self, updates):
84 for name, value in updates.items():
85 parts = name.split(".")
88 if isinstance(obj, dict):
90 elif isinstance(obj, list):
93 raise KeyError("%r not found in world" % (name,))
94 obj[parts[-1]] = value
97 return WorldDictProxy(self._state)
99 def add_new_roach(self):
100 roach_names = [x['name'] for x in self.roaches]
102 if cand not in roach_names:
103 roach = self._build_roach(cand)
104 self._state['roaches'].append(roach)
107 def apply_event(self, action, *args, **kw):
109 return self._apply_set(*args, **kw)
110 raise ValueError("Unknown world event action: %r" % (action,))
113 def _maybe_subproxy(proxy, name, value):
114 """ Return a sub world proxy if appropriate. """
115 if isinstance(value, dict):
116 prefix = "%s%s." % (proxy._prefix, name)
117 return WorldDictProxy(value, _prefix=prefix, _top=proxy._top)
118 elif isinstance(value, list):
119 prefix = "%s%s." % (proxy._prefix, name)
120 return WorldListProxy(value, _prefix=prefix, _top=proxy._top)
124 class WorldBaseProxy:
125 """ Base for world proxies. """
127 def __init__(self, state, _prefix='', _top=None):
133 self.__dict__.update({
140 def _record_change(self, fullname, value):
141 self._events.append(WorldEvent("set", {
145 def pop_events(self):
146 events, self._events = self._events, []
150 class WorldDictProxy(WorldBaseProxy):
151 """ World dictionary proxy that records changes and produces events. """
155 (k, _maybe_subproxy(self, k, v)) for k, v in self._state.items())
157 def __setattr__(self, name, value):
158 self._top._record_change("%s%s" % (self._prefix, name), value)
160 def __getattr__(self, name):
161 # return None for attributes that don't exist
162 value = self._state.get(name)
163 return _maybe_subproxy(self, name, value)
165 def __setitem__(self, name, value):
166 return self.__setattr__(name, value)
168 def __getitem__(self, name):
169 return self.__getattr__(name)
172 class WorldListProxy(WorldBaseProxy):
173 """ World list proxy that records changes and produces events. """
175 def __setitem__(self, index, value):
176 self._top._record_change("%s%s" % (self._prefix, index), value)
178 def __getitem__(self, index):
179 return _maybe_subproxy(self, index, self._state[index])
182 return len(self._state)
185 return bool(self._state)