class_name Roller extends RefCounted ## Rolls a table and follows its pipes and inline references, producing a ## result tree. ## ## Each node is a Dictionary: ## table: RollTable, value: int (die value), index: int, entry: TableEntry, ## summary: String (the entry text with [[refs]] and {vars} expanded, as ## BBCode with TextExpander's internal [url] markers), ## children: Array of nodes (inline reference rolls first, marked ## "inline": true, then pipe rolls in pipe order), ## and "stop": String when the chain couldn't continue (its summary then ## explains why). ## Logic-card keys (docs/LOGIC.md), present only when they apply: ## kind: "choice" | "loop" | "sheet" | "router" (plain roll nodes have no kind) ## case: int, on a router node: the index of the case that matched ## effects: Array of {"text": String, "error": true?}, the effect log ## answer: the player's answer on a number/text choice (int or String) ## picked: true when the player picked a pick option; random: true for Random ## option: on a pick node for a dynamic option (options_from), its label ## passes: int, on a loop's header node ("Repeated N times"); its children ## are one node per pass ("pass": i, "value": i) and then the Afterwards ## node ("after": true) ## limit: true on the "Stopped after 10,000 actions" stop node ## cancelled: true on the "Cancelled" stop node ## ## The roller is a coroutine with an explicit work stack: pipes and loop passes ## never recurse in GDScript, so chains of thousands of steps are fine. Only ## inline [[references]] nest (at most RollContext.max_depth deep). ## ## roll_async() is the main entry point. It awaits ctx.prompt for choice cards ## and fills in ctx.root as it goes. roll() is the plain form: it never waits ## (choices get the headless answers) and returns the tree directly. ## Deepest level inline references can nest (matches RollContext). const MAX_DEPTH := RollContext.DEFAULT_MAX_DEPTH ## Most actions one top-level roll may take (matches RollContext). const MAX_ACTIONS := RollContext.DEFAULT_MAX_ACTIONS const CANCELLED := "Cancelled" const NO_CASE := "No case matched" const NO_OPTIONS := "No options available" enum { OP_ROLL, OP_PIPE, OP_LOOP } ## A RollContext wired to this board: it resolves [[names]] against the board's ## tables and rolls inline references through the roller. `persistent` is the ## collection's persistent variables (name without "@" -> {value, source}), ## shared, not copied. `decks` maps table id to DeckState for card-mode tables, ## also shared. Set ctx.prompt to ask the player on choice cards. static func new_context(board: TowerBoard, rng: RandomNumberGenerator, persistent: Dictionary = {}, decks: Dictionary = {}) -> RollContext: var ctx := RollContext.new(persistent, rng) ctx.max_depth = MAX_DEPTH ctx.board = board ctx.set_meta("decks", decks) # A weak reference, so the context doesn't keep itself alive through its hooks. var wr: WeakRef = weakref(ctx) ctx.resolve_table = func(name_or_id: String) -> String: return resolve(board, name_or_id) ctx.roll_table = func(id: String, depth: int) -> Dictionary: var c: RollContext = wr.get_ref() return {} if c == null else _chain_sync(board, id, depth, c) ctx.roll_table_async = func(id: String, depth: int) -> Dictionary: var c: RollContext = wr.get_ref() if c == null: return {} return await _chain(board, id, depth, c) return ctx ## Table id for a [[reference]]: an exact id, or a name matched ## case-insensitively without BBCode. "" if there's no such table. static func resolve(board: TowerBoard, name_or_id: String) -> String: var key := name_or_id.strip_edges() if board.get_table(key) != null: return key var want := RollContext.normalize_name(key) if want == "": return "" for t in board.tables: if RollContext.normalize_name(t.name) == want: return t.id return "" ## Rolls `table_id` and everything its pipes and references lead to, without ## ever waiting: choice cards get the headless answers (Random, min, ""). ## `decks` maps table id to DeckState for card-mode tables; missing decks are ## created in it on demand. `ctx` carries the variables for the whole chain. ## Without one, a fresh context (no persistent variables) is made around ## `decks`; a context from new_context() brings its own decks and `decks` is ## then ignored. Extra node keys: "save_as" (on nodes reached through a pipe ## that saves), "reshuffled" (card deck was refilled for this draw), "inline" ## (rolled by a [[reference]] in the parent's text), and the logic-card keys ## listed at the top of this file. static func roll(board: TowerBoard, table_id: String, rng: RandomNumberGenerator, depth: int = 0, decks: Dictionary = {}, ctx: RollContext = null) -> Dictionary: if ctx == null: ctx = new_context(board, rng, {}, decks) elif not ctx.has_meta("decks"): ctx.set_meta("decks", decks) var was := ctx.no_prompt ctx.no_prompt = true var r: Variant = Callable(Roller, "roll_async").call(board, table_id, ctx, depth) ctx.no_prompt = was return r if r is Dictionary else {} ## The coroutine roll: `await Roller.roll_async(board, id, ctx)`. Choice cards ## await ctx.prompt (see ask()); with no prompt hook it finishes without ## waiting a frame. ctx.root holds the tree so far while it runs (see ## progress()). Resets the action counter, ctx.halted and ctx.root unless it's ## called from inside a running roll. static func roll_async(board: TowerBoard, table_id: String, ctx: RollContext, depth: int = 0) -> Dictionary: if ctx.board == null: ctx.board = board if not ctx.has_meta("decks"): ctx.set_meta("decks", {}) if ctx.running == 0: ctx.actions = 0 ctx.halted = "" ctx.root = {} ctx.forget_declarations() return await _chain(board, table_id, depth, ctx) ## The steps of the tree built so far (ctx.root), e.g. while a prompt is open. static func progress(ctx: RollContext) -> Array: return flatten(ctx.root, []) ## "Stopped after 10,000 actions". static func limit_text(n: int = MAX_ACTIONS) -> String: var s := str(n) var out := "" while s.length() > 3: out = "," + s.substr(s.length() - 3) + out s = s.substr(0, s.length() - 3) return "Stopped after %s actions" % (s + out) static func _chain_sync(board: TowerBoard, id: String, depth: int, ctx: RollContext) -> Dictionary: var was := ctx.no_prompt ctx.no_prompt = true var r: Variant = Callable(Roller, "_chain").call(board, id, depth, ctx) ctx.no_prompt = was return r if r is Dictionary else {} ## Runs one chain (a top-level roll, or one inline reference) on its own work ## stack. Returns its first node, or {} when the table is missing or is a ## variable card. static func _chain(board: TowerBoard, table_id: String, depth: int, ctx: RollContext) -> Dictionary: ctx.running += 1 var holder := {"children": []} var stack: Array = [{"op": OP_ROLL, "id": table_id, "parent": holder, "save": "", "depth": depth, "top": ctx.running == 1}] while not stack.is_empty() and ctx.halted == "": var f: Dictionary = stack.pop_back() match int(f["op"]): OP_ROLL: await _do_roll(board, f, ctx, stack) OP_PIPE: _do_pipe(board, f, ctx, stack) OP_LOOP: await _do_loop(f, ctx, stack) ctx.running -= 1 var kids: Array = holder["children"] return kids[0] if not kids.is_empty() else {} static func _stop(t: RollTable, why: String, extra: Dictionary = {}) -> Dictionary: var node := {"table": t, "stop": why, "summary": why, "children": []} node.merge(extra, true) return node static func _attach(f: Dictionary, node: Dictionary, ctx: RollContext) -> void: if str(f.get("save", "")) != "": node["save_as"] = f["save"] (f["parent"]["children"] as Array).append(node) if f.get("top", false): ctx.root = node ## Counts one action, or stops the roll at the limit (attaching the marker ## under `f.parent`). Returns false when the roll has to stop. static func _take_action(f: Dictionary, t: RollTable, ctx: RollContext) -> bool: if ctx.actions >= ctx.max_actions: var msg := limit_text(ctx.max_actions) _attach(f, _stop(t, msg, {"limit": true}), ctx) ctx.halted = msg return false ctx.actions += 1 return true static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: Array) -> void: var t := board.get_table(str(f["id"])) if t == null or t.kind == RollTable.KIND_VARIABLE: return if not _take_action(f, t, ctx): return if t.entries.is_empty(): _attach(f, _stop(t, "This table has no results"), ctx) return match t.kind: RollTable.KIND_CHOICE: await _do_choice(t, f, ctx, stack) RollTable.KIND_LOOP: _start_loop(t, f, ctx, stack) RollTable.KIND_ROUTER: await _do_router(t, f, ctx, stack) RollTable.KIND_SHEET: var sheet := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "", "kind": RollTable.KIND_SHEET} _attach(f, sheet, ctx) await _enter(sheet, f, ctx, stack, true, true) _: var node := _pick_node(t, ctx) _attach(f, node, ctx) if not node.has("stop"): await _enter(node, f, ctx, stack) ## Rolls an entry the normal way (card mode, ranges or weights). Returns a node ## with no children yet, or a stop node. static func _pick_node(t: RollTable, ctx: RollContext) -> Dictionary: var rng := ctx.rng var index: int var value: int var reshuffled := false if t.card_mode: var decks: Dictionary = ctx.get_meta("decks", {}) if not decks.has(t.id): decks[t.id] = DeckState.new() var deck: DeckState = decks[t.id] if deck.cards_left(t).y <= 0: return _stop(t, "This table has no results") if deck.cards_left(t).x <= 0: if t.deck_empty == "stop": return _stop(t, "Deck empty") deck.reshuffle() reshuffled = true var card := deck.draw(t, rng) index = int(card["index"]) value = int(card["value"]) elif t.is_ranged(): var rv := t.roll_value(ctx) if rv["error"] != "": return _stop(t, "Can't roll %s: %s" % [t.dice, rv["error"]]) value = int(rv["value"]) index = t.entry_index_clamped(value) if t.is_expr_dice() else t.entry_index_for(value) if index < 0: return _stop(t, "No result for %s" % t.fmt(value), {"value": value}) else: index = _pick_weighted(t, rng) if index < 0: return _stop(t, "No result can come up") value = index + 1 var node := {"table": t, "index": index, "value": value, "entry": t.entries[index], "children": [], "summary": ""} if reshuffled: node["reshuffled"] = true return node ## The chosen entry happens: its effects run, its text expands (unless ## `expand` is false, for answers) and its pipes are queued. `live` renders the ## text without rolling references (sheet cards). ## ## Before any pipe runs, every pipe's condition and count is worked out once, ## as a snapshot (see pipe_plan()), so what an earlier pipe's subtree does to ## the variables can't change whether or how often a later pipe runs. static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Array, expand: bool = true, live: bool = false) -> void: var t: RollTable = node["table"] var e: TableEntry = node["entry"] var depth := int(f.get("depth", 0)) if e.effects.strip_edges() != "": _log(node, Effects.run(e.effects, ctx, t.id)) if expand: ctx.depth = depth + 1 var ex: Dictionary = await TextExpander.expand_async(e.text, ctx, live) ctx.depth = depth var kids: Array = node["children"] for c: Dictionary in ex["children"]: c["inline"] = true kids.append(c) node["summary"] = ex["text"] # The Chosen entry of a dynamic pick reads as the option's label unless # it has text of its own. if node.has("option"): var plain := Formatter.strip_tags(e.text).strip_edges() if plain == "" or plain == CHOSEN: node["summary"] = Formatter.escape_literal(str(node["option"])) if ctx.halted != "": return var save := str(f.get("save", "")) if save != "": var v: Variant = node["answer"] if node.has("answer") else Formatter.to_export_bbcode(str(node["summary"])) ctx.save(save, v, t.id) # A picked option is saved under the choice's save_as before the pipe # snapshot, so its own pipe conditions can read it. if t.kind == RollTable.KIND_CHOICE and t.save_as != "" and not node.has("answer"): if node.has("option"): ctx.save(t.save_as, str(node["option"]), t.id) else: ctx.save(t.save_as, Formatter.strip_tags(str(node["summary"])).strip_edges(), t.id) if e.pipes.is_empty(): return var log: Array = [] var plan := pipe_plan(e, ctx, log) _log(node, log) for k in range(plan.size() - 1, -1, -1): var item: Dictionary = plan[k] if not item["run"]: continue var p: String = item["to"] stack.append({"op": OP_PIPE, "node": node, "entry": e, "to": p, "left": int(item["count"]), "save": e.save_for(p), "depth": depth}) ## Appends effect-log lines to a node's "effects". static func _log(node: Dictionary, lines: Array) -> void: if lines.is_empty(): return if not node.has("effects"): node["effects"] = [] (node["effects"] as Array).append_array(lines) ## The snapshot of an entry's pipes, taken once after the entry's effects ran ## and its text expanded: one item per pipe, in pipe order, ## {"to": table id, "run": bool, "count": int}. ## - A pipe with a condition ("when") runs only if it's true. An error ## counts as false and adds an error line to `log`. ## - An "otherwise" pipe runs only if none of the entry's conditions was true. ## - Any other pipe always runs. ## Counts are worked out only for pipes that run (0 for the others); an ## expression count's error gives 0 and an error line. static func pipe_plan(e: TableEntry, ctx: RollContext, log: Array = []) -> Array: var plan: Array = [] var any_true := false for p in e.pipes: var w := e.when_for(p) var run := true if w != "": var r := Expr.evaluate(w, ctx) if r["error"] != "": log.append({"text": "Pipe condition %s: %s" % [w, r["error"]], "error": true}) run = false else: run = Expr.truthy(r["value"]) any_true = any_true or run plan.append({"to": p, "run": run, "count": 0, "otherwise": w == "" and e.is_otherwise(p)}) for item: Dictionary in plan: if item["otherwise"]: item["run"] = not any_true item.erase("otherwise") if item["run"]: item["count"] = e.count_value(str(item["to"]), ctx, log) return plan static func _do_pipe(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: Array) -> void: if int(f["left"]) <= 0: return var t := board.get_table(str(f["to"])) if t == null or t.kind == RollTable.KIND_VARIABLE: return f["left"] = int(f["left"]) - 1 stack.append(f) stack.append({"op": OP_ROLL, "id": f["to"], "parent": f["node"], "save": f["save"], "depth": f["depth"]}) # ---------- Routers ---------- ## The index of the first router case whose condition is true (an empty ## condition, the Otherwise case, always matches), or -1. Errors count as ## false and add a line to `log`. static func route(t: RollTable, ctx: RollContext, log: Array = []) -> int: for k in t.entries.size(): var w := t.entries[k].when.strip_edges() if w == "": return k var r := Expr.evaluate(w, ctx) if r["error"] != "": log.append({"text": "Case %s: %s" % [w, r["error"]], "error": true}) elif Expr.truthy(r["value"]): return k return -1 static func _do_router(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void: var log: Array = [] var k := route(t, ctx, log) if k < 0: var stop := _stop(t, NO_CASE, {"kind": RollTable.KIND_ROUTER}) _log(stop, log) _attach(f, stop, ctx) return var node := {"table": t, "index": k, "entry": t.entries[k], "children": [], "summary": "", "kind": RollTable.KIND_ROUTER, "case": k} _log(node, log) _attach(f, node, ctx) await _enter(node, f, ctx, stack) # ---------- Loops ---------- static func _repeated(n: int) -> String: return "Repeated 1 time" if n == 1 else "Repeated %d times" % n static func _start_loop(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void: var header := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": _repeated(0), "kind": RollTable.KIND_LOOP, "passes": 0} _attach(f, header, ctx) var total := 0 if t.loop_mode == "times": var r := Expr.evaluate(t.loop_expr, ctx) if r["error"] != "": header["effects"] = [{"text": "Repeat %s: %s" % [t.loop_expr, r["error"]], "error": true}] else: total = maxi(0, Expr.as_int(r, 0)) stack.append({"op": OP_LOOP, "node": header, "table": t, "i": 0, "total": total, "depth": f.get("depth", 0), "save": f.get("save", ""), "had_i": ctx.chain_vars.has("i"), "prev_i": ctx.chain_vars.get("i")}) ## 1 true, 0 false, -1 error (logged on the header). static func _cond(t: RollTable, header: Dictionary, ctx: RollContext) -> int: var r := Expr.evaluate(t.loop_expr, ctx) if r["error"] != "": if not header.has("effects"): header["effects"] = [] (header["effects"] as Array).append({"text": "%s %s: %s" % [t.loop_mode.capitalize(), t.loop_expr, r["error"]], "error": true}) return -1 return 1 if Expr.truthy(r["value"]) else 0 static func _do_loop(f: Dictionary, ctx: RollContext, stack: Array) -> void: var t: RollTable = f["table"] var header: Dictionary = f["node"] var i := int(f["i"]) var go := false match t.loop_mode: "times": go = i < int(f["total"]) "while": go = _cond(t, header, ctx) == 1 "until": go = i == 0 or _cond(t, header, ctx) == 0 if go: if not _take_action({"parent": header}, t, ctx): return i += 1 f["i"] = i ctx.chain_vars["i"] = i header["passes"] = i header["summary"] = _repeated(i) var pass_node := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "", "kind": RollTable.KIND_LOOP, "pass": i, "value": i} (header["children"] as Array).append(pass_node) stack.append(f) await _enter(pass_node, {"depth": f["depth"]}, ctx, stack) return if f["had_i"]: ctx.chain_vars["i"] = f["prev_i"] else: ctx.chain_vars.erase("i") if str(f["save"]) != "": ctx.save(str(f["save"]), i, t.id) if t.entries.size() > 1: var after := {"table": t, "index": 1, "entry": t.entries[1], "children": [], "summary": "", "kind": RollTable.KIND_LOOP, "after": true} (header["children"] as Array).append(after) await _enter(after, {"depth": f["depth"]}, ctx, stack) # ---------- Choices ---------- ## The prompt request for a choice card (docs/LOGIC.md ยง8): ## {table_id, kind ("pick" | "number" | "text"), title, prompt (BBCode, ## rendered), options: [{index, entry, text, details, weight, ...}], min, max, ## default, log (error lines from show_if and options_where), hidden (how many ## fixed options show_if hid)}. ## A pick's options are its fixed options whose show_if holds (index = entry ## = the entry's index), then, on a dynamic card (options_from), one option ## per candidate variable or list item (index = entries.size() + j, entry = ## 0, the Chosen entry, plus "dynamic": true, "option", "label", "value" and ## "value_text"). The reply is an option's index, or -1 for Random. static func request_for(t: RollTable, ctx: RollContext) -> Dictionary: var options: Array = [] var log: Array = [] var hidden := 0 if t.choice == "pick": var ranged := t.is_ranged() for k in range(t.fixed_start(), t.entries.size()): var e := t.entries[k] if not option_shown(e, ctx, log): hidden += 1 continue options.append({"index": k, "entry": k, "text": TextExpander.render(e.text, ctx), "details": e.details, "weight": e.span() if ranged else maxi(0, e.weight)}) if t.is_dynamic() and not t.entries.is_empty() and option_shown(t.entries[0], ctx, log): var chosen := t.entries[0] var cands := dynamic_options(t, ctx, log) for j in cands.size(): var c: Dictionary = cands[j] var vt := Expr.format_value(c["value"]) if str(c["kind"]) == "prefix" else "" var label := str(c["label"]) var shown := label if vt == "" else "%s %s" % [label, vt] options.append({"index": t.entries.size() + j, "entry": 0, "text": Formatter.escape_literal(shown), "details": chosen.details, "weight": maxi(0, chosen.weight), "dynamic": true, "option": c["option"], "label": label, "value": c["value"], "value_text": vt}) var lo := Expr.eval_int(t.min_expr, ctx, 0) var hi := maxi(lo, Expr.eval_int(t.max_expr, ctx, 99)) var def: Variant = -1 if t.choice == "number": def = lo elif t.choice == "text": def = "" return {"table_id": t.id, "kind": t.choice, "title": t.name, "prompt": TextExpander.render(t.prompt, ctx), "options": options, "min": lo, "max": hi, "default": def, "log": log, "hidden": hidden} ## Whether a pick option is offered now: its show_if is empty or true. An ## error counts as false and adds a line to `log`. static func option_shown(e: TableEntry, ctx: RollContext, log: Array = []) -> bool: var w := e.show_if.strip_edges() if w == "": return true var r := Expr.evaluate(w, ctx) if r["error"] != "": log.append({"text": "Show only if %s: %s" % [w, r["error"]], "error": true}) return false return Expr.truthy(r["value"]) ## The candidates of a dynamic pick card (options_from, filtered by ## options_where), in order: Array of {kind ("prefix" | "list"), option (the ## variable name without "@", or the list item), label, value}. A prefix ## gives one per set variable, sorted by label ("Pilot"); a list gives one ## per item, in list order (label and value are the item). A filter error ## counts as false and adds one line to `log`. static func dynamic_options(t: RollTable, ctx: RollContext, log: Array = []) -> Array: var out: Array = [] var src := RollTable.parse_options_from(t.options_from) if str(src["error"]) != "": log.append({"text": "Options from %s: %s" % [t.options_from.strip_edges(), src["error"]], "error": true}) return out var name := str(src["name"]) var cands: Array = [] match str(src["kind"]): "prefix": for v in ctx.list_vars(name): cands.append({"kind": "prefix", "option": v["name"], "label": v["label"], "value": v["value"]}) "list": var cur: Variant = ctx.get_value("@" + name) for item in Expr.list_items(cur if cur != null else ""): cands.append({"kind": "list", "option": item, "label": item, "value": item}) var where := t.options_where.strip_edges() if where == "": return cands var saved := {} for k in OPTION_VARS: if ctx.chain_vars.has(k): saved[k] = ctx.chain_vars[k] var failed := false for c: Dictionary in cands: _bind_option(ctx, c) var r := Expr.evaluate(where, ctx) if r["error"] != "": if not failed: failed = true log.append({"text": "Only where %s: %s" % [where, r["error"]], "error": true}) elif Expr.truthy(r["value"]): out.append(c) for k in OPTION_VARS: if saved.has(k): ctx.chain_vars[k] = saved[k] else: ctx.chain_vars.erase(k) return out ## How many options a pick card offers right now (show_if and options_from ## included); for the card's live count. static func available_count(t: RollTable, ctx: RollContext) -> int: return (request_for(t, ctx)["options"] as Array).size() ## The chain variables a dynamic option sets. const OPTION_VARS: Array[String] = ["option", "option_label", "option_value"] ## The default text of a dynamic card's Chosen entry: the result then reads as ## the picked option's label. const CHOSEN := "Chosen" static func _bind_option(ctx: RollContext, c: Dictionary) -> void: ctx.chain_vars["option"] = c["option"] ctx.chain_vars["option_label"] = c["label"] ctx.chain_vars["option_value"] = Expr.normalize(c["value"]) ## The headless answer to a request: Random for a pick, min for a number, "" ## for text. static func default_reply(req: Dictionary) -> Variant: match str(req.get("kind", "pick")): "number": return int(req.get("min", 0)) "text": return "" return -1 ## Asks the player through ctx.prompt, or gives the headless answer. static func ask(ctx: RollContext, req: Dictionary) -> Variant: if ctx.no_prompt or not ctx.prompt.is_valid(): return default_reply(req) return await ctx.prompt.call(req) static func _do_choice(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void: var req := request_for(t, ctx) var opts: Array = req["options"] if t.choice == "pick" and opts.is_empty(): var none := _stop(t, NO_OPTIONS, {"kind": RollTable.KIND_CHOICE}) _log(none, req["log"]) _attach(f, none, ctx) return var reply: Variant = await ask(ctx, req) if reply == null: _attach(f, _stop(t, CANCELLED, {"kind": RollTable.KIND_CHOICE, "cancelled": true}), ctx) ctx.halted = CANCELLED return match t.choice: "number": var v := int(req["min"]) if reply is int or reply is float: v = int(reply) elif reply is String and (reply as String).strip_edges().is_valid_int(): v = (reply as String).strip_edges().to_int() v = clampi(v, int(req["min"]), int(req["max"])) await _answered(t, f, ctx, stack, v, str(v)) "text": var s := str(reply) await _answered(t, f, ctx, stack, s, Formatter.close_open_tags(s)) _: var idx := int(reply) if (reply is int or reply is float) else -1 var opt: Dictionary = {} for o: Dictionary in opts: if int(o["index"]) == idx: opt = o break var node: Dictionary if not opt.is_empty(): node = _option_node(t, opt, ctx) node["picked"] = true elif not t.is_dynamic() and int(req["hidden"]) == 0: # A plain fixed list: Random rolls the card the usual way # (weights, ranges, card mode). node = _pick_node(t, ctx) node["random"] = true else: var k := _pick_option(opts, ctx.rng) if k < 0: node = _stop(t, "No result can come up") else: node = _option_node(t, opts[k], ctx) node["random"] = true node["kind"] = RollTable.KIND_CHOICE _log(node, req["log"]) _attach(f, node, ctx) if node.has("stop"): return await _enter(node, f, ctx, stack) ## The node for a pick option from a request: a fixed entry (a card-mode deck ## counts the draw), or the Chosen entry for a dynamic option, which binds ## option, option_label and option_value first. static func _option_node(t: RollTable, o: Dictionary, ctx: RollContext) -> Dictionary: var ei := int(o.get("entry", o["index"])) var node := {"table": t, "index": ei, "entry": t.entries[ei], "children": [], "summary": ""} if o.get("dynamic", false): _bind_option(ctx, {"option": o["option"], "label": o["label"], "value": o["value"]}) node["option"] = str(o["label"]) elif t.card_mode: var decks: Dictionary = ctx.get_meta("decks", {}) if not decks.has(t.id): decks[t.id] = DeckState.new() var deck: DeckState = decks[t.id] var eid := t.entries[ei].id deck.drawn[eid] = int(deck.drawn.get(eid, 0)) + 1 return node ## Random among a request's options by their "weight" (each dynamic option ## weighs as much as the Chosen entry; fixed ones their own weight, or span ## on a ranged card). Position in `opts`, or -1 when every weight is 0. static func _pick_option(opts: Array, rng: RandomNumberGenerator) -> int: var total := 0 for o: Dictionary in opts: total += maxi(0, int(o.get("weight", 1))) if total <= 0: return -1 var pick := rng.randi_range(0, total - 1) for k in opts.size(): pick -= maxi(0, int((opts[k] as Dictionary).get("weight", 1))) if pick < 0: return k return -1 static func _answered(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array, value: Variant, summary: String) -> void: ctx.chain_vars["answer"] = value if t.save_as != "": ctx.save(t.save_as, value, t.id) var node := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": summary, "kind": RollTable.KIND_CHOICE, "answer": value} _attach(f, node, ctx) await _enter(node, f, ctx, stack, false) ## Index of a weighted random entry, or -1 if every weight is 0. static func _pick_weighted(t: RollTable, rng: RandomNumberGenerator) -> int: var total := t.total_weight() if total <= 0: return -1 var pick := rng.randi_range(0, total - 1) for i in t.entries.size(): pick -= maxi(0, t.entries[i].weight) if pick < 0: return i return -1 ## Ids of tables that can never finish rolling: every result they can give ## leads, through pipes, back into such a table. A table that loops on only ## some of its entries is fine, and so is a pipe whose count is an expression ## (it may come to 0) or a conditional pipe (it may not run). static func endless_cycles(board: TowerBoard) -> Array[String]: var done := {} var changed := true while changed: changed = false for t in board.tables: if done.has(t.id): continue if _can_finish(t, board, done): done[t.id] = true changed = true var out: Array[String] = [] for t in board.tables: if not done.has(t.id): out.append(t.id) return out static func _entry_finishes(e: TableEntry, board: TowerBoard, done: Dictionary) -> bool: for p in e.pipes: if e.count_expr(p) != "" or e.is_conditional(p): continue if board.get_table(p) != null and not done.has(p): return false return true static func _can_finish(t: RollTable, board: TowerBoard, done: Dictionary) -> bool: if t.entries.is_empty() or t.kind == RollTable.KIND_VARIABLE: return true if t.kind == RollTable.KIND_LOOP: # Every entry runs (a while/until loop ends on its condition). for e in t.entries: if not _entry_finishes(e, board, done): return false return true var player := t.kind != RollTable.KIND_ROLL for e in t.entries: if not player and not t.can_come_up(e): continue if _entry_finishes(e, board, done): return true if player: return false # No entry can come up at all: the roll just stops. for e in t.entries: if t.can_come_up(e): return false return true ## One line of the result tray for a single node. Plain data only, because it ## is saved in the roll history. "text" is BBCode with internal markers. ## Logic-card keys (only when they apply): kind, effects (Array of {text, ## error?}), answer, passes, pass, after, picked, random, limit, cancelled, ## case (router nodes: the matched case's index). static func step_of(n: Dictionary, depth: int = 0) -> Dictionary: var t: RollTable = n["table"] var step := { "table": t.name, "table_id": t.id, "num": t.fmt(n["value"]) if n.has("value") else "", "die": t.die_size(), "dice": t.dice_label(), "text": str(n.get("summary", n.get("stop", ""))), "depth": depth, } if n.has("entry"): step["entry_id"] = (n["entry"] as TableEntry).id if n.has("stop"): step["stop"] = true if n.get("inline", false): step["inline"] = true if n.get("reshuffled", false): step["reshuffled"] = true if n.has("save_as"): step["save_as"] = n["save_as"] if n.has("kind"): step["kind"] = n["kind"] if n.has("effects"): step["effects"] = (n["effects"] as Array).duplicate(true) for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled", "case", "option"]: if n.has(k): step[k] = n[k] return step ## The whole chain in the order it was rolled. Iterative, so any length is ## fine; works on a partial tree (ctx.root while a roll is running) too. static func flatten(n: Dictionary, out: Array = [], depth: int = 0) -> Array: if n.is_empty(): return out var stack: Array = [[n, depth]] while not stack.is_empty(): var top: Array = stack.pop_back() var node: Dictionary = top[0] var d: int = top[1] out.append(step_of(node, d)) var kids: Array = node.get("children", []) for k in range(kids.size() - 1, -1, -1): stack.append([kids[k], d + 1]) return out static func reaches(n: Dictionary, table_id: String) -> bool: if n.is_empty(): return false var stack: Array = [n] while not stack.is_empty(): var node: Dictionary = stack.pop_back() if (node["table"] as RollTable).id == table_id: return true stack.append_array(node.get("children", [])) return false ## The last sheet node reached in a tree, or {} (the result headline when a ## chain reaches a sheet card). static func last_sheet(n: Dictionary) -> Dictionary: var found := {} if n.is_empty(): return found var stack: Array = [n] while not stack.is_empty(): var node: Dictionary = stack.pop_back() if str(node.get("kind", "")) == RollTable.KIND_SHEET and not node.has("stop"): found = node var kids: Array = node.get("children", []) for k in range(kids.size() - 1, -1, -1): stack.append(kids[k]) return found ## Marks every entry, pipe and reference pipe along the chain as lit. When ## given, `texts` gets each lit entry's expanded text (entry key -> BBCode). ## Iterative. A loop's pass and Afterwards nodes light their entries but no ## pipe (they aren't reached through one). static func collect_lit(n: Dictionary, entries: Dictionary, pipes: Dictionary, texts: Dictionary = {}) -> void: if n.is_empty(): return var stack: Array = [n] while not stack.is_empty(): var node: Dictionary = stack.pop_back() if node.is_empty() or node.has("stop"): continue var t: RollTable = node["table"] var e: TableEntry = node["entry"] entries[entry_key(t.id, e.id)] = true texts[entry_key(t.id, e.id)] = str(node.get("summary", e.text)) var kids: Array = node["children"] for c: Dictionary in kids: if not (c.has("pass") or c.has("after")): pipes[link_key(t.id, e.id, c)] = true for k in range(kids.size() - 1, -1, -1): stack.append(kids[k]) static func entry_key(table_id: String, entry_id: String) -> String: return table_id + ":" + entry_id static func pipe_key(table_id: String, entry_id: String, to_id: String) -> String: return "%s:%s>%s" % [table_id, entry_id, to_id] ## Key of a reference pipe: a [[reference]] in an entry's text to another table. static func ref_key(table_id: String, entry_id: String, to_id: String) -> String: return "%s:%s~%s" % [table_id, entry_id, to_id] static func is_ref_key(key: String) -> bool: return key.contains("~") ## The pipe or reference-pipe key that led from an entry to child node `c`. static func link_key(table_id: String, entry_id: String, c: Dictionary) -> String: var to := (c["table"] as RollTable).id return ref_key(table_id, entry_id, to) if c.get("inline", false) else pipe_key(table_id, entry_id, to) ## Ids of the tables an entry's text references, resolved against the board, ## without duplicates or missing tables. static func ref_targets(board: TowerBoard, text: String) -> Array[String]: var out: Array[String] = [] if not text.contains("[[") and not text.contains("|"): return out var res := func(name: String) -> String: return resolve(board, name) for name in TextExpander.references(text, res): var id := resolve(board, name) if id != "" and not out.has(id): out.append(id) return out ## A context for showing values live (variable and sheet cards, previews): ## nothing is rolled or saved through it by the caller's intent, but dice in ## expressions still roll. `persistent` is the collection's variables. static func live_context(board: TowerBoard, persistent: Dictionary) -> RollContext: return new_context(board, RandomNumberGenerator.new(), persistent, {}) ## Live display of a variable card: its current value as text, or its ## starting value (marked) when it isn't set yet. ## Returns {"text": String, "set": bool, "error": String}. static func variable_display(board: TowerBoard, persistent: Dictionary, t: RollTable) -> Dictionary: var ctx := live_context(board, persistent) var v: Variant = ctx.get_value("@" + t.var_name) if v != null: return {"text": Expr.format_value(v), "set": true, "error": ""} var r := t.initial_value(ctx) return {"text": Expr.format_value(r["value"]), "set": false, "error": str(r["error"])} ## Live rendering of a sheet card's template with current values (BBCode with ## internal markers; [[references]] read as table names, nothing is rolled). static func render_sheet(board: TowerBoard, persistent: Dictionary, t: RollTable) -> String: if t.entries.is_empty(): return "" return TextExpander.render(t.entries[0].text, live_context(board, persistent)) # ---------- Lint ---------- ## Problems with conditional pipes and router cards, for a board check. Pure: ## nothing is rolled. Each item: {table_id, entry_id ("" for the whole card), ## message}. ## - a pipe condition, or a router case condition, that doesn't parse ## - an entry whose "otherwise" pipe comes before one of its conditional ## pipes (a hint: it still works, since the snapshot is taken first) ## - an "otherwise" pipe on an entry with no conditional pipe (always runs) ## - a router with no cases, or whose Otherwise case isn't the last one static func lint_pipes(board: TowerBoard) -> Array[Dictionary]: var out: Array[Dictionary] = [] for t in board.tables: out.append_array(lint_router(t)) out.append_array(lint_options(t)) for i in t.entries.size(): var e := t.entries[i] var first_other := "" var has_when := false var warned := false for p in e.pipes: var pw := e.when_for(p) if pw != "": has_when = true if Expr.check(pw) != "": out.append({"table_id": t.id, "entry_id": e.id, "message": "Pipe condition %s: %s" % [pw, Expr.check(pw)]}) if first_other != "" and not warned: warned = true out.append({"table_id": t.id, "entry_id": e.id, "message": "The otherwise pipe to %s comes before a conditional pipe; put it last so it reads in order" % _table_name(board, first_other)}) elif e.is_otherwise(p) and first_other == "": first_other = p if first_other != "" and not has_when: out.append({"table_id": t.id, "entry_id": e.id, "message": "The otherwise pipe to %s always runs: no pipe on this entry has a condition" % _table_name(board, first_other)}) return out ## The router part of lint_pipes() for one card (empty for other kinds): no ## cases, an Otherwise case that isn't last, case conditions that don't parse. static func lint_router(t: RollTable) -> Array[Dictionary]: var out: Array[Dictionary] = [] if t.kind != RollTable.KIND_ROUTER: return out if t.entries.is_empty(): out.append({"table_id": t.id, "entry_id": "", "message": "This router has no cases"}) for i in t.entries.size(): var e := t.entries[i] var w := e.when.strip_edges() if w == "": if i < t.entries.size() - 1: out.append({"table_id": t.id, "entry_id": e.id, "message": "The Otherwise case isn't last, so the cases after it can never be chosen"}) elif Expr.check(w) != "": out.append({"table_id": t.id, "entry_id": e.id, "message": "Case %s: %s" % [w, Expr.check(w)]}) return out ## Problems with a card's dynamic and conditional options (empty when fine): ## a bad options_from pattern or options_where filter, a filter without ## options_from, options_from or show_if on a card that isn't a pick choice ## (they do nothing there), show_if conditions that don't parse, and a ## dynamic card with no Chosen entry. static func lint_options(t: RollTable) -> Array[Dictionary]: var out: Array[Dictionary] = [] var pick := t.kind == RollTable.KIND_CHOICE and t.choice == "pick" var from := t.options_from.strip_edges() var where := t.options_where.strip_edges() if from != "": if not pick: out.append({"table_id": t.id, "entry_id": "", "message": "Options from %s does nothing: only Which option cards take options from variables" % from}) else: var p := RollTable.parse_options_from(from) if str(p["error"]) != "": out.append({"table_id": t.id, "entry_id": "", "message": "Options from %s: %s" % [from, p["error"]]}) if t.entries.is_empty(): out.append({"table_id": t.id, "entry_id": "", "message": "This card takes options from %s but has no Chosen entry" % from}) if where != "": if from == "": out.append({"table_id": t.id, "entry_id": "", "message": "Only where %s does nothing without Options from" % where}) elif Expr.check(where) != "": out.append({"table_id": t.id, "entry_id": "", "message": "Only where %s: %s" % [where, Expr.check(where)]}) for e in t.entries: var w := e.show_if.strip_edges() if w == "": continue if not pick: out.append({"table_id": t.id, "entry_id": e.id, "message": "Show only if %s does nothing: only Which option cards hide options" % w}) elif Expr.check(w) != "": out.append({"table_id": t.id, "entry_id": e.id, "message": "Show only if %s: %s" % [w, Expr.check(w)]}) return out static func _table_name(board: TowerBoard, id: String) -> String: var t := board.get_table(id) return Formatter.strip_tags(t.name) if t else id