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 (BoardChecks) ---------- ## Problems found without rolling anything (BoardChecks.static_checks lists ## the item keys and kinds). static func static_checks(board_to_check: TowerBoard) -> Array[Dictionary]: return BoardChecks.static_checks(board_to_check) ## Tables worth starting a test from (BoardChecks.start_candidates). static func start_candidates(board_to_check: TowerBoard, last_rolled: String = "") -> Array[String]: return BoardChecks.start_candidates(board_to_check, last_rolled) # ---------- 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 BoardReportText.is_clean(r) ## The static problems as text lines (BoardReportText.format_problems). static func format_problems(problems: Array, list: int = 40) -> PackedStringArray: return BoardReportText.format_problems(problems, list) ## The report as text (BoardReportText.format_report). static func format_report(r: Dictionary, list: int = 40, show_sheet: bool = true) -> String: return BoardReportText.format_report(r, list, show_sheet) 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