Test board: BoardTester class, Build-mode dialog, README section
Moves the simulator into core/board_tester.gd (static checks, sliced runs on fresh variables and decks), keeps tools/simulate_board.gd as a thin wrapper, adds the Test board dialog with a Build tools button and Board menu item. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
14a0b6e6a4
commit
be75723aef
11 changed files with 1172 additions and 290 deletions
17
README.md
17
README.md
|
|
@ -60,6 +60,21 @@ godot --path .
|
||||||
- **Moving around:** drag the felt to pan, use the mouse wheel to scroll (Shift for sideways),
|
- **Moving around:** drag the felt to pan, use the mouse wheel to scroll (Shift for sideways),
|
||||||
Ctrl+wheel or pinch to zoom, and **Fit** to see every table.
|
Ctrl+wheel or pinch to zoom, and **Fit** to see every table.
|
||||||
|
|
||||||
|
**Test board** (Build mode, top bar or **Board ▾**) rolls the board many times to find
|
||||||
|
problems before you play it. Pick a start card (by default one nothing pipes into, or the last
|
||||||
|
one you rolled), 100, 500 or 1000 runs, and whether the simulated player answers choices at
|
||||||
|
random or prefers options matching a regular expression, then **Run** (it shows progress and
|
||||||
|
can be cancelled; the app stays responsive). The report has a summary line and collapsible
|
||||||
|
lists: **Problems** (static checks: bad expressions and effects, range gaps and overlaps,
|
||||||
|
pipes to missing tables, endless cycles, choice cards with no options), **Errors** (effect and
|
||||||
|
expression errors while rolling, unset variables, runs stopped by the action limit), **Dead
|
||||||
|
ends** (rolls that stopped, such as "No result for 7"), tables **Never reached** and entries
|
||||||
|
**Never chosen**. Click any line to jump to that card (the dialog closes; reopen it to see the
|
||||||
|
same report again), **Copy report** puts it on the clipboard as text. Every run starts with
|
||||||
|
empty variables and decks of its own, so your saved variables and decks are never touched. The
|
||||||
|
logic is `core/board_tester.gd` (`BoardTester`); `tools/simulate_board.gd` is its command-line
|
||||||
|
front end (`--board=<json> --start=<id> --runs=N [--prefer=<regex>] [--check]`).
|
||||||
|
|
||||||
Collections save automatically to `user://collections/<id>.json`, and card draws, saved
|
Collections save automatically to `user://collections/<id>.json`, and card draws, saved
|
||||||
variables and roll history to `user://state/state.json` (on Linux, under
|
variables and roll history to `user://state/state.json` (on Linux, under
|
||||||
`~/.local/share/godot/app_userdata/TableTower/`). Local state is never exported.
|
`~/.local/share/godot/app_userdata/TableTower/`). Local state is never exported.
|
||||||
|
|
@ -95,6 +110,8 @@ the first questions and leaves the next pop-up open; `--menu=add`, `--open-setti
|
||||||
`--edit-effects=<id>`, `--demo-long=<n>` (a chain of n steps) and `--confirm-reset` show the
|
`--edit-effects=<id>`, `--demo-long=<n>` (a chain of n steps) and `--confirm-reset` show the
|
||||||
rest.
|
rest.
|
||||||
|
|
||||||
|
Test board: `--test-board` opens the dialog, `--test-board-run=<runs>` also starts a run.
|
||||||
|
|
||||||
Groups and templates: `--select=<id>,<id>`, `--group-selected[=<name>]`, `--collapse-groups`,
|
Groups and templates: `--select=<id>,<id>`, `--group-selected[=<name>]`, `--collapse-groups`,
|
||||||
`--expand-groups`, `--toggle-group=<id>`, `--group-menu`, `--drag-demo`, `--templates[=<search>]`,
|
`--expand-groups`, `--toggle-group=<id>`, `--group-menu`, `--drag-demo`, `--templates[=<search>]`,
|
||||||
`--insert-form=builtin:2d-check`, `--insert-template=<id> --template-values=skill=pilot|target=8`,
|
`--insert-form=builtin:2d-check`, `--insert-template=<id> --template-values=skill=pilot|target=8`,
|
||||||
|
|
|
||||||
493
core/board_tester.gd
Normal file
493
core/board_tester.gd
Normal file
|
|
@ -0,0 +1,493 @@
|
||||||
|
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.
|
||||||
|
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)
|
||||||
|
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))))
|
||||||
|
if t == null:
|
||||||
|
t = RollTable.new("", "")
|
||||||
|
add.call("pipes", t, eid, text)
|
||||||
|
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
|
||||||
1
core/board_tester.gd.uid
Normal file
1
core/board_tester.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
uid://cp8dbh87laugr
|
||||||
213
tests/test_board_tester.gd
Normal file
213
tests/test_board_tester.gd
Normal file
|
|
@ -0,0 +1,213 @@
|
||||||
|
extends SceneTree
|
||||||
|
## BoardTester: static checks, simulated runs, isolation from the caller's
|
||||||
|
## variables and decks, batches, start-table detection, and the Test board
|
||||||
|
## dialog driven through its methods.
|
||||||
|
## Run: godot --headless --path . -s res://tests/test_board_tester.gd
|
||||||
|
|
||||||
|
var _failures := 0
|
||||||
|
|
||||||
|
|
||||||
|
## Stands in for Main: just enough for the dialog.
|
||||||
|
class FakeMain extends Control:
|
||||||
|
var data: TowerBoard
|
||||||
|
var history: Array = []
|
||||||
|
var focused: Array = []
|
||||||
|
|
||||||
|
func focus_table(table_id: String, entry_id: String = "") -> void:
|
||||||
|
focused.append([table_id, entry_id])
|
||||||
|
|
||||||
|
|
||||||
|
func _init() -> void:
|
||||||
|
var b := _board()
|
||||||
|
|
||||||
|
# ----- Static checks -----
|
||||||
|
var probs := BoardTester.static_checks(b)
|
||||||
|
_check(_has(probs, "effect", "start", "e1"), "a bad effect is found with its table and entry: %s" % str(probs))
|
||||||
|
_check(_has(probs, "expression", "badexpr", ""), "a bad dice expression is found")
|
||||||
|
_check(_has(probs, "expression", "pick", "") and _text_has(probs, "Prompt"), "a bad {= } in a prompt is found")
|
||||||
|
_check(_has(probs, "expression", "loop", "") and _text_has(probs, "Loop rule"), "a bad loop rule is found")
|
||||||
|
_check(_has(probs, "expression", "start", "e1") and _text_has(probs, "Pipe count"), "a bad pipe count is found")
|
||||||
|
_check(_has(probs, "range", "gap", "") and _text_has(probs, "No result for 3"), "a range gap is found")
|
||||||
|
_check(_has(probs, "missing_pipe", "start", "e1"), "a pipe to a missing table is found")
|
||||||
|
_check(_has(probs, "empty_choice", "empty", ""), "a choice card with no options is found")
|
||||||
|
_check(_has(probs, "cycle", "ping", ""), "an endless cycle is found")
|
||||||
|
_check(not _has(probs, "range", "okrange", "") and not _has(probs, "effect", "mine", ""), "good cards give no problems")
|
||||||
|
|
||||||
|
# ----- Simulation -----
|
||||||
|
var caller_vars := {"gold": {"value": 99, "source": "x"}}
|
||||||
|
var r: Dictionary = await BoardTester.simulate(b, "start", {"runs": 80, "seed": 2, "prefer": "^Gap$"})
|
||||||
|
_eq(r["runs"], 80, "80 runs done")
|
||||||
|
_check((r["dead_ends"] as Array).size() >= 1 and str(r["dead_ends"][0]["text"]).contains("No result for 3") and r["dead_ends"][0]["table_id"] == "gap",
|
||||||
|
"the dead end names its table: %s" % str(r["dead_ends"]))
|
||||||
|
_check((r["unreached"] as Array).has("island") and not (r["unreached"] as Array).has("start"), "the island is never reached: %s" % str(r["unreached"]))
|
||||||
|
_check((r["errors"] as Array).size() >= 1 and r["errors"][0]["table_id"] == "start" and r["errors"][0]["entry_id"] == "e1" and str(r["errors"][0]["text"]).contains("nope"),
|
||||||
|
"the runtime error has table and entry ids: %s" % str(r["errors"]))
|
||||||
|
_check(r["actions"]["max"] >= r["actions"]["p95"] and r["prompts_mean"] > 0.0, "action and prompt stats exist")
|
||||||
|
_check(not BoardTester.is_clean(r), "not clean")
|
||||||
|
# A starting vars dictionary is copied for every run, never changed.
|
||||||
|
var r2: Dictionary = await BoardTester.simulate(b, "start", {"runs": 5, "seed": 3, "vars": caller_vars})
|
||||||
|
_eq(caller_vars["gold"]["value"], 99, "the caller's variables are untouched")
|
||||||
|
_eq(caller_vars.size(), 1, "no variables were added to the caller's dictionary")
|
||||||
|
_eq(r2["runs"], 5, "runs with a starting vars copy")
|
||||||
|
|
||||||
|
# ----- Batches -----
|
||||||
|
var t := BoardTester.new(b, "start", {"runs": 25, "seed": 4})
|
||||||
|
var did := 0
|
||||||
|
var calls := 0
|
||||||
|
while not t.is_done():
|
||||||
|
did += await t.run_batch(7)
|
||||||
|
calls += 1
|
||||||
|
_eq(did, 25, "batches add up to the planned runs")
|
||||||
|
_eq(calls, 4, "25 runs in slices of 7 is 4 calls")
|
||||||
|
_eq(t.report()["runs"], 25, "report counts all runs")
|
||||||
|
var whole: Dictionary = await BoardTester.simulate(b, "start", {"runs": 25, "seed": 4})
|
||||||
|
_eq(whole["completed"], t.report()["completed"], "sliced and whole runs agree (same seed)")
|
||||||
|
_eq(whole["actions"], t.report()["actions"], "same action stats")
|
||||||
|
var t2 := BoardTester.new(b, "start", {"runs": 100, "seed": 5})
|
||||||
|
await t2.run_batch(10)
|
||||||
|
t2.cancel()
|
||||||
|
_check(t2.is_done() and t2.report()["runs"] == 10 and t2.report()["cancelled"], "cancel stops after the finished slice")
|
||||||
|
_eq(await t2.run_batch(5), 0, "no runs after cancel")
|
||||||
|
|
||||||
|
# ----- Start tables -----
|
||||||
|
var starts := BoardTester.start_candidates(b)
|
||||||
|
_check(starts.has("start") and starts.has("island") and starts.has("badexpr") and not starts.has("gap") and not starts.has("pick") and not starts.has("v_gold"),
|
||||||
|
"start candidates are roots without variable cards: %s" % str(starts))
|
||||||
|
_check(not starts.has("mine"), "a table referenced as [[Mine]] is not a root: %s" % str(starts))
|
||||||
|
_check(BoardTester.start_candidates(b, "gap")[0] == "gap", "the last rolled table comes first")
|
||||||
|
_check(not BoardTester.start_candidates(b, "v_gold").has("v_gold"), "a variable card is never offered")
|
||||||
|
|
||||||
|
# ----- Dialog -----
|
||||||
|
var fm := FakeMain.new()
|
||||||
|
fm.data = b
|
||||||
|
root.add_child(fm)
|
||||||
|
var d := TestBoardDialog.new(fm)
|
||||||
|
fm.add_child(d)
|
||||||
|
await process_frame
|
||||||
|
_eq(d.selected_start(), "start", "the dialog defaults to the first root")
|
||||||
|
d.runs = 100
|
||||||
|
d.run_test()
|
||||||
|
var frames := 0
|
||||||
|
while d.running and frames < 400:
|
||||||
|
await process_frame
|
||||||
|
frames += 1
|
||||||
|
_check(not d.running, "the run finishes")
|
||||||
|
_check(d.sections.has("Problems") and d.sections["Problems"]["count"] >= 6, "problems section filled")
|
||||||
|
_check(d.sections["Errors"]["count"] >= 1, "errors section filled")
|
||||||
|
_check(d.sections["Dead ends"]["count"] >= 1, "dead ends section filled")
|
||||||
|
_check(d.sections["Never reached"]["count"] >= 1, "never reached section filled")
|
||||||
|
_check(d.sections.has("Never chosen"), "never chosen section exists")
|
||||||
|
_check(d.summary.text.begins_with("100 runs · ") and d.summary.text.contains("never reached"), "summary line: %s" % d.summary.text)
|
||||||
|
_check(d.report_text().contains("Static problems:") and d.report_text().contains("Dead ends"), "report text can be copied")
|
||||||
|
var first_summary := d.summary.text
|
||||||
|
d.click_item("gap", "")
|
||||||
|
_eq(fm.focused, [["gap", ""]], "clicking an item calls focus_table")
|
||||||
|
await process_frame
|
||||||
|
await process_frame
|
||||||
|
# Reopening shows the last report.
|
||||||
|
var d2 := TestBoardDialog.new(fm)
|
||||||
|
fm.add_child(d2)
|
||||||
|
await process_frame
|
||||||
|
_check(d2.sections.has("Problems") and d2.summary.text == first_summary, "the last report is shown again on reopen")
|
||||||
|
# Cancel mid-run.
|
||||||
|
d2.runs = 1000
|
||||||
|
d2.run_test()
|
||||||
|
await process_frame
|
||||||
|
d2.cancel_run()
|
||||||
|
frames = 0
|
||||||
|
while d2.running and frames < 400:
|
||||||
|
await process_frame
|
||||||
|
frames += 1
|
||||||
|
_check(not d2.running and d2.summary.text.begins_with("Cancelled after"), "cancelled run reports it: %s" % d2.summary.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 = "bt"
|
||||||
|
b.name = "Tester"
|
||||||
|
var start := RollTable.new("start", "Start")
|
||||||
|
var e := TableEntry.new("e1", "Begin")
|
||||||
|
e.effects = "@gold += nope("
|
||||||
|
e.add_pipe("pick")
|
||||||
|
e.add_pipe("nowhere")
|
||||||
|
e.add_pipe("loop", "2 +")
|
||||||
|
start.entries.append(e)
|
||||||
|
var pick := RollTable.create(RollTable.KIND_CHOICE, "pick", "Pick", "pick")
|
||||||
|
pick.prompt = "Which? {= 1 + }"
|
||||||
|
pick.entries[0].text = "Gap"
|
||||||
|
pick.entries[0].add_pipe("gap")
|
||||||
|
pick.entries[1].text = "Fine"
|
||||||
|
pick.entries[1].add_pipe("ok")
|
||||||
|
pick.entries[2].text = "Dig in [[Mine]]"
|
||||||
|
var gap := RollTable.new("gap", "Gap")
|
||||||
|
gap.dice = "1d6"
|
||||||
|
for spec in [[1, 2, "Low"], [4, 6, "High"]]:
|
||||||
|
var ge := TableEntry.new("g%d" % spec[0], spec[2])
|
||||||
|
ge.has_range = true
|
||||||
|
ge.range_lo = spec[0]
|
||||||
|
ge.range_hi = spec[1]
|
||||||
|
gap.entries.append(ge)
|
||||||
|
var ok := RollTable.new("ok", "Fine")
|
||||||
|
ok.entries.append(TableEntry.new("e1", "All good"))
|
||||||
|
var mine := RollTable.new("mine", "Mine")
|
||||||
|
mine.entries.append(TableEntry.new("e1", "Dig"))
|
||||||
|
var island := RollTable.new("island", "Island")
|
||||||
|
island.entries.append(TableEntry.new("e1", "Alone"))
|
||||||
|
var bad := RollTable.new("badexpr", "Bad dice")
|
||||||
|
bad.dice = "2d6 +"
|
||||||
|
var be := TableEntry.new("b1", "X")
|
||||||
|
be.has_range = true
|
||||||
|
be.range_lo = 2
|
||||||
|
be.range_hi = 12
|
||||||
|
bad.entries.append(be)
|
||||||
|
var loop := RollTable.create(RollTable.KIND_LOOP, "loop", "Loop", "times")
|
||||||
|
loop.loop_expr = "3 *"
|
||||||
|
var empty := RollTable.create(RollTable.KIND_CHOICE, "empty", "Empty", "pick")
|
||||||
|
empty.entries.clear()
|
||||||
|
var ping := RollTable.new("ping", "Ping")
|
||||||
|
var pe := TableEntry.new("e1", "to pong")
|
||||||
|
pe.add_pipe("pong")
|
||||||
|
ping.entries.append(pe)
|
||||||
|
var pong := RollTable.new("pong", "Pong")
|
||||||
|
var po := TableEntry.new("e1", "to ping")
|
||||||
|
po.add_pipe("ping")
|
||||||
|
pong.entries.append(po)
|
||||||
|
var good := RollTable.new("okrange", "Fine range")
|
||||||
|
good.dice = "1d6"
|
||||||
|
var gr := TableEntry.new("r1", "All")
|
||||||
|
gr.has_range = true
|
||||||
|
gr.range_lo = 1
|
||||||
|
gr.range_hi = 6
|
||||||
|
good.entries.append(gr)
|
||||||
|
var gold := RollTable.create(RollTable.KIND_VARIABLE, "v_gold", "Gold", "number")
|
||||||
|
gold.var_name = "gold"
|
||||||
|
for tb in [start, pick, gap, ok, mine, island, bad, loop, empty, ping, pong, good, gold]:
|
||||||
|
b.tables.append(tb)
|
||||||
|
return b
|
||||||
|
|
||||||
|
|
||||||
|
func _has(probs: Array, kind: String, tid: String, eid: String) -> bool:
|
||||||
|
for p: Dictionary in probs:
|
||||||
|
if p["kind"] == kind and p["table_id"] == tid and (eid == "" or p["entry_id"] == eid):
|
||||||
|
return true
|
||||||
|
return false
|
||||||
|
|
||||||
|
|
||||||
|
func _text_has(probs: Array, s: String) -> bool:
|
||||||
|
for p: Dictionary in probs:
|
||||||
|
if str(p["text"]).contains(s):
|
||||||
|
return true
|
||||||
|
return false
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
1
tests/test_board_tester.gd.uid
Normal file
1
tests/test_board_tester.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
uid://bv60dpluysjlk
|
||||||
|
|
@ -1,16 +1,14 @@
|
||||||
extends SceneTree
|
extends SceneTree
|
||||||
## Keeps tools/simulate_board.gd working: runs it on a small inline board with
|
## Keeps the simulator (BoardTester, and its CLI 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.
|
## 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
|
## Run: godot --headless --path . -s res://tests/test_simulate.gd
|
||||||
|
|
||||||
const Sim := preload("res://tools/simulate_board.gd")
|
|
||||||
|
|
||||||
var _failures := 0
|
var _failures := 0
|
||||||
|
|
||||||
|
|
||||||
func _init() -> void:
|
func _init() -> void:
|
||||||
var b := _board()
|
var b := _board()
|
||||||
var r: Dictionary = await Sim.simulate(b, "start", {"runs": 60, "seed": 3, "track": ["gold", "@name"]})
|
var r: Dictionary = await BoardTester.simulate(b, "start", {"runs": 60, "seed": 3, "track": ["gold", "@name"]})
|
||||||
_eq(r["runs"], 60, "60 runs")
|
_eq(r["runs"], 60, "60 runs")
|
||||||
_eq(r["completed"], 60, "every run completes")
|
_eq(r["completed"], 60, "every run completes")
|
||||||
_check((r["halted"] as Dictionary).is_empty(), "nothing halted: %s" % str(r["halted"]))
|
_check((r["halted"] as Dictionary).is_empty(), "nothing halted: %s" % str(r["halted"]))
|
||||||
|
|
@ -24,7 +22,7 @@ func _init() -> void:
|
||||||
_check(not uc.has("pick"), "every pick option was chosen at some point")
|
_check(not uc.has("pick"), "every pick option was chosen at some point")
|
||||||
var sheet := str(r["sample_sheet"])
|
var sheet := str(r["sample_sheet"])
|
||||||
_check(sheet.begins_with("Hero: ") and sheet.contains("Gold "), "a sample sheet is kept: %s" % 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")
|
_check(not BoardTester.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.
|
# 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))
|
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)
|
_check(gold <= 18, "variables start clean for every run (gold %d)" % gold)
|
||||||
|
|
@ -36,13 +34,13 @@ func _init() -> void:
|
||||||
var lg: Dictionary = r["longest"]
|
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))
|
_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.
|
# A preference picks the matching option every time.
|
||||||
var r2: Dictionary = await Sim.simulate(b, "start", {"runs": 20, "seed": 4, "prefer": "^Mine$"})
|
var r2: Dictionary = await BoardTester.simulate(b, "start", {"runs": 20, "seed": 4, "prefer": "^Mine$"})
|
||||||
_check((r2["unchosen"] as Dictionary).has("pick"), "--prefer always picks the matching option")
|
_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")
|
_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.
|
# The action limit is reported as a halt reason.
|
||||||
var r3: Dictionary = await Sim.simulate(b, "start", {"runs": 5, "seed": 5, "max_actions": 4})
|
var r3: Dictionary = await BoardTester.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")
|
_eq((r3["halted"] as Dictionary).get("Action limit", 0), 5, "the action limit is a halt reason")
|
||||||
var text := Sim.format_report(r)
|
var text := BoardTester.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)
|
_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])
|
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
|
||||||
quit(1 if _failures else 0)
|
quit(1 if _failures else 0)
|
||||||
|
|
|
||||||
|
|
@ -22,9 +22,10 @@ extends SceneTree
|
||||||
## persistent-vars dictionary), so runs never leak state into each other.
|
## 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
|
## The exit code is 1 when any run hit an error, the action limit, or a
|
||||||
## dead end ("No result for ..."), else 0.
|
## dead end ("No result for ..."), else 0.
|
||||||
|
## --check also print the static checks (BoardTester.static_checks).
|
||||||
##
|
##
|
||||||
## Other scripts can call simulate() and format_report() directly (see
|
## A thin wrapper around BoardTester (core/board_tester.gd); simulate(),
|
||||||
## tests/test_simulate.gd).
|
## answer(), is_clean() and format_report() forward to it.
|
||||||
|
|
||||||
|
|
||||||
func _init() -> void:
|
func _init() -> void:
|
||||||
|
|
@ -32,7 +33,7 @@ func _init() -> void:
|
||||||
var path := str(args.get("board", ""))
|
var path := str(args.get("board", ""))
|
||||||
var start := str(args.get("start", ""))
|
var start := str(args.get("start", ""))
|
||||||
if path == "" or start == "":
|
if path == "" or start == "":
|
||||||
print("Usage: godot --headless --path . -s res://tools/simulate_board.gd -- --board=<json> --start=<table id> --runs=N [--seed=S] [--prefer=<regex>] [--track=a,b] [--max-actions=N] [--list=N] [--quiet]")
|
print("Usage: godot --headless --path . -s res://tools/simulate_board.gd -- --board=<json> --start=<table id> --runs=N [--seed=S] [--prefer=<regex>] [--track=a,b] [--max-actions=N] [--list=N] [--quiet] [--check]")
|
||||||
quit(2)
|
quit(2)
|
||||||
return
|
return
|
||||||
var text := FileAccess.get_file_as_string(path)
|
var text := FileAccess.get_file_as_string(path)
|
||||||
|
|
@ -58,6 +59,8 @@ func _init() -> void:
|
||||||
}
|
}
|
||||||
var report: Dictionary = await simulate(board, start, opts)
|
var report: Dictionary = await simulate(board, start, opts)
|
||||||
print(format_report(report, int(args.get("list", "40")), not args.has("quiet")))
|
print(format_report(report, int(args.get("list", "40")), not args.has("quiet")))
|
||||||
|
if args.has("check"):
|
||||||
|
print("\n".join(BoardTester.format_problems(BoardTester.static_checks(board), int(args.get("list", "40")))))
|
||||||
quit(0 if is_clean(report) else 1)
|
quit(0 if is_clean(report) else 1)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -75,292 +78,17 @@ static func _parse_args(list: PackedStringArray) -> Dictionary:
|
||||||
return out
|
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:
|
static func simulate(board: TowerBoard, start: String, opts: Dictionary = {}) -> Dictionary:
|
||||||
var runs := maxi(1, int(opts.get("runs", 100)))
|
return await BoardTester.simulate(board, start, opts)
|
||||||
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:
|
static func answer(req: Dictionary, rng: RandomNumberGenerator, prefer: RegEx = null) -> Variant:
|
||||||
match str(req.get("kind", "pick")):
|
return BoardTester.answer(req, rng, prefer)
|
||||||
"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:
|
static func is_clean(report: Dictionary) -> bool:
|
||||||
return (report["errors"] as Array).is_empty() and (report["dead_ends"] as Array).is_empty() \
|
return BoardTester.is_clean(report)
|
||||||
and not (report["halted"] as Dictionary).has("Action limit")
|
|
||||||
|
|
||||||
|
|
||||||
static func format_report(r: Dictionary, list: int = 40, show_sheet: bool = true) -> String:
|
static func format_report(r: Dictionary, list: int = 40, show_sheet: bool = true) -> String:
|
||||||
var out := PackedStringArray()
|
return BoardTester.format_report(r, list, show_sheet)
|
||||||
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
|
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ extends MenuButton
|
||||||
|
|
||||||
const ID_RESET := 1
|
const ID_RESET := 1
|
||||||
const ID_IMPORT := 2
|
const ID_IMPORT := 2
|
||||||
|
const ID_TEST := 3
|
||||||
const ID_EXPORT := 100
|
const ID_EXPORT := 100
|
||||||
|
|
||||||
## Export formats: label, file extension, FileDialog filter.
|
## Export formats: label, file extension, FileDialog filter.
|
||||||
|
|
@ -27,6 +28,7 @@ const IMPORT_FILTERS: Array[String] = [
|
||||||
signal reset_requested
|
signal reset_requested
|
||||||
signal import_requested
|
signal import_requested
|
||||||
signal export_requested(format: Dictionary)
|
signal export_requested(format: Dictionary)
|
||||||
|
signal test_requested
|
||||||
|
|
||||||
|
|
||||||
func setup(can_reset: bool, can_import: bool) -> void:
|
func setup(can_reset: bool, can_import: bool) -> void:
|
||||||
|
|
@ -44,6 +46,7 @@ func setup(can_reset: bool, can_import: bool) -> void:
|
||||||
var pm := get_popup()
|
var pm := get_popup()
|
||||||
ModalCard.style_popup(pm)
|
ModalCard.style_popup(pm)
|
||||||
pm.add_item("Reset sample", ID_RESET)
|
pm.add_item("Reset sample", ID_RESET)
|
||||||
|
pm.add_item("Test board…", ID_TEST)
|
||||||
pm.add_separator("Import")
|
pm.add_separator("Import")
|
||||||
pm.add_item("Import as new collection…", ID_IMPORT)
|
pm.add_item("Import as new collection…", ID_IMPORT)
|
||||||
pm.set_item_disabled(pm.get_item_index(ID_IMPORT), not can_import)
|
pm.set_item_disabled(pm.get_item_index(ID_IMPORT), not can_import)
|
||||||
|
|
@ -53,6 +56,8 @@ func setup(can_reset: bool, can_import: bool) -> void:
|
||||||
pm.id_pressed.connect(func(id: int) -> void:
|
pm.id_pressed.connect(func(id: int) -> void:
|
||||||
if id == ID_RESET:
|
if id == ID_RESET:
|
||||||
reset_requested.emit()
|
reset_requested.emit()
|
||||||
|
elif id == ID_TEST:
|
||||||
|
test_requested.emit()
|
||||||
elif id == ID_IMPORT:
|
elif id == ID_IMPORT:
|
||||||
import_requested.emit()
|
import_requested.emit()
|
||||||
elif id >= ID_EXPORT and id < ID_EXPORT + EXPORTS.size():
|
elif id >= ID_EXPORT and id < ID_EXPORT + EXPORTS.size():
|
||||||
|
|
|
||||||
28
ui/main.gd
28
ui/main.gd
|
|
@ -212,8 +212,13 @@ func _build_top_bar() -> Control:
|
||||||
_board_menu.setup(true, collections_enabled())
|
_board_menu.setup(true, collections_enabled())
|
||||||
_board_menu.reset_requested.connect(reset_sample)
|
_board_menu.reset_requested.connect(reset_sample)
|
||||||
_board_menu.import_requested.connect(import_collection)
|
_board_menu.import_requested.connect(import_collection)
|
||||||
|
_board_menu.test_requested.connect(open_test_board)
|
||||||
_board_menu.export_requested.connect(export_collection)
|
_board_menu.export_requested.connect(export_collection)
|
||||||
tools.add_child(_board_menu)
|
tools.add_child(_board_menu)
|
||||||
|
var test_btn := Style.bar_button("Test board…")
|
||||||
|
test_btn.tooltip_text = "Roll the board many times and look for problems"
|
||||||
|
test_btn.pressed.connect(open_test_board)
|
||||||
|
tools.add_child(test_btn)
|
||||||
tools.visible = false
|
tools.visible = false
|
||||||
h.add_child(tools)
|
h.add_child(tools)
|
||||||
|
|
||||||
|
|
@ -1622,6 +1627,7 @@ func _run_cli(args: PackedStringArray) -> void:
|
||||||
if roll != "":
|
if roll != "":
|
||||||
start_roll(roll, args.has("--fast"))
|
start_roll(roll, args.has("--fast"))
|
||||||
_run_cli_extras(args)
|
_run_cli_extras(args)
|
||||||
|
_run_test_board_cli(args)
|
||||||
var shot := _arg_value(args, "--screenshot")
|
var shot := _arg_value(args, "--screenshot")
|
||||||
if shot == "":
|
if shot == "":
|
||||||
return
|
return
|
||||||
|
|
@ -2404,3 +2410,25 @@ func _run_cli_extras(args: PackedStringArray) -> void:
|
||||||
await get_tree().process_frame
|
await get_tree().process_frame
|
||||||
details().show_table(card, det)
|
details().show_table(card, det)
|
||||||
details().pin(card.get_global_rect().position + Vector2(60, 46))
|
details().pin(card.get_global_rect().position + Vector2(60, 46))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Test board ----------
|
||||||
|
|
||||||
|
## Build: opens the Test board dialog (core/board_tester.gd), which keeps its
|
||||||
|
## last report while the app is open.
|
||||||
|
func open_test_board() -> void:
|
||||||
|
_add_modal(TestBoardDialog.new(self))
|
||||||
|
|
||||||
|
|
||||||
|
# --test-board open the Test board dialog (shows the last report if any)
|
||||||
|
# --test-board-run=<runs> ... and start a test with that many runs (100, 500 or 1000)
|
||||||
|
func _run_test_board_cli(args: PackedStringArray) -> void:
|
||||||
|
var n := _arg_value(args, "--test-board-run")
|
||||||
|
if not args.has("--test-board") and n == "":
|
||||||
|
return
|
||||||
|
set_mode(Mode.BUILD)
|
||||||
|
var d := TestBoardDialog.new(self)
|
||||||
|
_add_modal(d)
|
||||||
|
if n != "":
|
||||||
|
d.runs = n.to_int()
|
||||||
|
d.run_test()
|
||||||
|
|
|
||||||
397
ui/test_board_dialog.gd
Normal file
397
ui/test_board_dialog.gd
Normal file
|
|
@ -0,0 +1,397 @@
|
||||||
|
class_name TestBoardDialog
|
||||||
|
extends ModalCard
|
||||||
|
## Build mode's "Test board": pick a start card, a number of runs and how the
|
||||||
|
## simulated player answers, run BoardTester in slices (a progress bar, and
|
||||||
|
## Cancel), then read the report: a summary line and collapsible sections for
|
||||||
|
## the static Problems, runtime Errors, Dead ends, tables Never reached and
|
||||||
|
## entries Never chosen. Every item jumps to its card. The last report is kept
|
||||||
|
## while the app is open and shown again when the dialog is reopened.
|
||||||
|
|
||||||
|
const RUN_CHOICES: Array[int] = [100, 500, 1000]
|
||||||
|
const SECTION_CAP := 60
|
||||||
|
## Roughly how long one slice of runs may take before the UI gets a frame.
|
||||||
|
const SLICE_MSEC := 25
|
||||||
|
|
||||||
|
## The last finished (or cancelled) test: {board, report, problems, text}.
|
||||||
|
static var last: Dictionary = {}
|
||||||
|
|
||||||
|
var main: Node
|
||||||
|
var board: TowerBoard
|
||||||
|
|
||||||
|
var start_pick: OptionButton
|
||||||
|
var prefer_edit: LineEdit
|
||||||
|
var run_button: Button
|
||||||
|
var copy_button: Button
|
||||||
|
var progress: ProgressBar
|
||||||
|
var status: Label
|
||||||
|
var summary: Label
|
||||||
|
var report_box: VBoxContainer
|
||||||
|
## Section name -> {"header": Button, "box": VBoxContainer, "count": int}
|
||||||
|
var sections: Dictionary = {}
|
||||||
|
var runs := 100
|
||||||
|
var use_prefer := false
|
||||||
|
var running := false
|
||||||
|
var tester: BoardTester = null
|
||||||
|
|
||||||
|
var _options_box: Control
|
||||||
|
var _progress_row: Control
|
||||||
|
var _report_text := ""
|
||||||
|
|
||||||
|
|
||||||
|
## `p_main` is the Main node (it has `data`, `card_for()`, `board` and, when
|
||||||
|
## present, `focus_table()`).
|
||||||
|
func _init(p_main: Node = null) -> void:
|
||||||
|
super._init("Test board", 640.0)
|
||||||
|
main = p_main
|
||||||
|
board = p_main.get("data") if p_main != null else null
|
||||||
|
_build()
|
||||||
|
|
||||||
|
|
||||||
|
func _ready() -> void:
|
||||||
|
super._ready()
|
||||||
|
if not last.is_empty() and last.get("board") == board:
|
||||||
|
_show_report(last["report"], last["problems"])
|
||||||
|
|
||||||
|
|
||||||
|
func _build() -> void:
|
||||||
|
_options_box = VBoxContainer.new()
|
||||||
|
(_options_box as VBoxContainer).add_theme_constant_override("separation", 10)
|
||||||
|
body.add_child(_options_box)
|
||||||
|
_options_box.add_child(note("Rolls a card many times, answering every choice at random, and reports problems, dead ends and what never came up. Your saved variables and decks are not touched."))
|
||||||
|
|
||||||
|
start_pick = OptionButton.new()
|
||||||
|
start_pick.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.DASH))
|
||||||
|
start_pick.add_theme_stylebox_override("hover", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.COPPER))
|
||||||
|
start_pick.add_theme_stylebox_override("pressed", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.COPPER))
|
||||||
|
start_pick.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.COPPER))
|
||||||
|
for c in ["font_color", "font_hover_color", "font_pressed_color", "font_focus_color", "font_hover_pressed_color"]:
|
||||||
|
start_pick.add_theme_color_override(c, Style.INK)
|
||||||
|
start_pick.add_theme_font_size_override("font_size", 16)
|
||||||
|
start_pick.clip_text = true
|
||||||
|
start_pick.fit_to_longest_item = false
|
||||||
|
start_pick.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||||
|
style_popup(start_pick.get_popup())
|
||||||
|
_fill_starts()
|
||||||
|
_options_box.add_child(field("Start from", start_pick))
|
||||||
|
|
||||||
|
var row := HBoxContainer.new()
|
||||||
|
row.add_theme_constant_override("separation", 18)
|
||||||
|
row.add_child(field("Runs", segmented(RUN_CHOICES.map(func(n: int) -> String: return str(n)), 0,
|
||||||
|
func(i: int) -> void: runs = RUN_CHOICES[i])))
|
||||||
|
row.add_child(field("Answers", segmented(["Random", "Prefer options matching…"], 0, func(i: int) -> void:
|
||||||
|
use_prefer = i == 1
|
||||||
|
prefer_edit.visible = use_prefer
|
||||||
|
if use_prefer:
|
||||||
|
prefer_edit.grab_focus()
|
||||||
|
)))
|
||||||
|
_options_box.add_child(row)
|
||||||
|
prefer_edit = LineEdit.new()
|
||||||
|
prefer_edit.placeholder_text = "Regular expression, e.g. ^Continue|another career"
|
||||||
|
style_line_edit(prefer_edit)
|
||||||
|
prefer_edit.visible = false
|
||||||
|
_options_box.add_child(prefer_edit)
|
||||||
|
|
||||||
|
_progress_row = VBoxContainer.new()
|
||||||
|
_progress_row.visible = false
|
||||||
|
progress = ProgressBar.new()
|
||||||
|
progress.show_percentage = false
|
||||||
|
progress.custom_minimum_size = Vector2(0, 12)
|
||||||
|
progress.add_theme_stylebox_override("background", Style.box(Color(0, 0, 0, 0.12), 6))
|
||||||
|
progress.add_theme_stylebox_override("fill", Style.box(Style.FELT, 6))
|
||||||
|
_progress_row.add_child(progress)
|
||||||
|
status = note("")
|
||||||
|
_progress_row.add_child(status)
|
||||||
|
body.add_child(_progress_row)
|
||||||
|
|
||||||
|
summary = Style.make_label("", Style.body_bold(), 17, Style.INK)
|
||||||
|
summary.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||||
|
summary.visible = false
|
||||||
|
body.add_child(summary)
|
||||||
|
report_box = VBoxContainer.new()
|
||||||
|
report_box.add_theme_constant_override("separation", 6)
|
||||||
|
body.add_child(report_box)
|
||||||
|
|
||||||
|
add_button("Close", "plain", close)
|
||||||
|
copy_button = add_button("Copy report", "plain", copy_report)
|
||||||
|
copy_button.disabled = true
|
||||||
|
run_button = add_button("Run", "primary", _on_run_pressed)
|
||||||
|
|
||||||
|
|
||||||
|
func _fill_starts() -> void:
|
||||||
|
start_pick.clear()
|
||||||
|
if board == null:
|
||||||
|
return
|
||||||
|
var last_rolled := ""
|
||||||
|
if main != null and main.get("history") is Array and not (main.get("history") as Array).is_empty():
|
||||||
|
var rec: Variant = (main.get("history") as Array)[0]
|
||||||
|
if rec is Dictionary:
|
||||||
|
last_rolled = str((rec as Dictionary).get("root", ""))
|
||||||
|
var ids := BoardTester.start_candidates(board, last_rolled)
|
||||||
|
var roots := ids.size()
|
||||||
|
for t in board.tables:
|
||||||
|
if t.kind != RollTable.KIND_VARIABLE and not ids.has(t.id):
|
||||||
|
ids.append(t.id)
|
||||||
|
for k in ids.size():
|
||||||
|
var t := board.get_table(ids[k])
|
||||||
|
start_pick.add_item("%s (%s)%s" % [Formatter.strip_tags(t.name), t.id, "" if k < roots else " - piped into"])
|
||||||
|
start_pick.set_item_metadata(k, t.id)
|
||||||
|
if start_pick.item_count > 0:
|
||||||
|
start_pick.select(0)
|
||||||
|
|
||||||
|
|
||||||
|
func selected_start() -> String:
|
||||||
|
if start_pick.selected < 0:
|
||||||
|
return ""
|
||||||
|
return str(start_pick.get_item_metadata(start_pick.selected))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Running ----------
|
||||||
|
|
||||||
|
func _on_run_pressed() -> void:
|
||||||
|
if running:
|
||||||
|
cancel_run()
|
||||||
|
else:
|
||||||
|
run_test()
|
||||||
|
|
||||||
|
|
||||||
|
func cancel_run() -> void:
|
||||||
|
if tester != null:
|
||||||
|
tester.cancel()
|
||||||
|
|
||||||
|
|
||||||
|
## Runs the test with the dialog's settings; returns when it is finished or
|
||||||
|
## cancelled. The UI stays responsive: runs happen in time slices.
|
||||||
|
func run_test() -> void:
|
||||||
|
if running or board == null or selected_start() == "":
|
||||||
|
return
|
||||||
|
running = true
|
||||||
|
run_button.text = "Cancel"
|
||||||
|
copy_button.disabled = true
|
||||||
|
_progress_row.visible = true
|
||||||
|
_clear_report()
|
||||||
|
var problems := BoardTester.static_checks(board)
|
||||||
|
tester = BoardTester.new(board, selected_start(), {
|
||||||
|
"runs": runs, "seed": randi(), "prefer": prefer_edit.text.strip_edges() if use_prefer else "",
|
||||||
|
})
|
||||||
|
progress.max_value = runs
|
||||||
|
progress.value = 0
|
||||||
|
var k := 1
|
||||||
|
while not tester.is_done():
|
||||||
|
var t0 := Time.get_ticks_msec()
|
||||||
|
await tester.run_batch(k)
|
||||||
|
var dt := maxi(1, Time.get_ticks_msec() - t0)
|
||||||
|
k = clampi(int(float(k) * SLICE_MSEC / dt), 1, 200) if dt < SLICE_MSEC else maxi(1, k / 2)
|
||||||
|
progress.value = tester.runs_done
|
||||||
|
status.text = "Run %d of %d" % [tester.runs_done, runs]
|
||||||
|
if not is_inside_tree():
|
||||||
|
return
|
||||||
|
await get_tree().process_frame
|
||||||
|
var report := tester.report()
|
||||||
|
tester = null
|
||||||
|
running = false
|
||||||
|
run_button.text = "Run again"
|
||||||
|
_progress_row.visible = false
|
||||||
|
last = {"board": board, "report": report, "problems": problems}
|
||||||
|
_show_report(report, problems)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Report ----------
|
||||||
|
|
||||||
|
func _clear_report() -> void:
|
||||||
|
for c in report_box.get_children():
|
||||||
|
c.queue_free()
|
||||||
|
sections.clear()
|
||||||
|
summary.visible = false
|
||||||
|
_report_text = ""
|
||||||
|
|
||||||
|
|
||||||
|
func _table_label(tid: String) -> String:
|
||||||
|
var t := board.get_table(tid) if board != null else null
|
||||||
|
return "%s (%s)" % [Formatter.strip_tags(t.name), tid] if t != null else tid
|
||||||
|
|
||||||
|
|
||||||
|
## The one-line summary, e.g. "500 runs · 0 errors · 2 dead ends · 3 tables never reached".
|
||||||
|
static func summary_line(report: Dictionary, problems: Array) -> String:
|
||||||
|
var errs := (report["errors"] as Array).size() + (report["unset_markers"] as Array).size()
|
||||||
|
var parts := PackedStringArray()
|
||||||
|
parts.append("%d runs" % report["runs"])
|
||||||
|
parts.append("%d %s" % [errs, "error" if errs == 1 else "errors"])
|
||||||
|
var dead := (report["dead_ends"] as Array).size()
|
||||||
|
parts.append("%d dead %s" % [dead, "end" if dead == 1 else "ends"])
|
||||||
|
var un := (report["unreached"] as Array).size()
|
||||||
|
parts.append("%d %s never reached" % [un, "table" if un == 1 else "tables"])
|
||||||
|
if not problems.is_empty():
|
||||||
|
parts.append("%d %s" % [problems.size(), "problem" if problems.size() == 1 else "problems"])
|
||||||
|
return " · ".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
func _show_report(report: Dictionary, problems: Array) -> void:
|
||||||
|
_clear_report()
|
||||||
|
run_button.text = "Run again"
|
||||||
|
copy_button.disabled = false
|
||||||
|
var line := summary_line(report, problems)
|
||||||
|
if report.get("cancelled", false):
|
||||||
|
line = "Cancelled after %d of %d runs · %s" % [report["runs"], report["runs_planned"], line.trim_prefix("%d runs · " % report["runs"])]
|
||||||
|
summary.text = line
|
||||||
|
summary.visible = true
|
||||||
|
|
||||||
|
# Problems
|
||||||
|
var items: Array = []
|
||||||
|
for p: Dictionary in problems:
|
||||||
|
items.append({"table_id": p["table_id"], "entry_id": p["entry_id"],
|
||||||
|
"text": "%s%s: %s" % [_table_label(p["table_id"]) if board.get_table(p["table_id"]) != null else "Board",
|
||||||
|
"" if str(p["entry_id"]) == "" else ", entry " + str(p["entry_id"]), p["text"]]})
|
||||||
|
_add_section("Problems", "Static checks", items, true)
|
||||||
|
# Errors: effect / expression errors, unset markers and action-limit halts
|
||||||
|
items = []
|
||||||
|
for e: Dictionary in report["errors"]:
|
||||||
|
items.append({"table_id": e["table_id"], "entry_id": e["entry_id"],
|
||||||
|
"text": "%dx %s, entry \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]]})
|
||||||
|
for e: Dictionary in report["unset_markers"]:
|
||||||
|
items.append({"table_id": e["table_id"], "entry_id": e["entry_id"],
|
||||||
|
"text": "%dx %s, entry \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]]})
|
||||||
|
for why: String in report["halted"]:
|
||||||
|
var top: Array = (report["longest"] as Dictionary).get("top", [])
|
||||||
|
items.append({"table_id": str(top[0]["table"]) if not top.is_empty() else "", "entry_id": "",
|
||||||
|
"text": "%d runs stopped: %s%s" % [report["halted"][why], why,
|
||||||
|
" (busiest table: %s)" % _table_label(str(top[0]["table"])) if not top.is_empty() else ""]})
|
||||||
|
_add_section("Errors", "Runtime errors", items, true)
|
||||||
|
items = []
|
||||||
|
for e: Dictionary in report["dead_ends"]:
|
||||||
|
items.append({"table_id": e["table_id"], "entry_id": "", "text": "%dx %s: %s" % [e["count"], e["table"], e["text"]]})
|
||||||
|
_add_section("Dead ends", "Rolls that stopped", items, true)
|
||||||
|
items = []
|
||||||
|
for id: String in report["unreached"]:
|
||||||
|
items.append({"table_id": id, "entry_id": "", "text": _table_label(id)})
|
||||||
|
_add_section("Never reached", "Tables no run got to", items, false)
|
||||||
|
items = []
|
||||||
|
var uc: Dictionary = report["unchosen"]
|
||||||
|
for id: String in uc:
|
||||||
|
var texts: Array = uc[id]
|
||||||
|
var ids: Array = report["unchosen_ids"][id]
|
||||||
|
for k in texts.size():
|
||||||
|
items.append({"table_id": id, "entry_id": ids[k], "text": "%s: \"%s\"" % [_table_label(id), texts[k]]})
|
||||||
|
_add_section("Never chosen", "Entries no run picked", items, false)
|
||||||
|
|
||||||
|
if str(report["sample_sheet"]) != "":
|
||||||
|
var sheet := Style.make_label("Sample sheet", Style.caps(), 12, Style.MUTED)
|
||||||
|
report_box.add_child(sheet)
|
||||||
|
var rtl := note(str(report["sample_sheet"]), Style.INK)
|
||||||
|
report_box.add_child(rtl)
|
||||||
|
_report_text = _compose_text(report, problems)
|
||||||
|
_refit.call_deferred()
|
||||||
|
|
||||||
|
|
||||||
|
func _refit() -> void:
|
||||||
|
if is_inside_tree():
|
||||||
|
await get_tree().process_frame
|
||||||
|
_fit()
|
||||||
|
|
||||||
|
|
||||||
|
func _add_section(title: String, hint: String, items: Array, open: bool) -> void:
|
||||||
|
var box := VBoxContainer.new()
|
||||||
|
box.add_theme_constant_override("separation", 2)
|
||||||
|
var header := Button.new()
|
||||||
|
header.flat = true
|
||||||
|
header.alignment = HORIZONTAL_ALIGNMENT_LEFT
|
||||||
|
header.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
|
||||||
|
header.add_theme_font_override("font", Style.body_bold())
|
||||||
|
header.add_theme_font_size_override("font_size", 16)
|
||||||
|
for c in ["font_color", "font_hover_color", "font_pressed_color", "font_focus_color", "font_hover_pressed_color"]:
|
||||||
|
header.add_theme_color_override(c, Style.INK if not items.is_empty() else Style.MUTED)
|
||||||
|
header.add_theme_color_override("font_disabled_color", Style.MUTED)
|
||||||
|
header.tooltip_text = hint
|
||||||
|
var list := VBoxContainer.new()
|
||||||
|
list.add_theme_constant_override("separation", 0)
|
||||||
|
list.visible = open and not items.is_empty()
|
||||||
|
var refresh := func() -> void:
|
||||||
|
header.text = "%s %s (%d)" % ["▾" if list.visible else "▸", title, items.size()]
|
||||||
|
refresh.call()
|
||||||
|
header.disabled = items.is_empty()
|
||||||
|
header.pressed.connect(func() -> void:
|
||||||
|
list.visible = not list.visible
|
||||||
|
refresh.call()
|
||||||
|
_fit()
|
||||||
|
)
|
||||||
|
box.add_child(header)
|
||||||
|
for k in mini(SECTION_CAP, items.size()):
|
||||||
|
list.add_child(_item_button(items[k]))
|
||||||
|
if items.size() > SECTION_CAP:
|
||||||
|
var more := note("... and %d more (see Copy report)" % (items.size() - SECTION_CAP))
|
||||||
|
list.add_child(more)
|
||||||
|
box.add_child(list)
|
||||||
|
report_box.add_child(box)
|
||||||
|
sections[title] = {"header": header, "box": list, "count": items.size(), "items": items}
|
||||||
|
|
||||||
|
|
||||||
|
func _item_button(item: Dictionary) -> Button:
|
||||||
|
var b := Button.new()
|
||||||
|
b.flat = true
|
||||||
|
b.text = str(item["text"])
|
||||||
|
b.alignment = HORIZONTAL_ALIGNMENT_LEFT
|
||||||
|
b.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||||
|
b.clip_text = false
|
||||||
|
b.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||||
|
b.add_theme_font_override("font", Style.body())
|
||||||
|
b.add_theme_font_size_override("font_size", 14)
|
||||||
|
for c in ["font_color", "font_hover_color", "font_pressed_color", "font_focus_color", "font_hover_pressed_color"]:
|
||||||
|
b.add_theme_color_override(c, Style.INK)
|
||||||
|
b.add_theme_stylebox_override("hover", Style.box(Style.HOVER_ROW, 5, [8, 3, 8, 3]))
|
||||||
|
b.add_theme_stylebox_override("pressed", Style.box(Style.HOVER_ROW, 5, [8, 3, 8, 3]))
|
||||||
|
b.add_theme_stylebox_override("normal", Style.box(Color(0, 0, 0, 0), 5, [8, 3, 8, 3]))
|
||||||
|
b.add_theme_stylebox_override("focus", Style.box(Color(0, 0, 0, 0), 5, [8, 3, 8, 3]))
|
||||||
|
b.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
|
||||||
|
var tid := str(item["table_id"])
|
||||||
|
b.disabled = tid == "" or board.get_table(tid) == null
|
||||||
|
b.tooltip_text = "Go to this card" if not b.disabled else ""
|
||||||
|
b.pressed.connect(click_item.bind(tid, str(item["entry_id"])))
|
||||||
|
return b
|
||||||
|
|
||||||
|
|
||||||
|
## Jumps to a card (and entry): through Main.focus_table() when it exists,
|
||||||
|
## otherwise by panning the board to the card. The dialog closes so the board
|
||||||
|
## is visible; reopening it shows the same report.
|
||||||
|
func click_item(table_id: String, entry_id: String = "") -> void:
|
||||||
|
if main == null or table_id == "":
|
||||||
|
return
|
||||||
|
if main.has_method("focus_table"):
|
||||||
|
main.call("focus_table", table_id, entry_id)
|
||||||
|
else:
|
||||||
|
_pan_to(table_id)
|
||||||
|
close()
|
||||||
|
|
||||||
|
|
||||||
|
func _pan_to(table_id: String) -> void:
|
||||||
|
var t := board.get_table(table_id)
|
||||||
|
var bv: Variant = main.get("board")
|
||||||
|
if t == null or bv == null:
|
||||||
|
return
|
||||||
|
var view: Control = bv
|
||||||
|
var card: Variant = main.call("card_for", table_id)
|
||||||
|
var size_of: Vector2 = (card as Control).size if card is Control else Vector2(260, 120)
|
||||||
|
var center := t.position + size_of / 2.0
|
||||||
|
var zoom: float = view.get("zoom")
|
||||||
|
view.get("world").position = view.size / 2.0 - center * zoom
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Copy ----------
|
||||||
|
|
||||||
|
func copy_report() -> void:
|
||||||
|
DisplayServer.clipboard_set(_report_text)
|
||||||
|
if main != null and main.has_method("toast"):
|
||||||
|
main.call("toast", "Report copied")
|
||||||
|
|
||||||
|
|
||||||
|
func report_text() -> String:
|
||||||
|
return _report_text
|
||||||
|
|
||||||
|
|
||||||
|
func _compose_text(report: Dictionary, problems: Array) -> String:
|
||||||
|
var out := PackedStringArray()
|
||||||
|
out.append("Test board: %s, starting from %s" % [board.name, _table_label(str(report.get("start", "")))])
|
||||||
|
out.append(summary.text)
|
||||||
|
out.append("")
|
||||||
|
out.append("\n".join(BoardTester.format_problems(problems, 1000)))
|
||||||
|
out.append("")
|
||||||
|
out.append(BoardTester.format_report(report, 1000))
|
||||||
|
return "\n".join(out)
|
||||||
1
ui/test_board_dialog.gd.uid
Normal file
1
ui/test_board_dialog.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
uid://chpx1qsf5okaf
|
||||||
Loading…
Reference in a new issue