From 82d46b927dcb026f03c961fce411ee8989a41eb6 Mon Sep 17 00:00:00 2001 From: RobinFiredrake Date: Sun, 8 Nov 2026 14:15:21 -0600 Subject: [PATCH] Add a headless board simulator tool and its test tools/simulate_board.gd rolls a collection N times with a random (or regex-preferred) player answering every choice card, each run on fresh board variables, and reports completions, halt reasons, action stats, effect/expression errors with table and entry, dead ends, unset or failed markers in text and prompts, unreached tables, never-chosen entries, tracked variable ranges, the longest run's busiest tables and a sample final sheet. tests/test_simulate.gd runs it on an inline board. Co-Authored-By: Claude Opus 5.5 --- tests/test_simulate.gd | 100 ++++++++++ tests/test_simulate.gd.uid | 1 + tools/simulate_board.gd | 366 ++++++++++++++++++++++++++++++++++++ tools/simulate_board.gd.uid | 1 + 4 files changed, 468 insertions(+) create mode 100644 tests/test_simulate.gd create mode 100644 tests/test_simulate.gd.uid create mode 100644 tools/simulate_board.gd create mode 100644 tools/simulate_board.gd.uid diff --git a/tests/test_simulate.gd b/tests/test_simulate.gd new file mode 100644 index 0000000..41b873d --- /dev/null +++ b/tests/test_simulate.gd @@ -0,0 +1,100 @@ +extends SceneTree +## Keeps tools/simulate_board.gd working: runs it on a small inline board with +## a choice, a loop, a check, a bad effect, an unreachable table and a sheet. +## Run: godot --headless --path . -s res://tests/test_simulate.gd + +const Sim := preload("res://tools/simulate_board.gd") + +var _failures := 0 + + +func _init() -> void: + var b := _board() + var r: Dictionary = await Sim.simulate(b, "start", {"runs": 60, "seed": 3, "track": ["gold", "@name"]}) + _eq(r["runs"], 60, "60 runs") + _eq(r["completed"], 60, "every run completes") + _check((r["halted"] as Dictionary).is_empty(), "nothing halted: %s" % str(r["halted"])) + var a: Dictionary = r["actions"] + _check(a["max"] >= a["p95"] and a["p95"] >= 4 and a["mean"] > 4.0, "action stats are sensible: %s" % str(a)) + var errs: Array = r["errors"] + _check(errs.size() == 1 and str(errs[0]["table"]).contains("pick") and str(errs[0]["entry"]) == "Broken", "the bad effect is reported with its table and entry: %s" % str(errs)) + _eq(r["unreached"], ["island"], "the island table is never reached") + var uc: Dictionary = r["unchosen"] + _check(not uc.has("check"), "an entry that can't come up (13 on 2d6) is not reported as unchosen: %s" % str(uc)) + _check(not uc.has("pick"), "every pick option was chosen at some point") + var sheet := str(r["sample_sheet"]) + _check(sheet.begins_with("Hero: ") and sheet.contains("Gold "), "a sample sheet is kept: %s" % sheet) + _check(not Sim.is_clean(r), "a run with an effect error is not clean") + # Each run starts with empty variables: gold never grows past one run's worth. + var gold := int((r["sample_vars"].get("gold", {}) as Dictionary).get("value", -1)) + _check(gold <= 18, "variables start clean for every run (gold %d)" % gold) + var mk: Array = r["unset_markers"] + _check(mk.size() == 1 and mk[0]["entry"] == "(prompt)" and str(mk[0]["text"]).contains("@nothing"), "an unset variable in a prompt is reported: %s" % str(mk)) + var tg: Dictionary = r["track"]["gold"] + _check(int(tg["n"]) > 0 and float(tg["max"]) <= 18.0 and float(tg["min"]) >= 0.0, "--track summarises a number variable: %s" % str(tg)) + _eq(r["track"]["name"]["n"], 0, "--track skips text variables") + var lg: Dictionary = r["longest"] + _check(int(lg["actions"]) == int(a["max"]) and not (lg["top"] as Array).is_empty(), "the longest run's busiest tables are kept: %s" % str(lg)) + # A preference picks the matching option every time. + var r2: Dictionary = await Sim.simulate(b, "start", {"runs": 20, "seed": 4, "prefer": "^Mine$"}) + _check((r2["unchosen"] as Dictionary).has("pick"), "--prefer always picks the matching option") + _check(int((r2["table_hits"] as Dictionary).get("mine", 0)) == 20 * 3, "the preferred option's pipe ran on every pass") + # The action limit is reported as a halt reason. + var r3: Dictionary = await Sim.simulate(b, "start", {"runs": 5, "seed": 5, "max_actions": 4}) + _eq((r3["halted"] as Dictionary).get("Action limit", 0), 5, "the action limit is a halt reason") + var text := Sim.format_report(r) + _check(text.contains("Runs: 60") and text.contains("Tables never reached: 1") and text.contains("Sample final sheet") and text.contains("@gold: min"), "the report prints:\n%s" % text) + print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures]) + quit(1 if _failures else 0) + + +func _board() -> TowerBoard: + var b := TowerBoard.new() + b.id = "sim-test" + var start := RollTable.new("start", "Start") + var e := TableEntry.new("e1", "Begin") + e.effects = "reset @gold; @name = \"Hero\"" + e.add_pipe("loop") + e.add_pipe("sheet") + start.entries.append(e) + var loop := RollTable.create(RollTable.KIND_LOOP, "loop", "Three times", "times") + loop.loop_expr = "3" + loop.entries[0].add_pipe("pick") + var pick := RollTable.create(RollTable.KIND_CHOICE, "pick", "Pick", "pick") + pick.prompt = "Which? {@nothing}" + pick.entries[0].text = "Mine" + pick.entries[0].effects = "@gold += 1d6" + pick.entries[0].add_pipe("mine") + pick.entries[1].text = "Check" + pick.entries[1].add_pipe("check") + pick.entries[2].text = "Broken" + pick.entries[2].effects = "@gold += nope(" + var mine := RollTable.new("mine", "Mine") + mine.entries.append(TableEntry.new("e1", "Dig")) + var check := RollTable.new("check", "Check") + check.dice = "2d6" + for spec in [[2, 7, "Fail"], [8, 12, "Pass"], [13, 13, "Impossible"]]: + var ce := TableEntry.new("c%d" % spec[0], spec[2]) + ce.has_range = true + ce.range_lo = spec[0] + ce.range_hi = spec[1] + check.entries.append(ce) + var island := RollTable.new("island", "Island") + island.entries.append(TableEntry.new("e1", "Alone")) + var sheet := RollTable.create(RollTable.KIND_SHEET, "sheet", "Sheet") + sheet.entries[0].text = "{@name}: Gold {@gold}" + var gold := RollTable.create(RollTable.KIND_VARIABLE, "v_gold", "Gold", "number") + gold.var_name = "gold" + for t in [start, loop, pick, mine, check, island, sheet, gold]: + b.tables.append(t) + return b + + +func _eq(got: Variant, want: Variant, what: String) -> void: + _check(str(got) == str(want), "%s\n got: %s\n want: %s" % [what, str(got), str(want)]) + + +func _check(ok: bool, what: String) -> void: + if not ok: + _failures += 1 + print(" ✗ ", what) diff --git a/tests/test_simulate.gd.uid b/tests/test_simulate.gd.uid new file mode 100644 index 0000000..e23785a --- /dev/null +++ b/tests/test_simulate.gd.uid @@ -0,0 +1 @@ +uid://neyn2x0o53cn diff --git a/tools/simulate_board.gd b/tools/simulate_board.gd new file mode 100644 index 0000000..323fbe0 --- /dev/null +++ b/tools/simulate_board.gd @@ -0,0 +1,366 @@ +extends SceneTree +## Rolls a collection many times headlessly, answering every choice card at +## random, and reports what happened: how many rolls finished, why the others +## stopped, how many actions they took, every effect or expression error, the +## tables and entries that were never reached, and a sample final sheet. +## +## Run: +## godot --headless --path . -s res://tools/simulate_board.gd -- \ +## --board= --start= --runs=N [--seed=S] \ +## [--prefer=] [--track=a,b] [--max-actions=N] [--list=N] [--quiet] +## +## --prefer on a pick card, choose an option whose text matches this +## regular expression (case-insensitive) whenever there is one, +## e.g. --prefer="^Continue|another career"; otherwise random. +## --list how many lines to print per section (default 40). +## --quiet leave the sample sheet out of the report. +## --track comma-separated board variables (no "@") whose final values +## are summarised over all runs (min, mean, max), e.g. +## --track=terms,age +## +## Every run starts with a fresh, empty set of board variables (its own +## persistent-vars dictionary), so runs never leak state into each other. +## The exit code is 1 when any run hit an error, the action limit, or a +## dead end ("No result for ..."), else 0. +## +## Other scripts can call simulate() and format_report() directly (see +## tests/test_simulate.gd). + + +func _init() -> void: + var args := _parse_args(OS.get_cmdline_user_args()) + var path := str(args.get("board", "")) + var start := str(args.get("start", "")) + if path == "" or start == "": + print("Usage: godot --headless --path . -s res://tools/simulate_board.gd -- --board= --start=
--runs=N [--seed=S] [--prefer=] [--track=a,b] [--max-actions=N] [--list=N] [--quiet]") + quit(2) + return + var text := FileAccess.get_file_as_string(path) + if text == "": + print("Can't read %s" % path) + quit(2) + return + var board := TowerBoard.new() + if not board.load_json(text): + print("%s is not a TableTower collection" % path) + quit(2) + return + if board.get_table(start) == null: + print("No table with id \"%s\" in %s" % [start, path]) + quit(2) + return + var opts := { + "runs": int(args.get("runs", "100")), + "seed": int(args.get("seed", "1")), + "prefer": str(args.get("prefer", "")), + "max_actions": int(args.get("max-actions", str(RollContext.DEFAULT_MAX_ACTIONS))), + "track": str(args.get("track", "")).split(",", false), + } + var report: Dictionary = await simulate(board, start, opts) + print(format_report(report, int(args.get("list", "40")), not args.has("quiet"))) + quit(0 if is_clean(report) else 1) + + +static func _parse_args(list: PackedStringArray) -> Dictionary: + var out := {} + for a in list: + if not a.begins_with("--"): + continue + var s := a.substr(2) + var eq := s.find("=") + if eq < 0: + out[s] = "true" + else: + out[s.substr(0, eq)] = s.substr(eq + 1) + return out + + +## Runs `opts.runs` top-level rolls of `start` and gathers statistics. +## opts: runs (int), seed (int), prefer (String regex, may be ""), +## max_actions (int), track (Array of variable names). Returns the report +## Dictionary that format_report() prints: +## runs, completed, halted {reason: count}, actions {max, mean, p95}, +## longest {actions, run, top: [{table, count}]} (the most-rolled tables +## of the run that took the most actions), track {name: {min, max, sum, n}}, +## prompts_mean, errors [{table, entry, text, count}], dead_ends +## [{table, text, count}], unset_markers [{table, entry, text, count}] +## (unset {@var?}, missing [[table]] and failed {= expr} markers), +## unreached [table ids], unchosen {table id: [entry texts]}, +## table_hits {table id: count}, sample_sheet (String), sample_vars +## (Dictionary), sample_halted (String) +static func simulate(board: TowerBoard, start: String, opts: Dictionary = {}) -> Dictionary: + var runs := maxi(1, int(opts.get("runs", 100))) + var rng := RandomNumberGenerator.new() + rng.seed = int(opts.get("seed", 1)) + var answer_rng := RandomNumberGenerator.new() + answer_rng.seed = rng.seed * 7919 + 17 + var prefer: RegEx = null + var pat := str(opts.get("prefer", "")) + if pat != "": + prefer = RegEx.create_from_string("(?i)" + pat) + var max_actions := int(opts.get("max_actions", RollContext.DEFAULT_MAX_ACTIONS)) + + var completed := 0 + var halted := {} + var actions: Array[int] = [] + var prompts_total := 0 + var errors := {} # key -> {table, entry, text, count} + var dead_ends := {} # key -> {table, text, count} + var markers := {} # key -> {table, entry, 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} + for name: String in opts.get("track", []): + track[name.strip_edges().trim_prefix("@")] = {"min": INF, "max": -INF, "sum": 0.0, "n": 0} + + for run in runs: + var vars := {} + 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], "entry": "(prompt)", "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], "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], "entry": _entry_label(board, tid, 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], "entry": _entry_label(board, tid, 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 - 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 + + var unreached: Array[String] = [] + var unchosen := {} + 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] = [] + 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)) + if not missing.is_empty(): + unchosen[t.id] = missing + + var sorted_actions := actions.duplicate() + sorted_actions.sort() + var total := 0 + for a in actions: + total += a + var p95: int = sorted_actions[clampi(ceili(0.95 * sorted_actions.size()) - 1, 0, sorted_actions.size() - 1)] + return { + "runs": runs, + "completed": completed, + "halted": halted, + "actions": {"max": sorted_actions.back(), "mean": float(total) / runs, "p95": p95}, + "longest": longest, + "track": track, + "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, + "table_hits": table_hits, + "sample_sheet": sample_sheet, + "sample_vars": sample_vars, + "sample_halted": sample_halted, + } + + +## The simulated player's reply to a prompt request (docs/LOGIC.md §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(report: Dictionary) -> bool: + return (report["errors"] as Array).is_empty() and (report["dead_ends"] as Array).is_empty() \ + and not (report["halted"] as Dictionary).has("Action limit") + + +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(board: TowerBoard, tid: String, eid: String) -> String: + var t := board.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(board: TowerBoard, tid: String, index: int) -> String: + var t := board.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 diff --git a/tools/simulate_board.gd.uid b/tools/simulate_board.gd.uid new file mode 100644 index 0000000..5d030c2 --- /dev/null +++ b/tools/simulate_board.gd.uid @@ -0,0 +1 @@ +uid://b4r31htjbaynj