signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def __setitem__(self, key, val):
created = key not in self<EOL>if key not in self._cache:<EOL><INDENT>self._cache[key] = self.Predecessors(self, key)<EOL><DEDENT>preds = self._cache[key]<EOL>preds.clear()<EOL>preds.update(val)<EOL>if created:<EOL><INDENT>self.send(self, key=key, val=val)<EOL><DEDENT>
Interpret ``val`` as a mapping of edges that end at ``dest``
f9015:c11:m2
def __delitem__(self, key):
it = self[key]<EOL>it.clear()<EOL>del self._cache[key]<EOL>self.send(self, key=key, val=None)<EOL>
Delete all edges ending at ``dest``
f9015:c11:m3
def _order_nodes(self):
raise NotImplemented<EOL>
Swap my orig and dest if desired
f9015:c12:m0
def __len__(self):
n = <NUM_LIT:0><EOL>for idx in iter(self):<EOL><INDENT>n += <NUM_LIT:1><EOL><DEDENT>return n<EOL>
How many edges currently connect my two nodes?
f9015:c12:m3
def __getitem__(self, idx):
if idx not in self:<EOL><INDENT>raise KeyError("<STR_LIT>")<EOL><DEDENT>return self._getedge(idx)<EOL>
Get an Edge with a particular index, if it exists at the present (branch, rev)
f9015:c12:m6
def __setitem__(self, idx, val):
orig, dest = self._order_nodes()<EOL>created = idx not in self<EOL>if orig not in self.graph.node:<EOL><INDENT>self.graph.add_node(orig)<EOL><DEDENT>if dest not in self.graph.node:<EOL><INDENT>self.graph.add_node(dest)<EOL><DEDENT>branch, turn, tick = self.db._nbtt()<EOL>self.db.query.exist_edge(<EOL>self.graph.name,<E...
Create an Edge at a given index from a mapping. Delete the existing Edge first, if necessary.
f9015:c12:m7
def __delitem__(self, idx):
branch, turn, tick = self.db._btt()<EOL>orig, dest = self._order_nodes()<EOL>tick += <NUM_LIT:1><EOL>e = self._getedge(idx)<EOL>e.clear()<EOL>if idx in self._cache:<EOL><INDENT>del self._cache[idx]<EOL><DEDENT>self.db._edges_cache.store(<EOL>self.graph.name, orig, dest, idx,<EOL>branch, turn, tick, None<EOL>)<EOL>self....
Delete the edge at a particular index
f9015:c12:m8
def clear(self):
for idx in self:<EOL><INDENT>del self[idx]<EOL><DEDENT>
Delete all edges between these nodes
f9015:c12:m9
def __getitem__(self, orig):
if orig not in self.graph.node:<EOL><INDENT>raise KeyError("<STR_LIT>")<EOL><DEDENT>return self._getsucc(orig)<EOL>
If the node exists, return its Successors
f9015:c13:m0
def __setitem__(self, orig, val):
r = self._getsucc(orig)<EOL>r.clear()<EOL>r.update(val)<EOL>self.send(self, key=orig, val=val)<EOL>
Interpret ``val`` as a mapping of successors, and turn it into a proper Successors object for storage
f9015:c13:m2
def __delitem__(self, orig):
succs = self._getsucc(orig)<EOL>succs.clear()<EOL>del self._cache[orig]<EOL>self.send(self, key=orig, val=None)<EOL>
Disconnect this node from everything
f9015:c13:m3
def _and_previous(self):
branch = self.db.branch<EOL>rev = self.db.rev<EOL>(parent, parent_rev) = self.db.sql('<STR_LIT>', branch).fetchone()<EOL>before_branch = parent if parent_rev == rev else branch<EOL>return (before_branch, rev-<NUM_LIT:1>, branch, rev)<EOL>
Return a 4-tuple that will usually be (current branch, current revision - 1, current branch, current revision), unless current revision - 1 is before the start of the current branch, in which case the first element will be the parent branch.
f9015:c16:m12
def clear(self):
self.adj.clear()<EOL>self.node.clear()<EOL>self.graph.clear()<EOL>
Remove all nodes and edges from the graph. Unlike the regular networkx implementation, this does *not* remove the graph's name. But all the other graph, node, and edge attributes go away.
f9015:c16:m13
def remove_edge(self, u, v):
try:<EOL><INDENT>del self.succ[u][v]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise NetworkXError(<EOL>"<STR_LIT>".format(u, v)<EOL>)<EOL><DEDENT>
Version of remove_edge that's much like normal networkx but only deletes once, since the database doesn't keep separate adj and succ mappings
f9015:c18:m0
def remove_edges_from(self, ebunch):
for e in ebunch:<EOL><INDENT>(u, v) = e[:<NUM_LIT:2>]<EOL>if u in self.succ and v in self.succ[u]:<EOL><INDENT>del self.succ[u][v]<EOL><DEDENT><DEDENT>
Version of remove_edges_from that's much like normal networkx but only deletes once, since the database doesn't keep separate adj and succ mappings
f9015:c18:m1
def add_edge(self, u, v, attr_dict=None, **attr):
if attr_dict is None:<EOL><INDENT>attr_dict = attr<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>attr_dict.update(attr)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise NetworkXError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT><DEDENT>if u not in self.node:<EOL><INDENT>self.node[u] = {}<EOL><DEDENT>if v not in self.node:<E...
Version of add_edge that only writes to the database once
f9015:c18:m2
def add_edges_from(self, ebunch, attr_dict=None, **attr):
if attr_dict is None:<EOL><INDENT>attr_dict = attr<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>attr_dict.update(attr)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise NetworkXError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT><DEDENT>for e in ebunch:<EOL><INDENT>ne = len(e)<EOL>if ne == <NUM_LIT:3>:<EOL><INDENT>u, v, dd =...
Version of add_edges_from that only writes to the database once
f9015:c18:m3
def remove_edge(self, u, v, key=None):
try:<EOL><INDENT>d = self.adj[u][v]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise NetworkXError(<EOL>"<STR_LIT>".format(u, v)<EOL>)<EOL><DEDENT>if key is None:<EOL><INDENT>d.popitem()<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>del d[key]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise NetworkXError(<EOL>"<STR_LIT>"...
Version of remove_edge that's much like normal networkx but only deletes once, since the database doesn't keep separate adj and succ mappings
f9015:c20:m0
def remove_edges_from(self, ebunch):
for e in ebunch:<EOL><INDENT>(u, v) = e[:<NUM_LIT:2>]<EOL>if u in self.succ and v in self.succ[u]:<EOL><INDENT>del self.succ[u][v]<EOL><DEDENT><DEDENT>
Version of remove_edges_from that's much like normal networkx but only deletes once, since the database doesn't keep separate adj and succ mappings
f9015:c20:m1
def add_edge(self, u, v, key=None, attr_dict=None, **attr):
if attr_dict is None:<EOL><INDENT>attr_dict = attr<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>attr_dict.update(attr)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise NetworkXError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT><DEDENT>if u not in self.node:<EOL><INDENT>self.node[u] = {}<EOL><DEDENT>if v not in self.node:<E...
Version of add_edge that only writes to the database once.
f9015:c20:m2
def getatt(attribute_name):
return property(attrgetter(attribute_name))<EOL>
An easy way to make an alias
f9018:m0
def singleton_get(s):
it = None<EOL>for that in s:<EOL><INDENT>if it is not None:<EOL><INDENT>return None<EOL><DEDENT>it = that<EOL><DEDENT>return it<EOL>
Take an iterable and return its only item if possible, else None.
f9018:m1
def sort_set(s):
if not isinstance(s, Set):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>s = frozenset(s)<EOL>if s not in _sort_set_memo:<EOL><INDENT>_sort_set_memo[s] = sorted(s, key=_sort_set_key)<EOL><DEDENT>return _sort_set_memo[s]<EOL>
Return a sorted list of the contents of a set This is intended to be used to iterate over world state, where you just need keys to be in some deterministic order, but the sort order should be obvious from the key. Non-strings come before strings and then tuples. Tuples compare element-wise as normal. ...
f9018:m4
def tables_for_meta(meta):
allegedb.alchemy.tables_for_meta(meta)<EOL>Table(<EOL>'<STR_LIT>', meta,<EOL>Column('<STR_LIT:key>', TEXT, primary_key=True),<EOL>Column(<EOL>'<STR_LIT>', TEXT, primary_key=True, default='<STR_LIT>'<EOL>),<EOL>Column('<STR_LIT>', INT, primary_key=True, default=<NUM_LIT:0>),<EOL>Column('<STR_LIT>', INT, primary_key=True...
Return a dictionary full of all the tables I need for LiSE. Use the provided metadata object.
f9019:m0
def queries(table):
def update_where(updcols, wherecols):<EOL><INDENT>"""<STR_LIT>"""<EOL>vmap = OrderedDict()<EOL>for col in updcols:<EOL><INDENT>vmap[col] = bindparam(col)<EOL><DEDENT>wheres = [<EOL>c == bindparam(c.name) for c in wherecols<EOL>]<EOL>tab = wherecols[<NUM_LIT:0>].table<EOL>return tab.update().values(**vmap).where(and_(*w...
Given dictionaries of tables and view-queries, return a dictionary of all the rest of the queries I need.
f9019:m2
def dict_delta(old, new):
r = {}<EOL>oldkeys = set(old.keys())<EOL>newkeys = set(new.keys())<EOL>r.update((k, new[k]) for k in newkeys.difference(oldkeys))<EOL>r.update((k, None) for k in oldkeys.difference(newkeys))<EOL>for k in oldkeys.intersection(newkeys):<EOL><INDENT>if old[k] != new[k]:<EOL><INDENT>r[k] = new[k]<EOL><DEDENT><DEDENT>return...
Return a dictionary containing the items of ``new`` that are either absent from ``old`` or whose values are different; as well as the value ``None`` for those keys that are present in ``old``, but absent from ``new``. Useful for describing changes between two versions of a dict.
f9020:m0
def __init__(self, args, kwargs={}, logq=None, logfile=None, loglevel=None):
kwargs.setdefault('<STR_LIT>', self.log)<EOL>self._real = Engine(*args, **kwargs)<EOL>self._logq = logq<EOL>self._loglevel = loglevel<EOL>self._muted_chars = set()<EOL>self.branch = self._real.branch<EOL>self.turn = self._real.turn<EOL>self.tick = self._real.tick<EOL>self._node_stat_cache = defaultdict(dict)<EOL>self._...
Instantiate an engine with the positional arguments ``args`` and the keyword arguments ``kwargs``. ``logq`` is a :class:`Queue` into which I'll put tuples of ``(loglevel, message)``.
f9020:c0:m0
def character_copy(self, char):
ret = self.character_stat_copy(char)<EOL>chara = self._real.character[char]<EOL>nv = self.character_nodes_stat_copy(char)<EOL>if nv:<EOL><INDENT>ret['<STR_LIT>'] = nv<EOL><DEDENT>ev = self.character_portals_stat_copy(char)<EOL>if ev:<EOL><INDENT>ret['<STR_LIT>'] = ev<EOL><DEDENT>avs = self.character_avatars_copy(char)<...
Return a dictionary describing character ``char``.
f9020:c0:m62
def character_delta(self, char, *, store=True):
ret = self.character_stat_delta(char, store=store)<EOL>nodes = self.character_nodes_delta(char, store=store)<EOL>chara = self._real.character[char]<EOL>if nodes:<EOL><INDENT>ret['<STR_LIT>'] = nodes<EOL><DEDENT>edges = self.character_portals_delta(char, store=store)<EOL>if edges:<EOL><INDENT>ret['<STR_LIT>'] = edges<EO...
Return a dictionary of changes to ``char`` since previous call.
f9020:c0:m63
def node_stat_copy(self, node_or_char, node=None):
if node is None:<EOL><INDENT>node = node_or_char<EOL><DEDENT>else:<EOL><INDENT>node = self._real.character[node_or_char].node[node]<EOL><DEDENT>return {<EOL>k: v.unwrap() if hasattr(v, '<STR_LIT>') and not hasattr(v, '<STR_LIT>') else v<EOL>for (k, v) in node.items() if k not in {<EOL>'<STR_LIT>',<EOL>'<STR_LIT:name>',...
Return a node's stats, prepared for pickling, in a dictionary.
f9020:c0:m72
def node_stat_delta(self, char, node, *, store=True):
try:<EOL><INDENT>old = self._node_stat_cache[char].get(node, {})<EOL>new = self.node_stat_copy(self._real.character[char].node[node])<EOL>if store:<EOL><INDENT>self._node_stat_cache[char][node] = new<EOL><DEDENT>r = dict_delta(old, new)<EOL>return r<EOL><DEDENT>except KeyError:<EOL><INDENT>return None<EOL><DEDENT>
Return a dictionary describing changes to a node's stats since the last time you looked at it. Deleted keys have the value ``None``. If the node's been deleted, this returns ``None``.
f9020:c0:m73
def character_nodes_stat_delta(self, char, *, store=True):
r = {}<EOL>nodes = set(self._real.character[char].node.keys())<EOL>for node in nodes:<EOL><INDENT>delta = self.node_stat_delta(char, node, store=store)<EOL>if delta:<EOL><INDENT>r[node] = delta<EOL><DEDENT><DEDENT>nsc = self._node_stat_cache[char]<EOL>for node in list(nsc.keys()):<EOL><INDENT>if node not in nodes:<EOL>...
Return a dictionary of ``node_stat_delta`` output for each node in a character.
f9020:c0:m74
@timely<EOL><INDENT>def update_node(self, char, node, patch):<DEDENT>
character = self._real.character[char]<EOL>if patch is None:<EOL><INDENT>del character.node[node]<EOL><DEDENT>elif node not in character.node:<EOL><INDENT>character.node[node] = patch<EOL>return<EOL><DEDENT>else:<EOL><INDENT>character.node[node].update(patch)<EOL><DEDENT>
Change a node's stats according to a dictionary. The ``patch`` dictionary should hold the new values of stats, keyed by the stats' names; a value of ``None`` deletes the stat.
f9020:c0:m76
@timely<EOL><INDENT>def update_nodes(self, char, patch, backdate=False):<DEDENT>
if backdate:<EOL><INDENT>parbranch, parrev = self._real._parentbranch_rev.get(<EOL>self._real.branch, ('<STR_LIT>', <NUM_LIT:0>)<EOL>)<EOL>tick_now = self._real.tick<EOL>self._real.tick = parrev<EOL><DEDENT>for i, (n, npatch) in enumerate(patch.items(), <NUM_LIT:1>):<EOL><INDENT>self.update_node(char, n, npatch)<EOL><D...
Change the stats of nodes in a character according to a dictionary.
f9020:c0:m77
@timely<EOL><INDENT>def del_node(self, char, node):<DEDENT>
del self._real.character[char].node[node]<EOL>for cache in (<EOL>self._char_nodes_rulebooks_cache,<EOL>self._node_stat_cache,<EOL>self._node_successors_cache<EOL>):<EOL><INDENT>try:<EOL><INDENT>del cache[char][node]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if char in self._char_nodes_cache and ...
Remove a node from a character.
f9020:c0:m78
@timely<EOL><INDENT>def thing_travel_to(self, char, thing, dest, weight=None, graph=None):<DEDENT>
return self._real.character[char].thing[thing].travel_to(dest, weight, graph)<EOL>
Make something find a path to ``dest`` and follow it. Optional argument ``weight`` is the portal stat to use to schedule movement times. Optional argument ``graph`` is an alternative graph to use for pathfinding. Should resemble a networkx DiGraph.
f9020:c0:m99
def patch(self, patch):
self.engine.handle(<EOL>'<STR_LIT>',<EOL>char=self.character.name,<EOL>patch=patch,<EOL>block=False<EOL>)<EOL>for node, stats in patch.items():<EOL><INDENT>nodeproxycache = self[node]._cache<EOL>for k, v in stats.items():<EOL><INDENT>if v is None:<EOL><INDENT>del nodeproxycache[k]<EOL><DEDENT>else:<EOL><INDENT>nodeprox...
Change a bunch of node stats at once. This works similarly to ``update``, but only accepts a dict-like argument, and it recurses one level. The patch is sent to the LiSE core all at once, so this is faster than using ``update``, too. :param patch: a dictionary. Keys are node n...
f9021:c9:m11
def handle(self, cmd=None, **kwargs):
if '<STR_LIT>' in kwargs:<EOL><INDENT>cmd = kwargs['<STR_LIT>']<EOL><DEDENT>elif cmd:<EOL><INDENT>kwargs['<STR_LIT>'] = cmd<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>branching = kwargs.get('<STR_LIT>', False)<EOL>cb = kwargs.pop('<STR_LIT>', None)<EOL>future = kwargs.pop('<STR_LIT>', False)...
Send a command to the LiSE core. The only positional argument should be the name of a method in :class:``EngineHandle``. All keyword arguments will be passed to it, with the exceptions of ``cb``, ``branching``, and ``silent``. With ``block=False``, don't wait for a result. ...
f9021:c35:m13
def pull(self, chars='<STR_LIT:all>', cb=None, block=True):
if block:<EOL><INDENT>deltas = self.handle('<STR_LIT>', chars=chars)<EOL>self._upd_caches(deltas)<EOL>if cb:<EOL><INDENT>cb(deltas)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return self._submit(self._pull_async, chars, cb)<EOL><DEDENT>
Update the state of all my proxy objects from the real objects.
f9021:c35:m23
def time_travel(self, branch, turn, tick=None, chars='<STR_LIT:all>', cb=None, block=True):
if cb and not chars:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if cb is not None and not callable(cb):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return self.handle(<EOL>'<STR_LIT>',<EOL>block=block,<EOL>branch=branch,<EOL>turn=turn,<EOL>tick=tick,<EOL>chars=chars,<EOL>cb=partial(self._upd_and_cb, ...
Move to a different point in the timestream. Needs ``branch`` and ``turn`` arguments. The ``tick`` is optional; if unspecified, you'll travel to the last tick in the turn. May take a callback function ``cb``, which will receive a dictionary describing changes to the characters in ``cha...
f9021:c35:m26
def remove(self, branch, turn, tick):
for parent, entitys in list(self.parents.items()):<EOL><INDENT>for entity, keys in list(entitys.items()):<EOL><INDENT>for key, branchs in list(keys.items()):<EOL><INDENT>if branch in branchs:<EOL><INDENT>branhc = branchs[branch]<EOL>if turn in branhc:<EOL><INDENT>trun = branhc[turn]<EOL>if tick in trun:<EOL><INDENT>del...
Delete data on or after this tick On the assumption that the future has been invalidated.
f9022:c13:m2
def truncate_loc(self, character, location, branch, turn, tick):
r = False<EOL>branches_turns = self.branches[character, location][branch]<EOL>branches_turns.truncate(turn)<EOL>if turn in branches_turns:<EOL><INDENT>bttrn = branches_turns[turn]<EOL>if bttrn.future(tick):<EOL><INDENT>bttrn.truncate(tick)<EOL>r = True<EOL><DEDENT><DEDENT>keyses = self.keys[character, location]<EOL>for...
Remove future data about a particular location Return True if I deleted anything, False otherwise.
f9022:c13:m3
def roundtrip_dedent(source):
return unparse(parse(dedent_source(source)))<EOL>
Reformat some lines of code into what unparse makes.
f9023:m0
def __init__(<EOL>self,<EOL>engine,<EOL>name,<EOL>triggers=None,<EOL>prereqs=None,<EOL>actions=None,<EOL>create=True<EOL>):
self.engine = engine<EOL>self.name = self.__name__ = name<EOL>branch, turn, tick = engine._btt()<EOL>if create and not self.engine._triggers_cache.contains_key(name, branch, turn, tick):<EOL><INDENT>tick += <NUM_LIT:1><EOL>self.engine.tick = tick<EOL>triggers = tuple(self._fun_names_iter('<STR_LIT>', triggers or []))<E...
Store the engine and my name, make myself a record in the database if needed, and instantiate one FunList each for my triggers, actions, and prereqs.
f9023:c5:m0
def _fun_names_iter(self, functyp, val):
funcstore = getattr(self.engine, functyp)<EOL>for v in val:<EOL><INDENT>if callable(v):<EOL><INDENT>setattr(funcstore, v.__name__, v)<EOL>yield v.__name__<EOL><DEDENT>elif v not in funcstore:<EOL><INDENT>raise KeyError("<STR_LIT>".format(<EOL>v, funcstore._tab<EOL>))<EOL><DEDENT>else:<EOL><INDENT>yield v<EOL><DEDENT><D...
Iterate over the names of the functions in ``val``, adding them to ``funcstore`` if they are missing; or if the items in ``val`` are already the names of functions in ``funcstore``, iterate over those.
f9023:c5:m2
def trigger(self, fun):
self.triggers.append(fun)<EOL>return fun<EOL>
Decorator to append the function to my triggers list.
f9023:c5:m4
def prereq(self, fun):
self.prereqs.append(fun)<EOL>return fun<EOL>
Decorator to append the function to my prereqs list.
f9023:c5:m5
def action(self, fun):
self.actions.append(fun)<EOL>return fun<EOL>
Decorator to append the function to my actions list.
f9023:c5:m6
def duplicate(self, newname):
if self.engine.rule.query.haverule(newname):<EOL><INDENT>raise KeyError("<STR_LIT>".format(newname))<EOL><DEDENT>return Rule(<EOL>self.engine,<EOL>newname,<EOL>list(self.triggers),<EOL>list(self.prereqs),<EOL>list(self.actions)<EOL>)<EOL>
Return a new rule that's just like this one, but under a new name.
f9023:c5:m7
def always(self):
self.triggers = [self.engine.trigger.truth]<EOL>
Arrange to be triggered every tick, regardless of circumstance.
f9023:c5:m8
@abstractmethod<EOL><INDENT>def _get_rule_mapping(self):<DEDENT>
raise NotImplementedError<EOL>
Get the :class:`RuleMapping` for my rulebook.
f9023:c8:m9
@abstractmethod<EOL><INDENT>def _get_rulebook_name(self):<DEDENT>
raise NotImplementedError<EOL>
Get the name of my rulebook.
f9023:c8:m10
@abstractmethod<EOL><INDENT>def _set_rulebook_name(self, n):<DEDENT>
raise NotImplementedError<EOL>
Tell the database that this is the name of the rulebook to use for me.
f9023:c8:m11
def new_empty(self, name):
if name in self:<EOL><INDENT>raise KeyError("<STR_LIT>".format(name))<EOL><DEDENT>new = Rule(self.engine, name)<EOL>self._cache[name] = new<EOL>self.send(self, rule=new, active=True)<EOL>return new<EOL>
Make a new rule with no actions or anything, and return it.
f9023:c10:m9
@contextmanager<EOL><INDENT>def loading(self):<DEDENT>
if getattr(self, '<STR_LIT>', False):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._initialized = False<EOL>yield<EOL>self._initialized = True<EOL>
Context manager for when you need to instantiate entities upon unpacking
f9024:c5:m0
def coinflip(self):
return self.choice((True, False))<EOL>
Return True or False with equal probability.
f9024:c5:m31
def roll_die(self, d):
return self.randint(<NUM_LIT:1>, d)<EOL>
Roll a die with ``d`` faces. Return the result.
f9024:c5:m32
def dice(self, n, d):
for i in range(<NUM_LIT:0>, n):<EOL><INDENT>yield self.roll_die(d)<EOL><DEDENT>
Roll ``n`` dice with ``d`` faces, and yield the results. This is an iterator. You'll get the result of each die in successon.
f9024:c5:m33
def dice_check(self, n, d, target, comparator='<STR_LIT>'):
from operator import gt, lt, ge, le, eq, ne<EOL>comps = {<EOL>'<STR_LIT:>>': gt,<EOL>'<STR_LIT:<>': lt,<EOL>'<STR_LIT>': ge,<EOL>'<STR_LIT>': le,<EOL>'<STR_LIT:=>': eq,<EOL>'<STR_LIT>': eq,<EOL>'<STR_LIT>': ne<EOL>}<EOL>try:<EOL><INDENT>comparator = comps.get(comparator, comparator)<EOL><DEDENT>except TypeError:<EOL><I...
Roll ``n`` dice with ``d`` sides, sum them, and return whether they are <= ``target``. If ``comparator`` is provided, use it instead of <=. You may use a string like '<' or '>='.
f9024:c5:m34
def percent_chance(self, pct):
if pct <= <NUM_LIT:0>:<EOL><INDENT>return False<EOL><DEDENT>if pct >= <NUM_LIT:100>:<EOL><INDENT>return True<EOL><DEDENT>return pct / <NUM_LIT:100> < self.random()<EOL>
Given a ``pct``% chance of something happening right now, decide at random whether it actually happens, and return ``True`` or ``False`` as appropriate. Values not between 0 and 100 are treated as though they were 0 or 100, whichever is nearer.
f9024:c5:m35
def get_delta(self, branch, turn_from, tick_from, turn_to, tick_to):
from allegedb.window import update_window, update_backward_window<EOL>if turn_from == turn_to:<EOL><INDENT>return self.get_turn_delta(branch, turn_to, tick_to, start_tick=tick_from)<EOL><DEDENT>delta = super().get_delta(branch, turn_from, tick_from, turn_to, tick_to)<EOL>if turn_from < turn_to:<EOL><INDENT>updater = pa...
Get a dictionary describing changes to the world. Most keys will be character names, and their values will be dictionaries of the character's stats' new values, with ``None`` for deleted keys. Characters' dictionaries have special keys 'nodes' and 'edges' which contain booleans indicating ...
f9024:c6:m2
def get_turn_delta(self, branch=None, turn=None, tick=None, start_tick=<NUM_LIT:0>):
branch = branch or self.branch<EOL>turn = turn or self.turn<EOL>tick = tick or self.tick<EOL>delta = super().get_turn_delta(branch, turn, start_tick, tick)<EOL>if branch in self._avatarness_cache.settings and turn in self._avatarness_cache.settings[branch]:<EOL><INDENT>for chara, graph, node, is_av in self._avatarness_...
Get a dictionary describing changes to the world within a given turn Defaults to the present turn, and stops at the present tick unless specified. See the documentation for ``get_delta`` for a detailed description of the delta format. :arg branch: branch of history, defaulting to the ...
f9024:c6:m3
def _remember_avatarness(<EOL>self, character, graph, node,<EOL>is_avatar=True, branch=None, turn=None,<EOL>tick=None<EOL>):
branch = branch or self.branch<EOL>turn = turn or self.turn<EOL>tick = tick or self.tick<EOL>self._avatarness_cache.store(<EOL>character,<EOL>graph,<EOL>node,<EOL>branch,<EOL>turn,<EOL>tick,<EOL>is_avatar<EOL>)<EOL>self.query.avatar_set(<EOL>character,<EOL>graph,<EOL>node,<EOL>branch,<EOL>turn,<EOL>tick,<EOL>is_avatar<...
Use this to record a change in avatarness. Should be called whenever a node that wasn't an avatar of a character now is, and whenever a node that was an avatar of a character now isn't. ``character`` is the one using the node as an avatar, ``graph`` is the character the node is...
f9024:c6:m5
def __init__(<EOL>self,<EOL>worlddb,<EOL>*,<EOL>string='<STR_LIT>',<EOL>function='<STR_LIT>',<EOL>method='<STR_LIT>',<EOL>trigger='<STR_LIT>',<EOL>prereq='<STR_LIT>',<EOL>action='<STR_LIT>',<EOL>connect_args={},<EOL>alchemy=False,<EOL>commit_modulus=None,<EOL>random_seed=None,<EOL>logfun=None,<EOL>validate=False,<EOL>c...
import os<EOL>worlddbpath = worlddb.replace('<STR_LIT>', '<STR_LIT>')<EOL>if clear and os.path.exists(worlddbpath):<EOL><INDENT>os.remove(worlddbpath)<EOL><DEDENT>if isinstance(string, str):<EOL><INDENT>self._string_file = string<EOL>if clear and os.path.exists(string):<EOL><INDENT>os.remove(string)<EOL><DEDENT><DEDENT...
Store the connections for the world database and the code database; set up listeners; and start a transaction :arg worlddb: Either a path to a SQLite database, or a rfc1738 URI for a database to connect to. :arg string: path to a JSON file storing strings to be used in the game :arg fun...
f9024:c6:m8
def debug(self, msg):
self.log('<STR_LIT>', msg)<EOL>
Log a message at level 'debug
f9024:c6:m11
def info(self, msg):
self.log('<STR_LIT:info>', msg)<EOL>
Log a message at level 'info
f9024:c6:m12
def warning(self, msg):
self.log('<STR_LIT>', msg)<EOL>
Log a message at level 'warning
f9024:c6:m13
def error(self, msg):
self.log('<STR_LIT:error>', msg)<EOL>
Log a message at level 'error
f9024:c6:m14
def critical(self, msg):
self.log('<STR_LIT>', msg)<EOL>
Log a message at level 'critical
f9024:c6:m15
def close(self):
import sys, os<EOL>for store in self.stores:<EOL><INDENT>if hasattr(store, '<STR_LIT>'):<EOL><INDENT>store.save(reimport=False)<EOL><DEDENT>path, filename = os.path.split(store._filename)<EOL>modname = filename[:-<NUM_LIT:3>]<EOL>if modname in sys.modules:<EOL><INDENT>del sys.modules[modname]<EOL><DEDENT><DEDENT>super(...
Commit changes and close the database.
f9024:c6:m17
def __enter__(self):
return self<EOL>
Return myself. For compatibility with ``with`` semantics.
f9024:c6:m18
def __exit__(self, *args):
self.close()<EOL>
Close on exit.
f9024:c6:m19
def advance(self):
try:<EOL><INDENT>return next(self._rules_iter)<EOL><DEDENT>except InnerStopIteration:<EOL><INDENT>self._rules_iter = self._follow_rules()<EOL>return StopIteration()<EOL><DEDENT>except StopIteration:<EOL><INDENT>self._rules_iter = self._follow_rules()<EOL>return final_rule<EOL><DEDENT>
Follow the next rule if available. If we've run out of rules, reset the rules iterator.
f9024:c6:m32
def new_character(self, name, data=None, **kwargs):
self.add_character(name, data, **kwargs)<EOL>return self.character[name]<EOL>
Create and return a new :class:`Character`.
f9024:c6:m33
def add_character(self, name, data=None, **kwargs):
self._init_graph(name, '<STR_LIT>')<EOL>self._graph_objs[name] = self.char_cls(self, name, data, **kwargs)<EOL>
Create a new character. You'll be able to access it as a :class:`Character` object by looking up ``name`` in my ``character`` property. ``data``, if provided, should be a networkx-compatible graph object. Your new character will be a copy of it. Any keyword arguments will be s...
f9024:c6:m34
def del_character(self, name):
self.query.del_character(name)<EOL>self.del_graph(name)<EOL>del self.character[name]<EOL>
Remove the Character from the database entirely. This also deletes all its history. You'd better be sure.
f9024:c6:m35
def alias(self, v, stat='<STR_LIT>'):
from .util import EntityStatAccessor<EOL>r = DummyEntity(self)<EOL>r[stat] = v<EOL>return EntityStatAccessor(r, stat, engine=self)<EOL>
Return a representation of a value suitable for use in historical queries. It will behave much as if you assigned the value to some entity and then used its ``historical`` method to get a reference to the set of its past values, which happens to contain only the value you've provided here, ``v`...
f9024:c6:m38
def turns_when(self, qry):
<EOL>for branch, turn in qry.iter_turns():<EOL><INDENT>yield turn<EOL><DEDENT>
Iterate over the turns in this branch when the query held true :arg qry: a Query, likely constructed by comparing the result of a call to an entity's ``historical`` method with the output of ``self.alias(..)`` or another ``historical(..)``
f9024:c6:m40
def roommate_collisions(engine):
done = set()<EOL>for chara in engine.character.values():<EOL><INDENT>if chara.name in done:<EOL><INDENT>continue<EOL><DEDENT>match = re.match('<STR_LIT>', chara.name)<EOL>if not match:<EOL><INDENT>continue<EOL><DEDENT>dorm, room, student = match.groups()<EOL>other_student = '<STR_LIT:1>' if student == '<STR_LIT:0>' els...
Test queries' ability to tell that all of the students that share rooms have been in the same place.
f9027:m1
def sober_collisions(engine):
students = [<EOL>stu for stu in<EOL>engine.character['<STR_LIT>'].stat['<STR_LIT>']<EOL>if not (stu.stat['<STR_LIT>'] or stu.stat['<STR_LIT>'])<EOL>]<EOL>assert students<EOL>def sameClasstime(stu0, stu1):<EOL><INDENT>assert list(<EOL>engine.turns_when(<EOL>stu0.avatar.only.historical('<STR_LIT:location>') ==<EOL>stu1.a...
Students that are neither lazy nor drunkards should all have been in class together at least once.
f9027:m3
def noncollision(engine):
dorm = defaultdict(lambda: defaultdict(dict))<EOL>for character in engine.character.values():<EOL><INDENT>match = re.match('<STR_LIT>', character.name)<EOL>if not match:<EOL><INDENT>continue<EOL><DEDENT>d, r, s = match.groups()<EOL>dorm[d][r][s] = character<EOL><DEDENT>for d in dorm:<EOL><INDENT>other_dorms = [dd for d...
Make sure students *not* from the same room never go there together
f9027:m5
def set_in_mapping(mapp, stat, v):
<EOL>if stat == '<STR_LIT:name>':<EOL><INDENT>return<EOL><DEDENT>if v is None:<EOL><INDENT>del mapp[stat]<EOL>return<EOL><DEDENT>if stat not in mapp:<EOL><INDENT>mapp[stat] = v<EOL>return<EOL><DEDENT>if isinstance(v, dict) or isinstance(v, set):<EOL><INDENT>mapp[stat].update(v)<EOL>for item in list(mapp[stat]):<EOL><IN...
Sync a value in ``mapp``, having key ``stat``, with ``v``.
f9030:m0
def update_char(char, *, stat=(), node=(), portal=()):
def update(d, dd):<EOL><INDENT>for k, v in dd.items():<EOL><INDENT>if v is None and k in d:<EOL><INDENT>del d[k]<EOL><DEDENT>else:<EOL><INDENT>d[k] = v<EOL><DEDENT><DEDENT><DEDENT>end_stats = char.stat.unwrap()<EOL>for stat, v in stat:<EOL><INDENT>set_in_mapping(char.stat, stat, v)<EOL>if v is None and stat in end_stat...
Make a bunch of changes to a character-like object
f9030:m1
def __init__(<EOL>self,<EOL>message,<EOL>path=None,<EOL>followed=None,<EOL>traveller=None,<EOL>branch=None,<EOL>turn=None,<EOL>lastplace=None<EOL>):
self.path = path<EOL>self.followed = followed<EOL>self.traveller = traveller<EOL>self.branch = branch<EOL>self.turn = turn<EOL>self.lastplace = lastplace<EOL>super().__init__(message)<EOL>
Store the message as usual, and also the optional arguments: ``path``: a list of Place names to show such a path as you found ``followed``: the portion of the path actually followed ``traveller``: the Thing doing the travelling ``branch``: branch during travel ``tick``: tick...
f9036:c6:m0
def do(self, func, *args, **kwargs):
if not callable(func):<EOL><INDENT>func = getattr(self.engine.function, func)<EOL><DEDENT>func(self, *args, **kwargs)<EOL>return self<EOL>
Apply the function to myself, and return myself. Look up the function in the database if needed. Pass it any arguments given, keyword or positional. Useful chiefly when chaining.
f9037:c1:m28
def perlin(self, stat='<STR_LIT>'):
from math import floor<EOL>p = self.engine.shuffle([<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT:15>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT:7>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT:30>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT:...
Apply Perlin noise to my nodes, and return myself. I'll try to use the name of the node as its spatial position for this purpose, or use its stats 'x', 'y', and 'z', or skip the node if neither are available. z is assumed 0 if not provided for a node. Result will be stored in a...
f9037:c1:m29
def copy_from(self, g):
renamed = {}<EOL>for k, v in g.node.items():<EOL><INDENT>ok = k<EOL>if k in self.place:<EOL><INDENT>n = <NUM_LIT:0><EOL>while k in self.place:<EOL><INDENT>k = ok + (n,) if isinstance(ok, tuple) else (ok, n)<EOL>n += <NUM_LIT:1><EOL><DEDENT><DEDENT>renamed[ok] = k<EOL>self.place[k] = v<EOL><DEDENT>if type(g) is nx.Multi...
Copy all nodes and edges from the given graph into this. Return myself.
f9037:c1:m30
def become(self, g):
self.clear()<EOL>self.copy_from(g)<EOL>return self<EOL>
Erase all my nodes and edges. Replace them with a copy of the graph provided. Return myself.
f9037:c1:m31
def grid_2d_8graph(self, m, n):
me = nx.Graph()<EOL>node = me.node<EOL>add_node = me.add_node<EOL>add_edge = me.add_edge<EOL>for i in range(m):<EOL><INDENT>for j in range(n):<EOL><INDENT>add_node((i, j))<EOL>if i > <NUM_LIT:0>:<EOL><INDENT>add_edge((i, j), (i-<NUM_LIT:1>, j))<EOL>if j > <NUM_LIT:0>:<EOL><INDENT>add_edge((i, j), (i-<NUM_LIT:1>, j-<NUM...
Make a 2d graph that's connected 8 ways, enabling diagonal movement
f9037:c1:m39
def cull_nodes(self, stat, threshold=<NUM_LIT:0.5>, comparator=ge):
comparator = self._lookup_comparator(comparator)<EOL>dead = [<EOL>name for name, node in self.node.items()<EOL>if stat in node and comparator(node[stat], threshold)<EOL>]<EOL>self.remove_nodes_from(dead)<EOL>return self<EOL>
Delete nodes whose stat >= ``threshold`` (default 0.5). Optional argument ``comparator`` will replace >= as the test for whether to cull. You can use the name of a stored function.
f9037:c1:m90
def cull_portals(self, stat, threshold=<NUM_LIT:0.5>, comparator=ge):
comparator = self._lookup_comparator(comparator)<EOL>dead = []<EOL>for u in self.portal:<EOL><INDENT>for v in self.portal[u]:<EOL><INDENT>if stat in self.portal[u][v] and comparator(<EOL>self.portal[u][v][stat], threshold<EOL>):<EOL><INDENT>dead.append((u, v))<EOL><DEDENT><DEDENT><DEDENT>self.remove_edges_from(dead)<EO...
Delete portals whose stat >= ``threshold`` (default 0.5). Optional argument ``comparator`` will replace >= as the test for whether to cull. You can use the name of a stored function.
f9037:c1:m91
def cull_edges(self, stat, threshold=<NUM_LIT:0.5>, comparator=ge):
return self.cull_portals(stat, threshold, comparator)<EOL>
Delete edges whose stat >= ``threshold`` (default 0.5). Optional argument ``comparator`` will replace >= as the test for whether to cull. You can use the name of a stored function.
f9037:c1:m92
def __init__(self, character, rulebook, booktyp):
super().__init__(rulebook.engine, rulebook)<EOL>self.character = character<EOL>self._table = booktyp + "<STR_LIT>"<EOL>
Initialize as usual for the ``rulebook``, mostly. My ``character`` property will be the one passed in, and my ``_table`` will be the ``booktyp`` with ``"_rules"`` appended.
f9037:c2:m0
def __init__(self, character, fun):
if not callable(fun):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self.character = character<EOL>if isinstance(fun, str):<EOL><INDENT>self.fun = self.engine.sense[fun]<EOL><DEDENT>else:<EOL><INDENT>self.fun = fun<EOL><DEDENT>
Store the character and the function. Look up the function in the engine's ``sense`` function store, if needed.
f9037:c4:m0
def __call__(self, observed):
if isinstance(observed, str):<EOL><INDENT>observed = self.engine.character[observed]<EOL><DEDENT>return self.fun(self.engine, self.character, Facade(observed))<EOL>
Call the function, prefilling the engine and observer arguments.
f9037:c4:m1
def __init__(self, container, sensename):
self.container = container<EOL>self.sensename = sensename<EOL>
Store the container and the name of the sense.
f9037:c5:m0
@property<EOL><INDENT>def func(self):<DEDENT>
fn = self.engine.query.sense_func_get(<EOL>self.observer.name,<EOL>self.sensename,<EOL>*self.engine._btt()<EOL>)<EOL>if fn is not None:<EOL><INDENT>return SenseFuncWrap(self.observer, fn)<EOL><DEDENT>
Return the function most recently associated with this sense.
f9037:c5:m1
def __call__(self, observed):
r = self.func(observed)<EOL>if not (<EOL>isinstance(r, Character) or<EOL>isinstance(r, Facade)<EOL>):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>return r<EOL>
Call my sense function and make sure it returns the right type, then return that.
f9037:c5:m2
def __init__(self, character):
super().__init__()<EOL>self.character = character<EOL>
Store the character.
f9037:c6:m0
def __iter__(self):
yield from self.engine.query.sense_active_items(<EOL>self.character.name, *self.engine._btt()<EOL>)<EOL>
Iterate over active sense names.
f9037:c6:m1