"""The "I Can't Believe It's Not Tracery" expansion engine, ported from Inform 7. Two halves: * a parser turning a template string into a small AST (literal text, substitutions, ``[one of]`` groups, ``[if]`` blocks), cached per template so that ``[one of]`` sites keep stable identity the way Inform's do; * an evaluator that walks the AST *eagerly, left to right*, mutating shared state as it goes. Eagerness matters. Tags like ``[b lewd]``, ``[m kindness]`` and ``[masc]`` fire during expansion and are read by tokens further right, so a lazy or generator-based evaluator would produce subtly different text. The unit of recursion is Inform's `substituted form of`: a nested pop expands its chosen entry to a *complete string* before the outer pop emits anything. """ from __future__ import annotations import random import re from dataclasses import dataclass from .state import GenState VOWELS = "AEIOUaeiou" MAX_REROLLS = 500 # the Inform original can spin forever; we cap and accept # Marks for what text can't do by itself: break a paragraph or a line, change to italic, bold or roman type, or wait # for a key. Evaluated text carries them to story.py, which acts on them as it prints. MARK = re.compile("\x01(/?[ib]|p|br|await)\x02") AWAIT = "\x01await\x02" SELECTORS = { "purely at random", "at random", "in random order", "cycling", "stopping", "sticky random", "as decreasingly likely outcomes", "then at random", } # --------------------------------------------------------------------------- # AST # --------------------------------------------------------------------------- @dataclass class Text: value: str @dataclass class Sub: verb: str arg: str | None @dataclass class OneOf: alternatives: list[list] selector: str @dataclass class If: branches: list[tuple[str | None, list]] # (condition, body); None == otherwise TOKEN_RE = re.compile(r"\[([^\[\]]*)\]") def _tokenize(template: str) -> list[str | tuple[str]]: """Split into literal strings and 1-tuples holding bracket contents.""" out: list[str | tuple[str]] = [] pos = 0 for m in TOKEN_RE.finditer(template): if m.start() > pos: out.append(template[pos : m.start()]) out.append((m.group(1),)) pos = m.end() if pos < len(template): out.append(template[pos:]) return out def parse_template(template: str) -> list: """Build the AST for one template string.""" tokens = _tokenize(template) nodes, idx = _parse_seq(tokens, 0, stop_at=()) return nodes def _parse_seq(tokens, i: int, stop_at: tuple[str, ...]): """Parse until one of `stop_at` (lowercased token heads) or end of input.""" nodes: list = [] while i < len(tokens): tok = tokens[i] if isinstance(tok, str): nodes.append(Text(tok)) i += 1 continue inner = tok[0] low = inner.strip().lower() if low in stop_at or ( "if" in stop_at and (low.startswith("otherwise") or low == "end if") ): return nodes, i if low == "one of": alts: list[list] = [] i += 1 selector = "purely at random" while True: body, i = _parse_seq(tokens, i, stop_at=("or", *SELECTORS)) alts.append(body) if i >= len(tokens): break # unterminated; tolerate nxt = tokens[i][0].strip().lower() i += 1 if nxt == "or": continue selector = nxt break nodes.append(OneOf(alts, selector)) continue if low.startswith("if "): branches: list[tuple[str | None, list]] = [] cond: str | None = low[3:].strip() i += 1 while True: body, i = _parse_seq(tokens, i, stop_at=("if",)) branches.append((cond, body)) if i >= len(tokens): break # missing [end if]; treat end-of-template as close nxt = tokens[i][0].strip().lower() i += 1 if nxt == "end if": break if nxt.startswith("otherwise if "): cond = nxt[len("otherwise if ") :].strip() continue if nxt == "otherwise": cond = None continue break nodes.append(If(branches)) continue # plain substitution: first word is the verb, remainder the argument parts = inner.strip().split(None, 1) if not parts: i += 1 continue verb = parts[0] arg = parts[1].strip() if len(parts) > 1 else None nodes.append(Sub(verb, arg)) i += 1 return nodes, i # --------------------------------------------------------------------------- # Engine # --------------------------------------------------------------------------- class UnknownSubstitution(KeyError): pass class Engine: def __init__(self, corpus: dict, state: GenState | None = None, seed=None, rng: random.Random | None = None, strict: bool = True): self.lists: dict[str, list[str]] = corpus["lists"] self.themes: dict[str, dict[str, list[str]]] = corpus["themes"] self.stages: dict[str, dict[str, list[str]]] = corpus["stages"] self.state = state if state is not None else GenState() self.rng = rng if rng is not None else random.Random(seed) self.strict = strict self._cache: dict[str, list] = {} self._unknown: set[str] = set() # -- helpers --------------------------------------------------------- def chance(self, n: int, m: int) -> bool: """Inform's `a random chance of N in M succeeds`.""" return self.rng.randint(1, m) <= n def pick(self, seq: list): """Inform's `a random number between 1 and X` then `entry Q`.""" return seq[self.rng.randint(1, len(seq)) - 1] def resolve(self, name: str) -> list[str]: """Resolve a list name, preferring live runtime lists over the corpus. Inform identifiers are case-insensitive, and the corpus is keyed in lower case, but references keep their original case ([pop NPCnames]). """ name = name.strip().lower() s = self.state runtime = { "poplist": s.poplist, "notelist": s.notelist, "socdirect": s.socdirect, "clique": s.clique, "long-clique": s.long_clique, "meaning-store": s.meaning_store, "stage-list": s.stage_list, "temp-stink": s.temp_stink, } if name in runtime: return runtime[name] try: return self.lists[name] except KeyError: raise UnknownSubstitution(f"no such list: {name!r}") from None def evaluate(self, template: str) -> str: """What `say` prints for this template: its text, made left to right, with marks (see MARK) where it breaks a paragraph or a line, changes type, or waits for a key.""" ast = self._cache.get(template) if ast is None: ast = parse_template(template) self._cache[template] = ast return self._eval(ast) def expand(self, template: str) -> str: """Inform's `substituted form of`: the text built whole before any of it is printed. `pop` does this to the entry it picks (sourceCode.txt:370), and the source does it itself in a few places. See `built`.""" return built(self.evaluate(template)) def _eval(self, nodes: list) -> str: out: list[str] = [] for node in nodes: if isinstance(node, Text): out.append(node.value) elif isinstance(node, Sub): out.append(self._dispatch(node.verb, node.arg)) elif isinstance(node, OneOf): out.append(self._eval(self._choose(node))) elif isinstance(node, If): for cond, body in node.branches: if cond is None or self.eval_condition(cond): out.append(self._eval(body)) break return "".join(out) def _choose(self, node: OneOf) -> list: alts = node.alternatives if len(alts) == 1: return alts[0] sel = node.selector mem = self.state.oneof_memory key = id(node) if sel == "purely at random": return self.pick(alts) if sel == "at random": # random, but never the same as the immediately preceding choice last = mem.get(key) if len(alts) > 1: while True: idx = self.rng.randint(0, len(alts) - 1) if idx != last: break else: idx = 0 mem[key] = idx return alts[idx] if sel == "in random order": deck = mem.get(key) if not deck: deck = list(range(len(alts))) self.rng.shuffle(deck) idx = deck.pop() mem[key] = deck return alts[idx] if sel == "cycling": idx = mem.get(key, -1) + 1 idx %= len(alts) mem[key] = idx return alts[idx] if sel == "stopping": idx = min(mem.get(key, -1) + 1, len(alts) - 1) mem[key] = idx return alts[idx] if sel == "sticky random": if key not in mem: mem[key] = self.rng.randint(0, len(alts) - 1) return alts[mem[key]] if sel == "as decreasingly likely outcomes": weights = [len(alts) - i for i in range(len(alts))] return self.rng.choices(alts, weights=weights, k=1)[0] if sel == "then at random": n = mem.get(key, 0) mem[key] = n + 1 return alts[n] if n < len(alts) else self.pick(alts) return self.pick(alts) def eval_condition(self, cond: str) -> bool: s = self.state c = cond.strip().lower() m = re.match(r"a random chance of (\d+) in (\d+) succeeds", c) if m: return self.chance(int(m.group(1)), int(m.group(2))) if c == "lewdness-on is true": return s.lewdness_on if c == "lewdness is assured": return "lewd" in s.themelist if c == "scentlocale obtains": return bool(s.scent_sourcing) if c == "scented-trouble is false": return not s.scented_trouble if c == "scented-trouble is true": return s.scented_trouble if c == "a-to-the is true": return s.a_to_the if c == "delays occur": return bool(s.delaylist) if self.strict: raise UnknownSubstitution(f"unknown condition: {cond!r}") return False # -- the [*a] article machinery -------------------------------------- def _article_prefix(self, z: str, remove_on_vowel: bool = True) -> str: """Resolve a pending [*a] against the text just produced. `[*a]` prints a bare "a" and flags `a_coming`; the next pop records its own depth, and on completion inspects the first character of its result to emit "n " or " ". See sourceCode.txt:341 and :357. `remove_on_vowel=False` reproduces a bug in `noreppop` (sourceCode.txt:524), where the vowel branch neglects to clear the recorded depth, so a later pop at the same depth can pick up a stray prefix. Kept because the goal is a faithful copy. """ s = self.state if s.depthgauge in s.a_depths and len(z) > 0: if z[0] in VOWELS: if remove_on_vowel and s.depthgauge in s.a_depths: s.a_depths.remove(s.depthgauge) return "n " if s.depthgauge in s.a_depths: s.a_depths.remove(s.depthgauge) return " " return "" def _enter_pop(self) -> None: s = self.state s.depthgauge += 1 if s.a_coming: s.a_depths.append(s.depthgauge) s.a_coming = False # -- the pop family --------------------------------------------------- def _pop_generic(self, entries: list[str], transform=None) -> str: if not entries: return "***ERROR: trying to pop from an empty list.***" self._enter_pop() z = self.expand(self.pick(entries)) pauses = AWAIT * z.count(AWAIT) # a wait while the entry was being built came before any of it z = z.replace(AWAIT, "") if transform: z = transform(z) prefix = self._article_prefix(z) self.state.depthgauge -= 1 return pauses + prefix + z def sub_pop(self, entries): return self._pop_generic(entries) def sub_uppop(self, entries): return self._pop_generic(entries, lambda z: z[:1].upper() + z[1:]) def sub_downpop(self, entries): return self._pop_generic(entries, lambda z: z[:1].lower() + z[1:]) def sub_titlepop(self, entries): return self._pop_generic(entries, title_case) def sub_alldownpop(self, entries): return self._pop_generic(entries, str.lower) def sub_noreppop(self, entries) -> str: """pop, rerolling while the result is already in poplist.""" s = self.state if not entries: return "***ERROR: trying to noreppop from an empty list.***" self._enter_pop() z = self.expand(self.pick(entries)) for _ in range(MAX_REROLLS): if z not in s.poplist: break z = self.expand(self.pick(entries)) s.poplist.append(z) prefix = self._article_prefix(z, remove_on_vowel=False) s.depthgauge -= 1 return prefix + z def sub_friendpop(self, entries) -> str: """NPC names, with a 1-in-5 chance of reusing an established character.""" s = self.state if not entries: return "***ERROR: trying to friendpop from an empty list.***" self._enter_pop() if len(s.long_clique) > 1 and self.chance(1, 5): z = self.pick(s.long_clique) else: z = self.expand(self.pick(entries)) prefix = self._article_prefix(z) s.notalone = True s.clique.append(z) if self.play_mode == "standard-mode" and z not in s.long_clique: s.long_clique.append(z) s.socdirect.append(z) s.depthgauge -= 1 return prefix + z def sub_assoc(self, entries) -> str: """pop, and additionally store the literal result as a resonance.""" s = self.state if not entries: return "***ERROR: trying to pop from an empty list.***" self._enter_pop() z = self.expand(self.pick(entries)) sub_z = z if s.depthgauge in s.a_depths and len(z) > 0: sub_z = ("n " if z[0] in VOWELS else " ") + z s.a_depths.remove(s.depthgauge) s.depthgauge -= 1 if z[:1].isspace(): z = z[1:] if z: s.socdirect.append(z) return sub_z # -- scent notes ------------------------------------------------------ def _off_brand(self) -> bool: if self.state.scent_themed: return False if self.chance(1, 3): return False return True def _psychogeographize(self, scent: str) -> None: s = self.state if s.stage_toggle: s.scent_sourcing.append((scent, s.current_scent_stage)) s.stage_toggle = False def sub_scentpop(self, entries) -> str: s = self.state if not entries: return "***ERROR: empty scentpop.***" s.scent_themed = False z = self.expand(self.pick(entries)) for _ in range(MAX_REROLLS): if not (z in s.poplist or self._off_brand()): break if z in s.notelist: s.notelist.remove(z) s.stage_toggle = False z = self.expand(self.pick(entries)) self._psychogeographize(z) s.stage_toggle = False s.poplist.append(z) s.notelist.append(z) return self.sub_thematic() + z def sub_notepop(self, entries) -> str: s = self.state if not entries: return "***ERROR: empty notepop.***" z = self.expand(self.pick(entries)) for _ in range(MAX_REROLLS): if z not in s.poplist: break if z in s.notelist: s.notelist.remove(z) z = self.expand(self.pick(entries)) self._psychogeographize(z) s.stage_toggle = False s.poplist.append(z) s.notelist.append(z) return z # -- themes ----------------------------------------------------------- @property def play_mode(self) -> str: return getattr(self, "_play_mode", "standard-mode") @play_mode.setter def play_mode(self, value: str) -> None: self._play_mode = value def theme_prop(self, theme: str, prop: str) -> list[str]: return self.themes[theme][prop] def _random_theme_prop(self, prop: str) -> list[str]: theme = self.pick(self.state.themelist) return self.theme_prop(theme, prop) def _first_theme_prop(self, prop: str) -> list[str]: return self.theme_prop(self.state.themelist[0], prop) def sub_thematic(self) -> str: if not self.chance(1, 2) or not self.state.themelist: return "" twist = self._random_theme_prop("twist") return self.sub_noreppop(twist) + " " def sub_composes(self) -> str: return self.sub_pop(self._random_theme_prop("composite")) def sub_phantasm(self) -> str: return self.sub_pop(self._random_theme_prop("phantpre")) def sub_themed_res_adj(self) -> str: return self.sub_pop(self._random_theme_prop("resonance-mods")) def sub_drama_scene(self) -> str: self.rng.shuffle(self.state.themelist) return self.sub_pop(self._first_theme_prop("scenelist")) def sub_wearfeels(self) -> str: if self.chance(1, 4): return self.sub_noreppop(self.resolve("all-feelings")) self.rng.shuffle(self.state.themelist) return self.sub_noreppop(self._first_theme_prop("wear-feelings")) def sub_aproposadj(self) -> str: z = list(self.lists["multiadjs"]) for theme in self.state.themelist: z.extend(self.theme_prop(theme, "twist")) return self.sub_pop(z) def sub_aproposnoun(self) -> str: z = list(self.lists["multinotes"]) for theme in self.state.themelist: z.extend(self.theme_prop(theme, "phantpre")) return self.sub_pop(z) # -- seasons ---------------------------------------------------------- def sub_theseason(self) -> str: s = self.state if s.current_season == "none": return self.sub_pop(self.resolve("seasons")) return self.sub_pop([s.current_season]) def sub_upseason(self) -> str: s = self.state if s.current_season == "none": return self.sub_uppop(self.resolve("seasons")) return self.sub_uppop([s.current_season]) def _set_season(self, season: str, things: str) -> str: if self.state.current_season == "none": self.state.current_season = f"{season}[m {things}]" return "" def sub_weathersnip(self) -> str: s = self.state if s.current_season == "none": s.current_season = self.pick(["winter", "autumn", "spring", "summer"]) base = s.current_season.split("[")[0] table = { "spring": ("springweather", "springthings"), "summer": ("summerweather", "summerthings"), "autumn": ("fallweather", "autumnthings"), "winter": ("winterweather", "winterthings"), } if base not in table: return "" weather, things = table[base] out = self.sub_pop(self.resolve(weather)) self.state.assoc_list.append(things) return out def sub_aproposmonth(self) -> str: base = self.state.current_season.split("[")[0] months = { "spring": ["March", "April", "May"], "summer": ["June", "July", "August"], "autumn": ["September", "October", "November"], "winter": ["December", "January", "February"], } if base in months: return self.pick(months[base]) return self.sub_pop(self.resolve("months")) def sub_inclement_boat(self) -> str: base = self.state.current_season.split("[")[0] if base == "summer": return self.pick(["the crowds of tourists", "the heat", "the unrelenting sun"]) if base == "winter": return self.pick(["biting winds", "the snow", "the cold"]) return self.pick(["a persistent drizzle", "the chill wind", "heavy mist"]) # -- scent sourcing --------------------------------------------------- def sub_scent_place(self) -> str: s = self.state if not s.scent_sourcing: return "" scent, stage = self.pick(s.scent_sourcing) s.temp_stink = [scent] return self.sub_pop(self.stages[stage]["short-placedesc"]) def _say_list(self, entries: list[str]) -> str: """Inform's rendering of a list value: 'a, b and c'.""" parts = [self.expand(e) for e in entries] if not parts: return "" if len(parts) == 1: return parts[0] return ", ".join(parts[:-1]) + " and " + parts[-1] # -- dispatch --------------------------------------------------------- def _dispatch(self, verb: str, arg: str | None) -> str: handler = _TABLE.get((verb, arg is not None)) if handler is None: handler = _TABLE.get((verb.lower(), arg is not None)) if handler is None and arg is None: # A bare `[listname]`: Inform prints the list value itself. The # three places this happens (`[2syll]`, `[socialhappenings]`, # `[controversalpubs]`) all name single-entry lists, so this is # equivalent to a pop, but implement the general list format. try: entries = self.resolve(verb.lower()) except UnknownSubstitution: entries = None if entries is not None: return self._say_list(entries) if handler is None: self._unknown.add(f"{verb}{' X' if arg else ''}") if self.strict: raise UnknownSubstitution(f"[{verb}{' ' + arg if arg else ''}]") return "" return handler(self, arg) def built(text: str) -> str: """Evaluated text as Inform builds it for `substituted form of`: in a scratch buffer, which keeps its own paragraph state and holds only characters. * A paragraph break leaves a blank line only after text in the same buffer; at the start it's a line break. So the `[p]` that opens some of the "first perfume" memories (sourceCode.txt:5630) starts a new line, no more. * Line breaks become newline characters, and italic, bold and roman type are lost. * A wait for a key happens while the text is being built, before any of it is printed, so the pause goes to the front. So the `[await]` in the escape memory (sourceCode.txt:5363) waits before the memory, not halfway. """ pauses = text.count(AWAIT) out: list[str] = [] started = False # Inform's say__p, for the buffer at = 0 for mark in MARK.finditer(text): if mark.start() > at: out.append(text[at : mark.start()]) started = True at = mark.end() if mark.group(1) == "p": out.append("\n\n" if started else "\n") started = False elif mark.group(1) == "br": out.append("\n") out.append(text[at:]) return AWAIT * pauses + "".join(out) def title_case(text: str) -> str: """Inform's title case: capitalise each word, leave the rest alone. Unlike ``str.title()`` this does not lowercase the tail of a word, so "Buddha's hand" and "d'Arcy" survive intact. """ return re.sub(r"(^|\s)(\w)", lambda m: m.group(1) + m.group(2).upper(), text) def sentence_case(text: str) -> str: return text[:1].upper() + text[1:] if text else text # --------------------------------------------------------------------------- # Phrase table # --------------------------------------------------------------------------- # Keys are (verb, takes_argument). Values are callables (engine, arg) -> str. def _list_verb(method_name): def call(eng: Engine, arg: str | None) -> str: return getattr(eng, method_name)(eng.resolve(arg)) return call def _nullary(fn): return lambda eng, arg: fn(eng) def _const(text): return lambda eng, arg: text def _set(**kwargs): def call(eng: Engine, arg: str | None) -> str: for k, v in kwargs.items(): setattr(eng.state, k, v) return "" return call def _sub_a(eng: Engine, arg=None) -> str: eng.state.a_coming = True return "a" def _sub_s(eng: Engine, arg=None) -> str: s = eng.state out = "s" if (not s.plural_reckoned and s.sing_last == 2) else "" s.plural_reckoned = True s.sing_last = 0 return out def _plural_ending(plural: str, singular: str = "", both_zero: bool = False): """Build one of the `[*es]` / `[*ies]` / `[*f]` family.""" def call(eng: Engine, arg=None) -> str: s = eng.state out = "" if s.sing_last == 2: out = plural elif s.sing_last in (0, 1) or both_zero: out = singular s.plural_reckoned = True return out return call def _star_s(eng: Engine, arg=None) -> str: s = eng.state out = "s" if s.sing_last in (0, 2) else "" s.plural_reckoned = True s.sing_last = 0 return out def _anti_s(eng: Engine, arg=None) -> str: s = eng.state out = "s" if s.sing_last != 2 else "" s.plural_reckoned = True s.sing_last = 0 return out def _star_man(eng: Engine, arg=None) -> str: s = eng.state stem = eng.pick(["wo", ""]) out = "" if s.sing_last in (0, 1): out = stem + "man" elif s.sing_last == 2: out = stem + "men" s.plural_reckoned = True return out def _gender_set(value: int, fuzzy: bool = False): def call(eng: Engine, arg=None) -> str: s = eng.state if s.npc_gender != 0: return "" if not fuzzy: s.npc_gender = value return "" if eng.chance(9, 10): s.npc_gender = value else: others = [g for g in (1, 2, 3) if g != value] s.npc_gender = eng.pick(others) return "" return call def _gender_neut(eng: Engine, arg=None) -> str: """`[neut]` as a gender tag (sourceCode.txt:3314). The source defines `To say neut` twice; the other (sourceCode.txt:677) zeroes `sing-last`. Every one of the 20 corpus uses tags a unisex forename, so the gender reading is the operative one. We also zero sing-last, which is what the other definition would have done and is inert on a name. """ s = eng.state if s.npc_gender == 0: s.npc_gender = eng.rng.randint(1, 3) s.sing_last = 0 return "" def _pronoun(fem: str, masc: str, neutral: str): def call(eng: Engine, arg=None) -> str: s = eng.state if s.npc_gender == 0: s.npc_gender = eng.rng.randint(1, 3) return {1: neutral, 2: fem, 3: masc}[s.npc_gender] return call def _npc_friend(upper: bool): def call(eng: Engine, arg=None) -> str: s = eng.state if eng.play_mode == "reflective-mode" and eng.chance(3, 4): if upper: out = eng.sub_uppop(eng.resolve("bullshitlist")) s.onefriend = True return out if not s.onefriend: s.onefriend = True out = _sub_a(eng) else: out = eng.expand("[one of]your[or][*their][purely at random] ") return out + eng.sub_pop(eng.resolve("brief-friends")) return eng.sub_friendpop(eng.resolve("npcnames")) return call def _dject(eng: Engine, arg: str) -> str: s = eng.state if eng.chance(3, 10) and not s.noadj: return eng.expand(f"[noreppop {arg}] ") if eng.chance(1, 7) and not s.noadj: return eng.sub_noreppop(eng.resolve("manyadjs")) + " " return "" def _djectr(eng: Engine, arg=None) -> str: if eng.chance(1, 6) and not eng.state.noadj: return eng.sub_noreppop(eng.resolve("manyadjs")) + " " return "" def _frag(eng: Engine, arg=None) -> str: s = eng.state if s.fraglist and eng.chance(1, 2): name = eng.pick(s.fraglist) s.fraglist.remove(name) return " (" + eng.sub_pop(eng.resolve("fragleads")) + eng.sub_pop(eng.resolve(name)) + ")" return "" def _release_delay(eng: Engine, arg=None) -> str: s = eng.state if not s.delaylist: return "" name = eng.pick(s.delaylist) out = eng.sub_pop(eng.resolve(name)) s.commacetic = True return out def _comma(eng: Engine, arg=None) -> str: s = eng.state if s.commacetic: s.commacetic = False return "," return "" def _the(eng: Engine, arg=None) -> str: s = eng.state if s.the_allowed: return "the " s.the_allowed = True return "" def _godpre(eng: Engine, arg=None) -> str: if eng.chance(1, 3): eng.state.godtoggle = 1 return eng.sub_pop(eng.resolve("god-prefix")) + " " return "" def _godsuff(eng: Engine, arg=None) -> str: s = eng.state out = "" if s.godtoggle == 0 and eng.chance(1, 2): out = " " + eng.sub_pop(eng.resolve("god-suffix")) s.godtoggle = 0 return out def _npctrouble(eng: Engine, arg=None) -> str: out = eng.sub_pop(eng.resolve("troublenpcs")) if eng.chance(1, 4): out += eng.expand( " (who always wore [one of]this scent[or][pop notelist] scents[purely at random])" ) eng.state.scented_trouble = True return out def _altstudent(eng: Engine, arg=None) -> str: if "lewd" in eng.state.themelist: return eng.expand("[one of]suitor[or]lover[purely at random][lover]") return eng.expand("[one of]student[or]protégé[purely at random][nolewds][m mentorship]") def _altmentor(eng: Engine, arg=None) -> str: if "lewd" in eng.state.themelist: return " former lover" return eng.expand("n old mentor[m mentorship][nolewds]") def _lover(eng: Engine, arg=None) -> str: eng.state.assoc_list.extend(["romance", "lust"]) eng.state.fraglist.append("loverfrags") return "" def _paramouring(eng: Engine, arg=None) -> str: if not eng.state.bff: return eng.expand( "[had-once][one of]an impossibly[or]a devastatingly[or]a transcendently" "[purely at random] [one of]cool[or]beautiful[or]stylish[or]grown-up[or]" "sophisticated[or]tough[or]chill[or]accomplished[purely at random] " "[one of]girlfriend[or]boyfriend[or]partner[purely at random]" ) return eng.sub_noreppop(eng.resolve("inaprop-coolness")) def _othergirlpop(eng: Engine, arg=None) -> str: if eng.state.wearadjs_said: return eng.sub_pop(eng.resolve("othergirls")) return ", " + eng.sub_wearfeels() + " and " + eng.sub_wearfeels() def _noblegender(eng: Engine, arg=None) -> str: g = eng.state.npc_gender if g == 3: return eng.pick(["King", "Emperor", "Duke", "Prince", "Lord"]) if g == 2: return eng.pick(["Queen", "Empress", "Duchess", "Princess", "Lady"]) return eng.pick(["King", "Queen", "Prince", "Duke", "Lord"]) def _toggle_once(field: str, word: str): """`[had-once]` / `[was-once]`: emit a word at most once per perfume.""" def call(eng: Engine, arg=None) -> str: if not getattr(eng.state, field): setattr(eng.state, field, True) return word return "" return call def _is_are(eng: Engine, arg=None) -> str: s = eng.state out = "are" if s.sing_last == 2 else "is" s.sing_last = 0 s.plural_reckoned = True return out def _flipsing(eng: Engine, arg=None) -> str: s = eng.state if s.sing_last == 2: s.sing_last = 0 s.sing_flip = True return "" def _flipoff(eng: Engine, arg=None) -> str: s = eng.state if s.sing_flip: s.sing_last = 2 s.sing_flip = False return "" def _add_to(field: str): return lambda eng, arg: (getattr(eng.state, field).append(arg), "")[1] def _brand(eng: Engine, arg: str) -> str: if arg in eng.state.themelist: eng.state.scent_themed = True return "" def _onstage(eng: Engine, arg: str) -> str: eng.state.stage_toggle = True eng.state.current_scent_stage = arg return "" _TABLE: dict[tuple[str, bool], object] = { # --- pops (take a list name) --------------------------------------- ("pop", True): _list_verb("sub_pop"), ("uppop", True): _list_verb("sub_uppop"), ("downpop", True): _list_verb("sub_downpop"), ("titlepop", True): _list_verb("sub_titlepop"), ("alldownpop", True): _list_verb("sub_alldownpop"), ("noreppop", True): _list_verb("sub_noreppop"), ("scentpop", True): _list_verb("sub_scentpop"), ("notepop", True): _list_verb("sub_notepop"), ("friendpop", True): _list_verb("sub_friendpop"), ("assoc", True): _list_verb("sub_assoc"), # --- resonance / fragment bookkeeping ------------------------------ ("m", True): _add_to("assoc_list"), ("addfrag", True): _add_to("fraglist"), ("delay", True): _add_to("delaylist"), ("b", True): _brand, ("onstage", True): _onstage, ("dject", True): _dject, ("djectr", False): _djectr, ("expandable", False): _set(expandable_assoc=True), ("assoc-holder", False): lambda eng, arg: eng.state.assoc_holder, # --- articles ------------------------------------------------------- ("*a", False): _sub_a, ("a*", False): _sub_a, ("athe", False): _set(a_to_the=True), ("thetoa", False): _set(a_to_the=False), ("cancel-the", False): _set(the_allowed=False), ("restore-the", False): _set(the_allowed=True), ("*the", False): _the, # --- number agreement ---------------------------------------------- ("sing", False): _set(sing_last=1), ("plure", False): lambda eng, arg: ( setattr(eng.state, "sing_last", 2), setattr(eng.state, "plural_reckoned", False), "", )[2], ("reckon", False): _set(plural_reckoned=True), ("flipsing", False): _flipsing, ("flipoff", False): _flipoff, ("is-are", False): _is_are, ("s", False): _sub_s, ("*s", False): _star_s, ("anti-s", False): _anti_s, ("*es", False): _plural_ending("es"), ("*ies", False): _plural_ending("ies", "y"), ("*f", False): _plural_ending("ves", "f"), ("*en", False): _plural_ending("en"), ("*fe", False): _plural_ending("ves", "fe"), ("*ices", False): _plural_ending("ices", "ex"), ("*ix", False): _plural_ending("ices", "ix"), ("*man", False): _star_man, # --- gender ---------------------------------------------------------- ("masc", False): _gender_set(3, fuzzy=True), ("fem", False): _gender_set(2, fuzzy=True), ("hardmasc", False): _gender_set(3), ("hardfem", False): _gender_set(2), ("hardnb", False): _gender_set(1), ("neut", False): _gender_neut, ("*they", False): _pronoun("she", "he", "they"), ("*them", False): _pronoun("her", "him", "them"), ("*their", False): _pronoun("her", "his", "their"), ("*theirs", False): _pronoun("hers", "his", "theirs"), ("noblegender", False): _noblegender, # --- NPCs ------------------------------------------------------------- ("npc-friend", False): _npc_friend(upper=False), ("Npc-friend", False): _npc_friend(upper=True), ("npctrouble", False): _npctrouble, ("altstudent", False): _altstudent, ("altmentor", False): _altmentor, ("lover", False): _lover, ("paramouring", False): _paramouring, ("othergirlpop", False): _othergirlpop, ("bff-toggle", False): _set(bff=True), ("you-switch", False): _set(yousaid=True), ("you-cond", False): lambda eng, arg: "" if eng.state.yousaid else "you ", ("had-once", False): _toggle_once("had_toggle", "had "), ("was-once", False): _toggle_once("was_toggle", "was "), # --- themes ----------------------------------------------------------- ("thematic", False): _nullary(Engine.sub_thematic), ("composes", False): _nullary(Engine.sub_composes), ("phantasm", False): _nullary(Engine.sub_phantasm), ("themed-res-adj", False): _nullary(Engine.sub_themed_res_adj), ("drama-scene", False): _nullary(Engine.sub_drama_scene), ("wearfeels", False): _nullary(Engine.sub_wearfeels), ("wear-switch", False): _set(wearadjs_said=True), ("aproposadj", False): _nullary(Engine.sub_aproposadj), ("aproposnoun", False): _nullary(Engine.sub_aproposnoun), ("t-ikonage", False): lambda eng, arg: eng.sub_pop(eng._first_theme_prop("t-ikons")), ("olda-themes", False): lambda eng, arg: eng.sub_pop(eng._first_theme_prop("cool-quals")), ("bottle-cladding", False): lambda eng, arg: eng.sub_pop(eng._first_theme_prop("bottleclads")), ("theme-classics", False): lambda eng, arg: eng.sub_pop(eng._first_theme_prop("classical-subjs")), ("randbottle", False): lambda eng, arg: eng.sub_pop(eng._first_theme_prop("bottlemats")), ("g-randbottle", False): lambda eng, arg: eng.sub_pop(eng._first_theme_prop("g-bottlemats")), # --- seasons ----------------------------------------------------------- ("theseason", False): _nullary(Engine.sub_theseason), ("upseason", False): _nullary(Engine.sub_upseason), ("summer-season", False): lambda eng, arg: eng._set_season("summer", "summerthings"), ("winter-season", False): lambda eng, arg: eng._set_season("winter", "winterthings"), ("spring-season", False): lambda eng, arg: eng._set_season("spring", "springthings"), ("autumn-season", False): lambda eng, arg: eng._set_season("autumn", "autumnthings"), ("weathersnip", False): _nullary(Engine.sub_weathersnip), ("aproposmonth", False): _nullary(Engine.sub_aproposmonth), ("inclement-boat", False): _nullary(Engine.sub_inclement_boat), # --- places ------------------------------------------------------------- ("scent-place", False): _nullary(Engine.sub_scent_place), ("scent-locale", False): lambda eng, arg: eng.expand( "[if scentlocale obtains][pop scentpl-variations][otherwise][assoc fakebuilds][end if]" ), ("roomfrag", False): lambda eng, arg: (eng.state.fraglist.append("roomfrags"), "")[1], # --- fragments / deferred clauses --------------------------------------- ("frag", False): _frag, ("finalclause", False): lambda eng, arg: ( ", " + _release_delay(eng) if eng.state.delaylist else "" ), ("release-delay", False): _release_delay, ("pushcomma", False): _set(commacetic=True), ("comma", False): _comma, ("suppresscomma", False): _set(nocomma=True), ("recomma", False): _set(nocomma=False), ("and-vs-comma", False): lambda eng, arg: " and" if eng.state.nocomma else ",", ("cond-comma", False): lambda eng, arg: "" if eng.state.nocomma else ",", ("catchcomma", False): lambda eng, arg: "," if eng.state.nocomma else "", # --- misc content toggles ------------------------------------------------ ("nolewds", False): _set(lewdness_on=False), ("cutadj", False): _set(noadj=True), ("backadj", False): _set(noadj=False), ("prob-dd", False): lambda eng, arg: eng.sub_pop(eng.resolve("probsynonyms")) + " ", ("gubadj", False): lambda eng, arg: eng.expand( "[one of][pop histnames] [or][titlepop gubberadjs] [or][purely at random]" ), ("movements", False): lambda eng, arg: eng.expand( "[pop movementprefixes][pop movementsuffixes]" ), ("dramaname", False): lambda eng, arg: eng.expand( "[pop dramafores][one of][pop dramamids][or][purely at random][pop dramaafts]" ), ("godpre", False): _godpre, ("godsuff", False): _godsuff, # --- pseudo-Greek name endings ------------------------------------------- ("os", False): lambda eng, arg: eng.pick(["os", "os", "a", "e"]), ("ios", False): lambda eng, arg: eng.pick(["ios", "aia"]), ("ia", False): lambda eng, arg: eng.pick(["es", "ia"]), ("as", False): lambda eng, arg: eng.pick(["as", "as", "a", "e"]), ("er", False): lambda eng, arg: eng.pick(["er", "re"]), ("n", False): lambda eng, arg: eng.pick(["n", "nia"]), ("ne", False): lambda eng, arg: eng.pick(["n", "ne"]), ("eo", False): lambda eng, arg: eng.pick(["eo", "ea"]), # --- literal text / formatting ------------------------------------------- ("'", False): _const("'"), ("bracket", False): _const("["), ("close bracket", False): _const("]"), ("quotation mark", False): _const('"'), ("i", False): _const("\x01i\x02"), ("/i", False): _const("\x01/i\x02"), ("b", False): _const("\x01b\x02"), ("/b", False): _const("\x01/b\x02"), ("p", False): _const("\x01p\x02"), ("br", False): _const("\x01br\x02"), ("ob", False): _const("["), ("cb", False): _const("]"), ("paragraph break", False): _const("\x01p\x02"), ("line break", False): _const("\x01br\x02"), ("no line break", False): _const(""), ("italic type", False): _const("\x01i\x02"), ("roman type", False): _const("\x01/i\x02"), ("bold type", False): _const("\x01b\x02"), # `[await]` waits for a key (sourceCode.txt:2407); the mark tells story.py where. See `built` for when. ("await", False): _const(AWAIT), ("wait for any key", False): _const(""), }