TableTower/core/roller.gd
RobinFiredrake adb93c545c Join the inspector and display halves; starting values apply to rolls
- Cards read the inspector's selection ({kind, tid, eid}) and the
  inspector marks the selected row on every card when it changes.
- A variable card's starting value now applies: before a top-level
  roll, each declared variable that isn't set yet and has a starting
  value is set to it (a "starts at 9" Strength no longer reads as 0).
- Check cards in Build no longer repeat "Success Success": a result
  text equal to the outlet name shows as an empty field with a hint.
- test_options switches to the Text view through Main.

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

1407 lines
53 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
## 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).
##
## 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 }
## 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()
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 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)
OP_RESTORE:
_restore(f, ctx)
# 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:
_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
_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 _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_CHECK:
await _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 := _pick_node(t, ctx)
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)
## 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
var fact: Dictionary
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"])
fact = {"type": "roll", "pick": "card", "dice": t.dice_label(), "total": value}
elif t.is_ranged():
var was: Variant = ctx.faces
ctx.faces = []
var rv := t.roll_value(ctx)
var faces: Array = ctx.faces
ctx.faces = was
if was != null:
(was as Array).append_array(faces)
if rv["error"] != "":
return _stop(t, "Can't roll %s: %s" % [t.dice, rv["error"]])
value = int(rv["value"])
fact = {"type": "roll", "pick": "dice", "dice": t.dice.strip_edges(), "faces": faces, "total": value}
if not faces.is_empty():
var nat := 0
for x: int in faces:
nat += x
fact["nat"] = nat
fact["mod"] = value - nat
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
fact = {"type": "roll", "pick": "weighted", "dice": t.dice_label(), "total": value}
var node := {"table": t, "index": index, "value": value, "entry": t.entries[index], "children": [],
"summary": "", "why": [fact]}
if reshuffled:
node["reshuffled"] = true
# "nat" for the caller (_do_roll sets the chain value and drops the key):
# the dice alone, or a plain table's die value. An expression without
# dice ("@terms") has none.
if fact.has("nat"):
node["nat"] = fact["nat"]
elif str(fact["pick"]) != "dice":
node["nat"] = value
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() != "":
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"]
# 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 why: Array = []
var plan := 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"]
stack.append(fr)
## 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)
## 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, "with": {name: value}} ("with"
## only on a pipe that runs and passes input values; a value whose expression
## fails is left out, so the target's default applies, with an error line).
## - 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. `why` gets the trace
## facts: {"type": "when", "to", "expr", "values": {name: value}, "result":
## bool, "error"?} per conditional pipe and {"type": "otherwise", "to",
## "result"} per otherwise pipe.
static func pipe_plan(e: TableEntry, ctx: RollContext, log: Array = [], why: 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)
var fact := {"type": "when", "to": p, "expr": w, "values": Expr.values_read(w, ctx), "result": false}
if r["error"] != "":
log.append({"text": "Pipe condition %s: %s" % [w, r["error"]], "error": true})
run = false
fact["error"] = str(r["error"])
else:
run = Expr.truthy(r["value"])
fact["result"] = run
why.append(fact)
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
why.append({"type": "otherwise", "to": item["to"], "result": item["run"]})
item.erase("otherwise")
if item["run"]:
item["count"] = e.count_value(str(item["to"]), ctx, log)
if not e.pipe_with.is_empty() and e.pipe_with.has(item["to"]):
item["with"] = with_values(e, str(item["to"]), ctx, log)
return plan
## The input values a pipe passes, worked out now: {name: value}. A value
## whose expression fails is left out (the target's default applies) and adds
## an error line to `log`.
static func with_values(e: TableEntry, target: String, ctx: RollContext, log: Array = []) -> Dictionary:
var out := {}
var w: Variant = e.pipe_with.get(target)
if not (w is Dictionary):
return out
for nm: String in w:
var src := str(w[nm])
var r := Expr.evaluate(src, ctx)
if r["error"] != "":
log.append({"text": "Pipe input %s = %s: %s" % [nm, src, r["error"]], "error": true})
else:
out[nm] = Expr.normalize(r["value"])
return out
# ---------- Card inputs ----------
## Binds a card's inputs as chain values for the subtree about to run: the
## pipe's "with" values (f["with"]), and each declared input's default for the
## rest. Pushes an OP_RESTORE frame first, so the previous values come back
## when the subtree ends. The trace facts and error lines go on the node via
## _attach().
static func _bind_inputs(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
var given: Dictionary = f.get("with", {})
if t.inputs.is_empty() and given.is_empty():
return
var values := {}
var facts: Array = []
var log: Array = []
for inp: Dictionary in t.inputs:
var nm := str(inp.get("name", ""))
if nm == "" or values.has(nm):
continue
if given.has(nm):
values[nm] = given[nm]
facts.append({"type": "input", "name": nm, "value": given[nm], "from": "pipe"})
continue
var def := str(inp.get("default", "")).strip_edges()
var v: Variant = 0
if def != "":
var r := Expr.evaluate(def, ctx)
if r["error"] != "":
log.append({"text": "Input %s default %s: %s" % [nm, def, r["error"]], "error": true})
else:
v = Expr.normalize(r["value"])
values[nm] = v
facts.append({"type": "input", "name": nm, "value": v, "from": "default"})
for nm: String in given:
if not values.has(nm):
values[nm] = given[nm]
facts.append({"type": "input", "name": nm, "value": given[nm], "from": "pipe"})
var saved := {}
for nm: String in values:
saved[nm] = [ctx.chain_vars.has(nm), ctx.chain_vars.get(nm)]
ctx.chain_vars[nm] = values[nm]
stack.append({"op": OP_RESTORE, "saved": saved})
f["inputs"] = values
f["pre_why"] = facts
f["pre_log"] = log
## Puts back the chain values a card's inputs hid.
static func _restore(f: Dictionary, ctx: RollContext) -> void:
var saved: Dictionary = f["saved"]
for nm: String in saved:
var pair: Array = saved[nm]
if pair[0]:
ctx.chain_vars[nm] = pair[1]
else:
ctx.chain_vars.erase(nm)
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"]}
if f.has("with"):
fr["with"] = f["with"]
stack.append(fr)
# ---------- 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`. `why` gets one fact per case tried:
## {"type": "case", "index", "expr" ("" for Otherwise), "values", "result",
## "error"?}.
static func route(t: RollTable, ctx: RollContext, log: Array = [], why: Array = []) -> int:
for k in t.entries.size():
var w := t.entries[k].when.strip_edges()
if w == "":
why.append({"type": "case", "index": k, "expr": "", "values": {}, "result": true})
return k
var r := Expr.evaluate(w, ctx)
var fact := {"type": "case", "index": k, "expr": w, "values": Expr.values_read(w, ctx), "result": false}
why.append(fact)
if r["error"] != "":
log.append({"text": "Case %s: %s" % [w, r["error"]], "error": true})
fact["error"] = str(r["error"])
elif Expr.truthy(r["value"]):
fact["result"] = true
return k
return -1
static func _do_router(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
var log: Array = []
var why: Array = []
var k := route(t, ctx, log, why)
if k < 0:
var stop := _stop(t, NO_CASE, {"kind": RollTable.KIND_ROUTER})
_log(stop, log)
_why(stop, why)
_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)
_why(node, why)
_attach(f, node, ctx)
await _enter(node, f, ctx, stack)
# ---------- Checks ----------
## Rolls a check card's dice, modifier and target (docs/PLAIN.md §4.1):
## {"nat", "mod", "total", "target", "success", "faces" (the dice faces),
## "error" ("" when fine)}. An empty modifier is 0. Numbers are whole
## (floored).
static func check_roll(t: RollTable, ctx: RollContext) -> Dictionary:
var out := {"nat": 0, "mod": 0, "total": 0, "target": 0, "success": false, "faces": [], "error": ""}
var was: Variant = ctx.faces
ctx.faces = []
var r := Expr.evaluate(t.check_dice, ctx)
var faces: Array = ctx.faces
ctx.faces = was
if was != null:
(was as Array).append_array(faces)
out["faces"] = faces
if r["error"] != "":
out["error"] = "Check dice %s: %s" % [t.check_dice, r["error"]]
return out
if not Expr.is_number(r["value"]):
out["error"] = "Check dice %s gave \"%s\", not a number" % [t.check_dice, Expr.format_value(r["value"])]
return out
var nat := Expr.as_int(r, 0)
var mod := 0
if t.check_mod.strip_edges() != "":
var m := Expr.evaluate(t.check_mod, ctx)
if m["error"] != "" or not Expr.is_number(m["value"]):
out["error"] = "Check modifier %s: %s" % [t.check_mod, m["error"] if m["error"] != "" else "not a number"]
return out
mod = Expr.as_int(m, 0)
var g := Expr.evaluate(t.check_target, ctx)
if g["error"] != "" or not Expr.is_number(g["value"]):
out["error"] = "Check target %s: %s" % [t.check_target, g["error"] if g["error"] != "" else "not a number"]
return out
var target := Expr.as_int(g, 0)
var total := nat + mod
out["nat"] = nat
out["mod"] = mod
out["total"] = total
out["target"] = target
out["success"] = total <= target if t.check_cmp == "le" else total >= target
return out
static func _do_check(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
var c := check_roll(t, ctx)
if str(c["error"]) != "":
var stop := _stop(t, "Can't roll the check: %s" % c["error"], {"kind": RollTable.KIND_CHECK})
stop["effects"] = [{"text": str(c["error"]), "error": true}]
_attach(f, stop, ctx)
return
ctx.chain_vars["nat"] = c["nat"]
ctx.chain_vars["total"] = c["total"]
ctx.chain_vars["effect"] = int(c["total"]) - int(c["target"])
var k := 0 if c["success"] else 1
var info := {"nat": c["nat"], "mod": c["mod"], "total": c["total"], "target": c["target"], "success": c["success"]}
var fact := {"type": "check", "dice": t.check_dice.strip_edges(), "mod_expr": t.check_mod.strip_edges(),
"target_expr": t.check_target.strip_edges(), "faces": c["faces"], "nat": c["nat"], "mod": c["mod"],
"total": c["total"], "target": c["target"], "cmp": t.check_cmp, "success": c["success"]}
if k >= t.entries.size():
var none := _stop(t, "This check has no Failure result", {"kind": RollTable.KIND_CHECK, "check": info, "value": c["total"]})
_why(none, [fact])
_attach(f, none, ctx)
return
var node := {"table": t, "index": k, "entry": t.entries[k], "value": c["total"], "children": [], "summary": "",
"kind": RollTable.KIND_CHECK, "check": info, "why": [fact]}
_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 why: Array = []
var hidden := 0
var chosen_hidden := false
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 not option_shown(t.entries[0], ctx, log):
chosen_hidden = true
elif t.is_dynamic() and not t.entries.is_empty():
var chosen := t.entries[0]
var cands := dynamic_options(t, ctx, log, why)
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 = ""
if hidden > 0 or chosen_hidden:
why.push_front({"type": "show_if", "hidden": hidden, "chosen_hidden": chosen_hidden})
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, "why": why}
## 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`. With a filter, `why` gets
## {"type": "options_where", "from", "expr", "kept", "total"}.
static func dynamic_options(t: RollTable, ctx: RollContext, log: Array = [], why: 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)
why.append({"type": "options_where", "from": t.options_from.strip_edges(), "expr": where, "kept": out.size(), "total": cands.size()})
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"])
_why(none, req["why"])
_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.erase("nat")
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"])
_why(node, req["why"])
_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), option, check ({nat, mod,
## total, target, success}), inputs ({name: value}) and why (the trace facts,
## a copy of the array; the facts themselves are shared, don't change them).
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", "check", "inputs"]:
if n.has(k):
step[k] = n[k]
if n.has("why"):
step["why"] = (n["why"] as Array).duplicate()
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. 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))
# ---------- 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))
out.append_array(lint_check(t))
out.append_array(lint_inputs(board, 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
## Problems with a check card (empty for other kinds): dice, modifier or
## target expressions that don't parse or are empty, and a missing Success or
## Failure result. Items also carry "kind": "check" and "level": "error".
static func lint_check(t: RollTable) -> Array[Dictionary]:
var out: Array[Dictionary] = []
if t.kind != RollTable.KIND_CHECK:
return out
for pair: Array in [["Check dice", t.check_dice], ["Check modifier", t.check_mod], ["Check target", t.check_target]]:
var src := str(pair[1]).strip_edges()
var msg := ""
if src == "":
if pair[0] != "Check modifier":
msg = "%s is empty" % pair[0]
elif Expr.check(src) != "":
msg = "%s %s: %s" % [pair[0], src, Expr.check(src)]
if msg != "":
out.append({"table_id": t.id, "entry_id": "", "message": msg, "kind": "check", "level": "error"})
if t.entries.size() < 2:
out.append({"table_id": t.id, "entry_id": "", "kind": "check", "level": "error",
"message": "A check needs a Success result and a Failure result"})
return out
## Problems with card inputs and the pipes that pass them (docs/PLAIN.md
## §4.2): declared inputs with a bad or repeated name or a default that
## doesn't parse ("level": "error"), pipe "with" expressions that don't parse
## (error), and a "with" naming an input the target doesn't declare
## ("level": "hint": it still works, as a chain value). Items carry "kind":
## "inputs".
static func lint_inputs(board: TowerBoard, t: RollTable) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var seen := {}
for inp: Dictionary in t.inputs:
var nm := str(inp.get("name", ""))
if not _is_name(nm):
out.append({"table_id": t.id, "entry_id": "", "kind": "inputs", "level": "error",
"message": "Input \"%s\" isn't a name (lowercase letters, digits and _)" % nm})
elif seen.has(nm):
out.append({"table_id": t.id, "entry_id": "", "kind": "inputs", "level": "error",
"message": "Input %s is declared twice" % nm})
seen[nm] = true
var def := str(inp.get("default", "")).strip_edges()
if def != "" and Expr.check(def) != "":
out.append({"table_id": t.id, "entry_id": "", "kind": "inputs", "level": "error",
"message": "Input %s default %s: %s" % [nm, def, Expr.check(def)]})
for e in t.entries:
if e.pipe_with.is_empty():
continue
for p in e.pipes:
var w := e.with_for(p)
if w.is_empty():
continue
var target := board.get_table(p)
for nm: String in w:
var src := str(w[nm])
if Expr.check(src) != "":
out.append({"table_id": t.id, "entry_id": e.id, "kind": "inputs", "level": "error",
"message": "Pipe input %s = %s: %s" % [nm, src, Expr.check(src)]})
if target != null and target.find_input(nm).is_empty():
out.append({"table_id": t.id, "entry_id": e.id, "kind": "inputs", "level": "hint",
"message": "The pipe to %s passes %s, but that card has no input called %s" % [_table_name(board, p), nm, nm]})
return out
static var _name_re: RegEx = null
static func _is_name(s: String) -> bool:
if _name_re == null:
_name_re = RegEx.create_from_string("^[a-z_][a-z0-9_]*$")
return _name_re.search(s) != null
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