TableTower/core/roller.gd
RobinFiredrake dbbb9750eb Conditional pipes and router cards
Pipes can carry "when" (Only if) and "otherwise". When an entry is
chosen, its effects run, its text expands, then every pipe condition and
count is evaluated once as a snapshot before any pipe runs; when pipes
run if true, otherwise pipes if no when pipe was true, plain pipes
always. Condition errors count as false and show as error lines.

New router card (kind "router"): its entries are cases with an
entry-level "when"; the first true case is chosen (empty = Otherwise),
and "No case matched" stops the node. One action. JSON round trip for
entry/pipe when and pipe otherwise, including JsonIO.canonical and
edge labels. Roller.lint_pipes() and Roller.lint_router() for board
checks. A pick choice's save_as is now stored before the snapshot.

UI: Only if / Otherwise in the pipe popover with live validation, pipe
labels ("if @str >= 8", "otherwise") and a source-end diamond on
conditional pipes, router card with fork icon, per-case condition rows,
case editing / reordering in Build, router settings, "+ Table" entry,
router cases in table previews. Logic demo now routes through a router.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 17:53:00 -06:00

856 lines
31 KiB
GDScript

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
## 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"
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"]
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"):
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, text, details}], min, max, default}.
static func request_for(t: RollTable, ctx: RollContext) -> Dictionary:
var options: Array = []
if t.choice == "pick":
for k in t.entries.size():
var e := t.entries[k]
options.append({"index": k, "text": TextExpander.render(e.text, ctx), "details": e.details})
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}
## 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 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 node: Dictionary
if idx >= 0 and idx < t.entries.size():
node = {"table": t, "index": idx, "entry": t.entries[idx], "children": [], "summary": "", "picked": true}
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]
var eid := t.entries[idx].id
deck.drawn[eid] = int(deck.drawn.get(eid, 0)) + 1
else:
node = _pick_node(t, ctx)
node["random"] = true
node["kind"] = RollTable.KIND_CHOICE
_attach(f, node, ctx)
if node.has("stop"):
return
await _enter(node, f, ctx, stack)
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"]:
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))
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
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