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),
32 def _build_roach(self, name, **kw):
42 "attributes": attributes,
45 def _apply_set(self, updates):
46 for name, value in updates.items():
47 parts = name.split(".")
50 if isinstance(obj, dict):
52 elif isinstance(obj, list):
55 raise KeyError("%r not found in world" % (name,))
56 obj[parts[-1]] = value
59 return WorldDictProxy(self._state)
61 def apply_event(self, action, *args, **kw):
63 return self._apply_set(*args, **kw)
64 raise ValueError("Unknown world event action: %r" % (action,))
67 def _maybe_subproxy(proxy, name, value):
68 """ Return a sub world proxy if appropriate. """
69 if isinstance(value, dict):
70 prefix = "%s%s." % (proxy._prefix, name)
71 return WorldDictProxy(value, _prefix=prefix, _top=proxy._top)
72 elif isinstance(value, list):
73 prefix = "%s%s." % (proxy._prefix, name)
74 return WorldListProxy(value, _prefix=prefix, _top=proxy._top)
79 """ Base for world proxies. """
81 def __init__(self, state, _prefix='', _top=None):
87 self.__dict__.update({
94 def _record_change(self, fullname, value):
95 self._events.append(WorldEvent("set", {
100 events, self._events = self._events, []
104 class WorldDictProxy(WorldBaseProxy):
105 """ World dictionary proxy that records changes and produces events. """
109 (k, _maybe_subproxy(self, k, v)) for k, v in self._state.items())
111 def __setattr__(self, name, value):
112 self._top._record_change("%s%s" % (self._prefix, name), value)
114 def __getattr__(self, name):
115 return _maybe_subproxy(self, name, self._state[name])
118 class WorldListProxy(WorldBaseProxy):
119 """ World list proxy that records changes and produces events. """
121 def __setitem__(self, index, value):
122 self._top._record_change("%s%s" % (self._prefix, index), value)
124 def __getitem__(self, index):
125 return _maybe_subproxy(self, index, self._state[index])