TableTower/core/board_tester.gd
RobinFiredrake 6f583ea4f5 Plain Build engine: Describe, Builder, checks, inputs, collections, why trace
Implements docs/PLAIN.md sections 1-5 (the engine half of the usability pass):

- core/describe.gd (Describe): rules in plain words, labelled from variable
  cards, collections and card inputs, falling back to the original text.
- core/builder.gd (Builder): effect and condition models that round-trip
  with the rule text, a rule tokenizer, and known_values(board).
- Collections: variable cards with var_type "collection" label their
  members and don't declare their stem.
- Check cards (kind "check"): dice + modifier vs target, Success/Failure,
  chain values nat/total/effect, node "check" info, lint and static checks.
- Card inputs and pipe "with" values, scoped over the pipe's subtree on the
  explicit work stack (OP_RESTORE frames), with defaults and snapshot
  evaluation.
- nat on every roll-table roll; dice faces recorded through ctx.faces.
- Why trace: facts on nodes and steps (input, roll, check, case, show_if,
  options_where, effect, when, otherwise).
- StateStore rules_view setting; JSON for the new keys; LOGIC.md and
  PLAIN.md updated (deviations in PLAIN.md 5a).

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

503 lines
19 KiB
GDScript

class_name BoardTester
extends RefCounted
## Tests a board without a window: static checks (bad expressions and effects,
## range gaps, pipes to missing tables, endless cycles ...) and a simulation
## that rolls a start table many times, answering every choice card at random,
## then reports what happened (see docs/LOGIC.md and the README).
##
## Use from a coroutine, in slices, so a UI stays responsive:
## var t := BoardTester.new(board, "start", {"runs": 500, "seed": 1})
## while not t.is_done():
## await t.run_batch(10)
## var report := t.report()
##
## Every run gets its own empty variables and decks, so the caller's saved
## variables and decks are never read or changed. tools/simulate_board.gd is
## the command-line front end.
var board: TowerBoard
var start := ""
var runs_total := 1
var runs_done := 0
var _rng := RandomNumberGenerator.new()
var _answer_rng := RandomNumberGenerator.new()
var _prefer: RegEx = null
var _max_actions := RollContext.DEFAULT_MAX_ACTIONS
var _base_vars := {}
var _cancelled := false
var _completed := 0
var _halted := {}
var _actions: Array[int] = []
var _prompts_total := 0
var _errors := {} # key -> {table, table_id, entry, entry_id, text, count}
var _dead_ends := {} # key -> {table, table_id, text, count}
var _markers := {} # key -> {table, table_id, entry, entry_id, text, count}
var _table_hits := {} # table id -> count
var _entry_hits := {} # "table:entry" -> count
var _sample_sheet := ""
var _sample_vars := {}
var _sample_halted := ""
var _longest := {"actions": -1, "run": 0, "top": []}
var _track := {} # name -> {min, max, sum, n}
## opts: runs (int), seed (int), prefer (regex String, may be ""), max_actions
## (int), track (Array of variable names), vars (Dictionary every run starts
## from a deep copy of; default empty).
func _init(p_board: TowerBoard, p_start: String, opts: Dictionary = {}) -> void:
board = p_board
start = p_start
runs_total = maxi(1, int(opts.get("runs", 100)))
_rng.seed = int(opts.get("seed", 1))
_answer_rng.seed = _rng.seed * 7919 + 17
var pat := str(opts.get("prefer", ""))
if pat != "":
_prefer = RegEx.create_from_string("(?i)" + pat)
_max_actions = int(opts.get("max_actions", RollContext.DEFAULT_MAX_ACTIONS))
_base_vars = opts.get("vars", {})
for name: String in opts.get("track", []):
_track[name.strip_edges().trim_prefix("@")] = {"min": INF, "max": -INF, "sum": 0.0, "n": 0}
func is_done() -> bool:
return _cancelled or runs_done >= runs_total
func cancel() -> void:
_cancelled = true
func was_cancelled() -> bool:
return _cancelled
## Does up to `k` more runs; returns how many it did.
func run_batch(k: int) -> int:
var did := 0
while did < k and not is_done():
await _one_run(runs_done)
runs_done += 1
did += 1
return did
## All the remaining runs in one go.
func run_all() -> void:
while not is_done():
await run_batch(25)
## Convenience: every run, then the report.
static func simulate(p_board: TowerBoard, p_start: String, opts: Dictionary = {}) -> Dictionary:
var t := BoardTester.new(p_board, p_start, opts)
await t.run_all()
return t.report()
func _one_run(run: int) -> void:
var vars: Dictionary = _base_vars.duplicate(true)
var ctx := Roller.new_context(board, _rng, vars, {})
ctx.max_actions = _max_actions
var counter := [0]
ctx.prompt = func(req: Dictionary) -> Variant:
counter[0] += 1
var texts: Array = [str(req.get("prompt", ""))]
for o: Dictionary in req.get("options", []):
texts.append(str(o.get("text", "")))
for txt: String in texts:
for m in _marker_re().search_all(txt):
var what := Formatter.strip_tags(m.get_string())
var tid := str(req.get("table_id", ""))
var mk := tid + ":prompt|" + what
if not _markers.has(mk):
_markers[mk] = {"table": "%s (%s)" % [Formatter.strip_tags(str(req.get("title", ""))), tid], "table_id": tid,
"entry": "(prompt)", "entry_id": "", "text": what, "count": 0}
_markers[mk]["count"] += 1
return answer(req, _answer_rng, _prefer)
var root: Dictionary = await Roller.roll_async(board, start, ctx)
_prompts_total += counter[0]
_actions.append(ctx.actions)
if ctx.halted == "":
_completed += 1
else:
var why := "Action limit" if ctx.halted.begins_with("Stopped after") else ctx.halted
_halted[why] = int(_halted.get(why, 0)) + 1
for name: String in _track:
var v: Variant = Expr.to_value((vars.get(name, {}) as Dictionary).get("value") if vars.get(name) is Dictionary else null)
if v is int or v is float:
var tr: Dictionary = _track[name]
tr["min"] = minf(tr["min"], v)
tr["max"] = maxf(tr["max"], v)
tr["sum"] += v
tr["n"] += 1
var run_hits := {}
for st: Dictionary in Roller.flatten(root, []):
var tid := str(st.get("table_id", ""))
run_hits[tid] = int(run_hits.get(tid, 0)) + 1
var eid := str(st.get("entry_id", ""))
var tname := Formatter.strip_tags(str(st.get("table", "")))
if st.get("stop", false):
if not st.get("limit", false) and not st.get("cancelled", false):
var dk := tid + "|" + str(st.get("text", ""))
if not _dead_ends.has(dk):
_dead_ends[dk] = {"table": "%s (%s)" % [tname, tid], "table_id": tid,
"text": Formatter.strip_tags(str(st.get("text", ""))), "count": 0}
_dead_ends[dk]["count"] += 1
continue
_table_hits[tid] = int(_table_hits.get(tid, 0)) + 1
if eid != "" and not st.has("pass") and not st.has("after"):
_entry_hits[tid + ":" + eid] = int(_entry_hits.get(tid + ":" + eid, 0)) + 1
elif st.has("pass"):
_entry_hits[tid + ":" + _loop_entry_id(board, tid, 0)] = 1
elif st.has("after"):
_entry_hits[tid + ":" + _loop_entry_id(board, tid, 1)] = 1
for l: Variant in st.get("effects", []):
if l is Dictionary and (l as Dictionary).get("error", false):
var text := str((l as Dictionary).get("text", ""))
var ek := tid + ":" + eid + "|" + text
if not _errors.has(ek):
_errors[ek] = {"table": "%s (%s)" % [tname, tid], "table_id": tid,
"entry": _entry_label(board, tid, eid), "entry_id": eid, "text": text, "count": 0}
_errors[ek]["count"] += 1
for m in _marker_re().search_all(str(st.get("text", ""))):
var what := Formatter.strip_tags(m.get_string())
var mk := tid + ":" + eid + "|" + what
if not _markers.has(mk):
_markers[mk] = {"table": "%s (%s)" % [tname, tid], "table_id": tid,
"entry": _entry_label(board, tid, eid), "entry_id": eid, "text": what, "count": 0}
_markers[mk]["count"] += 1
if ctx.actions > int(_longest["actions"]):
var top: Array = []
for k: String in run_hits:
top.append({"table": k, "count": run_hits[k]})
top = _sorted_by_count(top).slice(0, 8)
_longest = {"actions": ctx.actions, "run": run + 1, "top": top}
if run == runs_total - 1 or (_sample_sheet == "" and ctx.halted == ""):
var sheet := Roller.last_sheet(root)
if not sheet.is_empty():
_sample_sheet = Formatter.strip_tags(str(sheet.get("summary", "")))
_sample_vars = vars.duplicate(true)
_sample_halted = ctx.halted
## The report so far (also fine mid-run, or after cancel()). Keys: runs
## (done so far), runs_planned, cancelled, start, completed, halted {reason:
## count}, actions {max, mean, p95}, longest {actions, run, top}, track,
## prompts_mean, errors [{table, table_id, entry, entry_id, text, count}],
## dead_ends [{table, table_id, text, count}], unset_markers (same shape as
## errors; unset {@var?}, missing [[table]] and failed {= expr} markers),
## unreached [table ids], unchosen {table id: [entry texts]}, unchosen_ids
## {table id: [entry ids]}, table_hits, sample_sheet, sample_vars,
## sample_halted.
func report() -> Dictionary:
var runs := maxi(1, runs_done)
var unreached: Array[String] = []
var unchosen := {}
var unchosen_ids := {}
if runs_done > 0:
for t in board.tables:
if t.kind == RollTable.KIND_VARIABLE:
continue
if not _table_hits.has(t.id):
unreached.append(t.id)
continue
var missing: Array[String] = []
var ids: Array[String] = []
for e in t.entries:
if t.kind == RollTable.KIND_ROLL and not t.can_come_up(e):
continue
if not _entry_hits.has(t.id + ":" + e.id):
missing.append(Formatter.strip_tags(e.text).substr(0, 60))
ids.append(e.id)
if not missing.is_empty():
unchosen[t.id] = missing
unchosen_ids[t.id] = ids
var sorted_actions := _actions.duplicate()
sorted_actions.sort()
var total := 0
for a in _actions:
total += a
var p95 := 0
var amax := 0
if not sorted_actions.is_empty():
p95 = sorted_actions[clampi(ceili(0.95 * sorted_actions.size()) - 1, 0, sorted_actions.size() - 1)]
amax = sorted_actions.back()
return {
"runs": runs_done,
"runs_planned": runs_total,
"cancelled": _cancelled,
"start": start,
"completed": _completed,
"halted": _halted.duplicate(),
"actions": {"max": amax, "mean": float(total) / runs, "p95": p95},
"longest": _longest.duplicate(true),
"track": _track.duplicate(true),
"prompts_mean": float(_prompts_total) / runs,
"errors": _sorted_by_count(_errors.values()),
"dead_ends": _sorted_by_count(_dead_ends.values()),
"unset_markers": _sorted_by_count(_markers.values()),
"unreached": unreached,
"unchosen": unchosen,
"unchosen_ids": unchosen_ids,
"table_hits": _table_hits.duplicate(),
"sample_sheet": _sample_sheet,
"sample_vars": _sample_vars,
"sample_halted": _sample_halted,
}
# ---------- Static checks ----------
## Problems found without rolling anything. Array of {kind, table_id,
## entry_id ("" for the card), table (display name), text}, in board order.
## kinds: expression, effect, range, cycle, missing_pipe, empty_choice, pipes,
## check (check cards: bad dice, modifier or target, missing results) and
## inputs (card inputs and pipe "with" values; see Roller.lint_inputs()).
## Items from Roller.lint_pipes() also carry its "level" when it has one
## ("error" or "hint").
static func static_checks(b: TowerBoard) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var add := func(kind: String, t: RollTable, eid: String, text: String) -> void:
out.append({"kind": kind, "table_id": t.id, "entry_id": eid, "table": Formatter.strip_tags(t.name), "text": text})
for t in b.tables:
var expr := func(what: String, src: String, eid: String = "") -> void:
if src.strip_edges() == "":
return
var err := Expr.check(src)
if err != "":
add.call("expression", t, eid, "%s \"%s\": %s" % [what, src, err])
if t.is_expr_dice():
expr.call("Dice", t.dice)
if t.is_ranged():
var rp := t.range_problems()
if rp != "":
add.call("range", t, "", rp)
match t.kind:
RollTable.KIND_LOOP:
expr.call("Loop rule", t.loop_expr)
RollTable.KIND_CHOICE:
if t.choice == "pick" and t.entries.is_empty():
add.call("empty_choice", t, "", "Choice card has no options.")
if t.choice == "number":
expr.call("Minimum", t.min_expr)
expr.call("Maximum", t.max_expr)
_check_braces(t.prompt, func(src: String) -> void: expr.call("Prompt", src))
RollTable.KIND_VARIABLE:
var init := t.initial.strip_edges()
if t.var_type == "number" and init != "" and not init.is_valid_float():
expr.call("Initial value", init)
for e in t.entries:
_check_braces(e.text, func(src: String) -> void: expr.call("Text", src, e.id))
for p in Effects.validate(e.effects):
add.call("effect", t, e.id, "Effect \"%s\": %s" % [p["src"], p["error"]])
for target in e.pipes:
if b.get_table(target) == null:
add.call("missing_pipe", t, e.id, "Pipe to a table that doesn't exist (%s)." % target)
var ce := e.count_expr(target)
if ce != "":
expr.call("Pipe count", ce, e.id)
for id in Roller.endless_cycles(b):
var t := b.get_table(id)
add.call("cycle", t, "", "Can never finish: every result leads back into an endless cycle.")
var roller: GDScript = Roller
var has_lint := false
for m in roller.get_script_method_list():
if m["name"] == "lint_pipes":
has_lint = true
if has_lint:
var lint: Variant = roller.call("lint_pipes", b)
if lint is Array:
for item: Variant in lint:
var t: RollTable = null
var eid := ""
var text := str(item)
var lkind := "pipes"
var level := ""
if item is Dictionary:
var d: Dictionary = item
t = b.get_table(str(d.get("table_id", d.get("table", ""))))
eid = str(d.get("entry_id", d.get("entry", "")))
text = str(d.get("text", d.get("message", d.get("problem", text))))
lkind = str(d.get("kind", "pipes"))
level = str(d.get("level", ""))
if t == null:
t = RollTable.new("", "")
add.call(lkind, t, eid, text)
if level != "":
out.back()["level"] = level
return out
## Calls `f(src)` for each `{= expr}` in the text.
static func _check_braces(text: String, f: Callable) -> void:
var re := RegEx.create_from_string("\\{=([^}]*)\\}")
for m in re.search_all(text):
f.call(m.get_string(1))
## Tables worth starting a test from: not variable cards, with nothing piping
## into them and nothing referencing them by [[name]]. If `last_rolled` is a
## table it comes first (even if it isn't a root). Ids in board order.
static func start_candidates(b: TowerBoard, last_rolled: String = "") -> Array[String]:
var used := {}
for t in b.tables:
for e in t.entries:
for p in e.pipes:
used[p] = true
for r in Roller.ref_targets(b, e.text):
used[r] = true
for r in Roller.ref_targets(b, t.prompt):
used[r] = true
var out: Array[String] = []
for t in b.tables:
if t.kind != RollTable.KIND_VARIABLE and not used.has(t.id):
out.append(t.id)
var lr := b.get_table(last_rolled)
if lr != null and lr.kind != RollTable.KIND_VARIABLE:
out.erase(lr.id)
out.push_front(lr.id)
return out
# ---------- Answers and report text ----------
## The simulated player's reply to a prompt request (docs/LOGIC.md section 8):
## a random option or Random for a pick (or an option matching `prefer`), a
## random number in range, a short random word for text.
static func answer(req: Dictionary, rng: RandomNumberGenerator, prefer: RegEx = null) -> Variant:
match str(req.get("kind", "pick")):
"number":
return rng.randi_range(int(req.get("min", 0)), int(req.get("max", 0)))
"text":
var letters := "abcdefghijklmnopqrstuvwxyz"
var s := ""
for k in rng.randi_range(3, 8):
s += letters[rng.randi_range(0, letters.length() - 1)]
return s.capitalize()
var options: Array = req.get("options", [])
if prefer != null:
for o: Dictionary in options:
if prefer.search(Formatter.strip_tags(str(o.get("text", "")))) != null:
return int(o["index"])
if options.is_empty():
return -1
# Random (-1) is offered beside every option.
var k := rng.randi_range(-1, options.size() - 1)
return -1 if k < 0 else int(options[k]["index"])
## True when no run hit an error, a dead end or the action limit.
static func is_clean(r: Dictionary) -> bool:
return (r["errors"] as Array).is_empty() and (r["dead_ends"] as Array).is_empty() \
and not (r["halted"] as Dictionary).has("Action limit")
## The static problems as text lines (for the CLI's --check and Copy report).
static func format_problems(problems: Array, list: int = 40) -> PackedStringArray:
var out := PackedStringArray()
out.append("Static problems: %d" % problems.size())
for k in mini(list, problems.size()):
var p: Dictionary = problems[k]
var where: String = "%s (%s)" % [p["table"], p["table_id"]]
if str(p["entry_id"]) != "":
where += ", entry " + str(p["entry_id"])
out.append(" %s: %s" % [where, p["text"]])
if problems.size() > list:
out.append(" ... and %d more" % (problems.size() - list))
return out
static func format_report(r: Dictionary, list: int = 40, show_sheet: bool = true) -> String:
var out := PackedStringArray()
var a: Dictionary = r["actions"]
out.append("Runs: %d completed: %d prompts per run: %.1f" % [r["runs"], r["completed"], r["prompts_mean"]])
var hl := PackedStringArray()
for k: String in r["halted"]:
hl.append("%s %d" % [k, r["halted"][k]])
out.append("Halted: %s" % (", ".join(hl) if not hl.is_empty() else "none"))
out.append("Actions: max %d, mean %.1f, p95 %d" % [a["max"], a["mean"], a["p95"]])
var lg: Dictionary = r.get("longest", {})
if not (lg.get("top", []) as Array).is_empty():
var parts := PackedStringArray()
for x: Dictionary in lg["top"]:
parts.append("%s %d" % [x["table"], x["count"]])
out.append("Longest run (#%d) most-rolled tables: %s" % [lg["run"], ", ".join(parts)])
var tr: Dictionary = r.get("track", {})
for name: String in tr:
var t: Dictionary = tr[name]
if int(t["n"]) == 0:
out.append("@%s: never a number" % name)
else:
out.append("@%s: min %s, mean %.1f, max %s (%d runs)" % [name, Expr.format_value(t["min"]), t["sum"] / t["n"], Expr.format_value(t["max"]), t["n"]])
_section(out, "Effect / expression errors", r["errors"], list, func(e: Dictionary) -> String:
return "%dx %s, entry \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]])
_section(out, "Dead ends (rolls that stopped)", r["dead_ends"], list, func(e: Dictionary) -> String:
return "%dx %s: %s" % [e["count"], e["table"], e["text"]])
_section(out, "Unset variables, missing tables and {= } errors in text", r["unset_markers"], list, func(e: Dictionary) -> String:
return "%dx %s, entry \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]])
var un: Array = r["unreached"]
out.append("Tables never reached: %d" % un.size())
for k in mini(list, un.size()):
out.append(" " + str(un[k]))
if un.size() > list:
out.append(" ... and %d more" % (un.size() - list))
var uc: Dictionary = r["unchosen"]
var n_entries := 0
for k: String in uc:
n_entries += (uc[k] as Array).size()
out.append("Entries never chosen: %d in %d reached tables" % [n_entries, uc.size()])
var shown := 0
for k: String in uc:
if shown >= list:
out.append(" ... and %d more tables" % (uc.size() - shown))
break
var items: Array = uc[k]
var names := PackedStringArray()
for x in mini(4, items.size()):
names.append("\"%s\"" % items[x])
out.append(" %s: %d (%s%s)" % [k, items.size(), ", ".join(names), ", ..." if items.size() > 4 else ""])
shown += 1
if show_sheet:
out.append("Sample final sheet%s:" % (" (" + str(r["sample_halted"]) + ")" if str(r["sample_halted"]) != "" else ""))
out.append(str(r["sample_sheet"]) if str(r["sample_sheet"]) != "" else " (no sheet card was reached)")
return "\n".join(out)
static func _section(out: PackedStringArray, title: String, items: Array, list: int, fmt: Callable) -> void:
out.append("%s: %d" % [title, items.size()])
for k in mini(list, items.size()):
out.append(" " + str(fmt.call(items[k])))
if items.size() > list:
out.append(" ... and %d more" % (items.size() - list))
static func _sorted_by_count(list: Array) -> Array:
var out := list.duplicate()
out.sort_custom(func(x: Dictionary, y: Dictionary) -> bool: return int(x["count"]) > int(y["count"]))
return out
static func _entry_label(b: TowerBoard, tid: String, eid: String) -> String:
var t := b.get_table(tid)
if t == null:
return eid
var e := t.find_entry(eid)
return eid if e == null else Formatter.strip_tags(e.text).substr(0, 50)
static func _loop_entry_id(b: TowerBoard, tid: String, index: int) -> String:
var t := b.get_table(tid)
if t == null or t.entries.size() <= index:
return ""
return t.entries[index].id
static var _marker: RegEx = null
static func _marker_re() -> RegEx:
if _marker == null:
_marker = RegEx.create_from_string("\\[url=(?:unset|missing|error):[^\\]]*\\][^\\[]*\\[/url\\]")
return _marker