Split core/roller.gd into RollPipes, RollCards, RollChoice, RollTree and RollLint

The execution loop, node helpers and live display stay in Roller; every
Roller function and constant used elsewhere keeps a one-line delegator.
No behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
RobinFiredrake 2026-11-09 08:05:46 -06:00
parent f3912fb026
commit bb75837131
11 changed files with 1081 additions and 1025 deletions

267
core/roll_cards.gd Normal file
View file

@ -0,0 +1,267 @@
class_name RollCards
extends RefCounted
## How the Roller runs each card kind other than choices: a plain roll's pick
## (card mode, ranges or weights), routers, checks and loops. The handlers
## build nodes with Roller's node helpers and push frames on its work 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 Roller._stop(t, "This table has no results")
if deck.cards_left(t).x <= 0:
if t.deck_empty == "stop":
return Roller._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 Roller._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 Roller._stop(t, "No result for %s" % t.fmt(value), {"value": value})
else:
index = pick_weighted(t, rng)
if index < 0:
return Roller._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 (Roller._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
## 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
# ---------- 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 := Roller._stop(t, Roller.NO_CASE, {"kind": RollTable.KIND_ROUTER})
Roller._log(stop, log)
Roller._why(stop, why)
Roller._attach(f, stop, ctx)
return
var node := {"table": t, "index": k, "entry": t.entries[k], "children": [], "summary": "",
"kind": RollTable.KIND_ROUTER, "case": k}
Roller._log(node, log)
Roller._why(node, why)
Roller._attach(f, node, ctx)
await Roller._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 := Roller._stop(t, "Can't roll the check: %s" % c["error"], {"kind": RollTable.KIND_CHECK})
stop["effects"] = [{"text": str(c["error"]), "error": true}]
Roller._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 := Roller._stop(t, "This check has no Failure result", {"kind": RollTable.KIND_CHECK, "check": info, "value": c["total"]})
Roller._why(none, [fact])
Roller._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]}
Roller._attach(f, node, ctx)
await Roller._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}
Roller._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": Roller.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 Roller._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 Roller._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 Roller._enter(after, {"depth": f["depth"]}, ctx, stack)

1
core/roll_cards.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://34tk0cnvk0xc

260
core/roll_choice.gd Normal file
View file

@ -0,0 +1,260 @@
class_name RollChoice
extends RefCounted
## Choice cards for the Roller: the prompt request, show_if and dynamic
## options (options_from / options_where), asking the player, and running the
## answer.
## 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 run(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 := Roller._stop(t, Roller.NO_OPTIONS, {"kind": RollTable.KIND_CHOICE})
Roller._log(none, req["log"])
Roller._why(none, req["why"])
Roller._attach(f, none, ctx)
return
var reply: Variant = await ask(ctx, req)
if reply == null:
Roller._attach(f, Roller._stop(t, Roller.CANCELLED, {"kind": RollTable.KIND_CHOICE, "cancelled": true}), ctx)
ctx.halted = Roller.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 = RollCards.pick_node(t, ctx)
node.erase("nat")
node["random"] = true
else:
var k := _pick_option(opts, ctx.rng)
if k < 0:
node = Roller._stop(t, "No result can come up")
else:
node = _option_node(t, opts[k], ctx)
node["random"] = true
node["kind"] = RollTable.KIND_CHOICE
Roller._log(node, req["log"])
Roller._why(node, req["why"])
Roller._attach(f, node, ctx)
if node.has("stop"):
return
await Roller._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}
Roller._attach(f, node, ctx)
await Roller._enter(node, f, ctx, stack, false)

1
core/roll_choice.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://c02u6gk8nsgei

231
core/roll_lint.gd Normal file
View file

@ -0,0 +1,231 @@
class_name RollLint
extends RefCounted
## Static checks of a board for the Roller's logic, nothing rolled: endless
## pipe cycles and the lint_* problem lists.
## 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
## 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

1
core/roll_lint.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://c38v4ww0q0i5w

125
core/roll_pipes.gd Normal file
View file

@ -0,0 +1,125 @@
class_name RollPipes
extends RefCounted
## Pipe snapshots and card inputs for the Roller: what an entry's pipes do
## (pipe_plan()), the values they pass, and binding a card's inputs for the
## subtree it runs.
## 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 a Roller.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 Roller._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": Roller.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)

1
core/roll_pipes.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cmdpq6cvma4u

151
core/roll_tree.gd Normal file
View file

@ -0,0 +1,151 @@
class_name RollTree
extends RefCounted
## Reading a Roller result tree: tray steps (step_of(), flatten()), searches
## over it, and the lit entry / pipe / reference keys the board highlights.
## 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 Roller.resolve(board, name)
for name in TextExpander.references(text, res):
var id := Roller.resolve(board, name)
if id != "" and not out.has(id):
out.append(id)
return out

1
core/roll_tree.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cfulnuma0fa6a

File diff suppressed because it is too large Load diff