TableTower/core/roller.gd

480 lines
21 KiB
GDScript3
Raw Normal View History

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
## check: on a check card's node, {nat, mod, total, target, success}
## (its "value" is the total; "index" 0 is Success, 1 Failure)
## inputs: {name: value}, the card inputs bound while this node's subtree
## ran (docs/PLAIN.md §4.2)
## why: Array of trace facts (plain Dictionaries with a "type"; see
## docs/LOGIC.md §10 and Describe.why()), present when there are any
##
## 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).
##
## The parts: RollPipes (pipe snapshots, card inputs), RollCards (plain picks,
## routers, checks, loops), RollChoice (choice cards), RollTree (reading the
## result tree, lit keys) and RollLint (static board checks).
##
## 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, OP_RESTORE, OP_COMBINE, OP_PAUSE }
## A paused thread the player chose not to continue.
const STOPPED_HERE := "Stopped here"
## 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 RollChoice.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()
apply_starting_values(board, ctx)
return await _chain(board, table_id, depth, ctx)
## A variable card that says "starts at …" gives its variable that value
## the first time a roll needs it: before a top-level roll, each declared
## variable that isn't set yet and has a starting value is set to it (and
## saved like any other change). Variables with no starting value stay unset,
## and collections are left alone.
static func apply_starting_values(board: TowerBoard, ctx: RollContext) -> void:
if board == null:
return
for t in board.tables:
if t.kind != RollTable.KIND_VARIABLE or t.is_collection() or t.var_name == "":
continue
if t.initial.strip_edges() == "" or ctx.get_value("@" + t.var_name) != null:
continue
var r := t.initial_value(ctx)
if str(r.get("error", "")) == "":
ctx.save("@" + t.var_name, r["value"], t.id)
## The steps of the tree built so far (ctx.root), e.g. while a prompt is open.
static func progress(ctx: RollContext) -> Array:
return RollTree.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 RollCards.do_loop(f, ctx, stack)
OP_RESTORE:
RollPipes.restore(f, ctx)
OP_COMBINE:
var keep: Dictionary = await RollCombine.run(f, ctx)
if not keep.is_empty():
_queue_pipes(keep, ctx, stack, int(f["depth"]))
OP_PAUSE:
await _do_pause(board, f, ctx, stack)
# A halted roll leaves frames behind: put back any card inputs they hid.
while not stack.is_empty():
var rest: Dictionary = stack.pop_back()
if int(rest["op"]) == OP_RESTORE:
RollPipes.restore(rest, ctx)
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"]
if f.has("inputs"):
node["inputs"] = f["inputs"]
var facts: Array = f["pre_why"]
if node.has("why"):
facts.append_array(node["why"])
node["why"] = facts
_log(node, f["pre_log"])
(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
RollPipes.bind_inputs(t, f, ctx, stack)
if t.entries.is_empty():
_attach(f, _stop(t, "This table has no results"), ctx)
return
match t.kind:
RollTable.KIND_CHOICE:
await RollChoice.run(t, f, ctx, stack)
RollTable.KIND_LOOP:
RollCards.start_loop(t, f, ctx, stack)
RollTable.KIND_ROUTER:
await RollCards.do_router(t, f, ctx, stack)
RollTable.KIND_CHECK:
await RollCards.do_check(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 := RollCards.pick_for(t, ctx, f)
if node.has("nat"):
ctx.chain_vars["nat"] = node["nat"]
node.erase("nat")
_attach(f, node, ctx)
if not node.has("stop"):
await _enter(node, f, ctx, stack)
## 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 RollPipes.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() != "":
var facts: Array = []
_log(node, Effects.run(e.effects, ctx, t.id, facts))
_why(node, facts)
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"]
if t.has_columns() and not node.has("kind"):
await RollColumns.fill(node, f, ctx, depth)
ctx.depth = depth
# 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 == RollChoice.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
# A roll that is being combined with others (RollCombine) waits: only the
# one that's kept follows its threads.
if f.get("no_follow", false):
return
_queue_pipes(node, ctx, stack, depth)
## Snapshots a result's threads (RollPipes.pipe_plan) and queues the ones
## that run, last first so they run in order.
static func _queue_pipes(node: Dictionary, ctx: RollContext, stack: Array, depth: int) -> void:
var e: TableEntry = node["entry"]
var log: Array = []
var why: Array = []
var plan := RollPipes.pipe_plan(e, ctx, log, why)
_log(node, log)
_why(node, why)
for k in range(plan.size() - 1, -1, -1):
var item: Dictionary = plan[k]
if not item["run"]:
continue
var p: String = item["to"]
var fr := {"op": OP_PIPE, "node": node, "entry": e, "to": p, "left": int(item["count"]), "save": e.save_for(p), "depth": depth}
if item.has("with"):
fr["with"] = item["with"]
if e.dice_for(p) != "":
fr["dice"] = e.dice_for(p)
if not e.reroll_for(p).is_empty():
fr["reroll"] = e.reroll_for(p)
var mode := e.combine_for(p)
if mode != "all" and int(item["count"]) > 1:
# Runs after every repeat: combines them (RollCombine).
stack.append({"op": OP_COMBINE, "node": node, "to": p, "mode": mode, "save": fr["save"],
"start": (node["children"] as Array).size(), "depth": depth})
fr["no_follow"] = true
fr["save"] = ""
stack.append(fr)
if e.pipe_pause.has(p):
# Runs first: waits for the player before the thread above it.
stack.append({"op": OP_PAUSE, "node": node, "to": p, "depth": depth})
## Appends why-trace facts to a node's "why".
static func _why(node: Dictionary, facts: Array) -> void:
if facts.is_empty():
return
if not node.has("why"):
node["why"] = facts
else:
(node["why"] as Array).append_array(facts)
## 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)
## A paused thread: asks the player (kind "pause") whether to go on. Stopping
## drops the thread waiting under this frame and marks the result.
static func _do_pause(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: Array) -> void:
var t := board.get_table(str(f["to"]))
var node: Dictionary = f["node"]
var req := {"kind": "pause", "table_id": str(f["to"]), "title": t.name if t else str(f["to"]),
"prompt": "Continue to %s?" % Formatter.strip_tags(t.name if t else str(f["to"])),
"from": Formatter.strip_tags((node["table"] as RollTable).name)}
var reply: Variant = await RollChoice.ask(ctx, req)
if reply == true:
return
if not stack.is_empty() and int((stack.back() as Dictionary)["op"]) == OP_PIPE:
stack.pop_back()
node["stopped_before"] = str(f["to"])
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)
var fr := {"op": OP_ROLL, "id": f["to"], "parent": f["node"], "save": f["save"], "depth": f["depth"]}
for key in ["with", "dice", "reroll"]:
if f.has(key):
fr[key] = f[key]
if f.get("no_follow", false):
fr["no_follow"] = true
stack.append(fr)
## 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. A collection shows its set
## members ("Gun Combat 1, Pilot 0"; set is false when there are none).
## Returns {"text": String, "set": bool, "error": String}.
static func variable_display(board: TowerBoard, persistent: Dictionary, t: RollTable) -> Dictionary:
var ctx := live_context(board, persistent)
if t.is_collection():
var listed := ctx.list_text(t.var_name + "_")
return {"text": listed, "set": listed != "", "error": ""}
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))
# ---------- Delegators (the parts live in RollPipes, RollCards, RollChoice, RollTree, RollLint) ----------
## The default text of a dynamic card's Chosen entry (RollChoice.CHOSEN).
const CHOSEN := RollChoice.CHOSEN
static func request_for(t: RollTable, ctx: RollContext) -> Dictionary: return RollChoice.request_for(t, ctx)
static func dynamic_options(t: RollTable, ctx: RollContext, log: Array = [], why: Array = []) -> Array: return RollChoice.dynamic_options(t, ctx, log, why)
static func available_count(t: RollTable, ctx: RollContext) -> int: return RollChoice.available_count(t, ctx)
static func ask(ctx: RollContext, req: Dictionary) -> Variant: return await RollChoice.ask(ctx, req)
static func step_of(n: Dictionary, depth: int = 0) -> Dictionary: return RollTree.step_of(n, depth)
static func flatten(n: Dictionary, out: Array = [], depth: int = 0) -> Array: return RollTree.flatten(n, out, depth)
static func reaches(n: Dictionary, table_id: String) -> bool: return RollTree.reaches(n, table_id)
static func last_sheet(n: Dictionary) -> Dictionary: return RollTree.last_sheet(n)
static func collect_lit(n: Dictionary, entries: Dictionary, pipes: Dictionary, texts: Dictionary = {}) -> void: RollTree.collect_lit(n, entries, pipes, texts)
static func entry_key(table_id: String, entry_id: String) -> String: return RollTree.entry_key(table_id, entry_id)
static func pipe_key(table_id: String, entry_id: String, to_id: String) -> String: return RollTree.pipe_key(table_id, entry_id, to_id)
static func ref_key(table_id: String, entry_id: String, to_id: String) -> String: return RollTree.ref_key(table_id, entry_id, to_id)
static func is_ref_key(key: String) -> bool: return RollTree.is_ref_key(key)
static func link_key(table_id: String, entry_id: String, c: Dictionary) -> String: return RollTree.link_key(table_id, entry_id, c)
static func ref_targets(board: TowerBoard, text: String) -> Array[String]: return RollTree.ref_targets(board, text)
static func endless_cycles(board: TowerBoard) -> Array[String]: return RollLint.endless_cycles(board)
static func lint_pipes(board: TowerBoard) -> Array[Dictionary]: return RollLint.lint_pipes(board)
static func lint_router(t: RollTable) -> Array[Dictionary]: return RollLint.lint_router(t)
static func lint_options(t: RollTable) -> Array[Dictionary]: return RollLint.lint_options(t)
static func lint_check(t: RollTable) -> Array[Dictionary]: return RollLint.lint_check(t)
static func lint_inputs(board: TowerBoard, t: RollTable) -> Array[Dictionary]: return RollLint.lint_inputs(board, t)