TableTower/tools/simulate_board.gd

367 lines
15 KiB
GDScript3
Raw Normal View History

extends SceneTree
## Rolls a collection many times headlessly, answering every choice card at
## random, and reports what happened: how many rolls finished, why the others
## stopped, how many actions they took, every effect or expression error, the
## tables and entries that were never reached, and a sample final sheet.
##
## Run:
## godot --headless --path . -s res://tools/simulate_board.gd -- \
## --board=<collection.json> --start=<table id> --runs=N [--seed=S] \
## [--prefer=<regex>] [--track=a,b] [--max-actions=N] [--list=N] [--quiet]
##
## --prefer on a pick card, choose an option whose text matches this
## regular expression (case-insensitive) whenever there is one,
## e.g. --prefer="^Continue|another career"; otherwise random.
## --list how many lines to print per section (default 40).
## --quiet leave the sample sheet out of the report.
## --track comma-separated board variables (no "@") whose final values
## are summarised over all runs (min, mean, max), e.g.
## --track=terms,age
##
## Every run starts with a fresh, empty set of board variables (its own
## persistent-vars dictionary), so runs never leak state into each other.
## The exit code is 1 when any run hit an error, the action limit, or a
## dead end ("No result for ..."), else 0.
##
## Other scripts can call simulate() and format_report() directly (see
## tests/test_simulate.gd).
func _init() -> void:
var args := _parse_args(OS.get_cmdline_user_args())
var path := str(args.get("board", ""))
var start := str(args.get("start", ""))
if path == "" or start == "":
print("Usage: godot --headless --path . -s res://tools/simulate_board.gd -- --board=<json> --start=<table id> --runs=N [--seed=S] [--prefer=<regex>] [--track=a,b] [--max-actions=N] [--list=N] [--quiet]")
quit(2)
return
var text := FileAccess.get_file_as_string(path)
if text == "":
print("Can't read %s" % path)
quit(2)
return
var board := TowerBoard.new()
if not board.load_json(text):
print("%s is not a TableTower collection" % path)
quit(2)
return
if board.get_table(start) == null:
print("No table with id \"%s\" in %s" % [start, path])
quit(2)
return
var opts := {
"runs": int(args.get("runs", "100")),
"seed": int(args.get("seed", "1")),
"prefer": str(args.get("prefer", "")),
"max_actions": int(args.get("max-actions", str(RollContext.DEFAULT_MAX_ACTIONS))),
"track": str(args.get("track", "")).split(",", false),
}
var report: Dictionary = await simulate(board, start, opts)
print(format_report(report, int(args.get("list", "40")), not args.has("quiet")))
quit(0 if is_clean(report) else 1)
static func _parse_args(list: PackedStringArray) -> Dictionary:
var out := {}
for a in list:
if not a.begins_with("--"):
continue
var s := a.substr(2)
var eq := s.find("=")
if eq < 0:
out[s] = "true"
else:
out[s.substr(0, eq)] = s.substr(eq + 1)
return out
## Runs `opts.runs` top-level rolls of `start` and gathers statistics.
## opts: runs (int), seed (int), prefer (String regex, may be ""),
## max_actions (int), track (Array of variable names). Returns the report
## Dictionary that format_report() prints:
## runs, completed, halted {reason: count}, actions {max, mean, p95},
## longest {actions, run, top: [{table, count}]} (the most-rolled tables
## of the run that took the most actions), track {name: {min, max, sum, n}},
## prompts_mean, errors [{table, entry, text, count}], dead_ends
## [{table, text, count}], unset_markers [{table, entry, text, count}]
## (unset {@var?}, missing [[table]] and failed {= expr} markers),
## unreached [table ids], unchosen {table id: [entry texts]},
## table_hits {table id: count}, sample_sheet (String), sample_vars
## (Dictionary), sample_halted (String)
static func simulate(board: TowerBoard, start: String, opts: Dictionary = {}) -> Dictionary:
var runs := maxi(1, int(opts.get("runs", 100)))
var rng := RandomNumberGenerator.new()
rng.seed = int(opts.get("seed", 1))
var answer_rng := RandomNumberGenerator.new()
answer_rng.seed = rng.seed * 7919 + 17
var prefer: RegEx = null
var pat := str(opts.get("prefer", ""))
if pat != "":
prefer = RegEx.create_from_string("(?i)" + pat)
var max_actions := int(opts.get("max_actions", RollContext.DEFAULT_MAX_ACTIONS))
var completed := 0
var halted := {}
var actions: Array[int] = []
var prompts_total := 0
var errors := {} # key -> {table, entry, text, count}
var dead_ends := {} # key -> {table, text, count}
var markers := {} # key -> {table, entry, text, count}
var table_hits := {} # table id -> count
var entry_hits := {} # "table:entry" -> count
var sample_sheet := ""
var sample_vars := {}
var sample_halted := ""
var longest := {"actions": -1, "run": 0, "top": []}
var track := {} # name -> {min, max, sum, n}
for name: String in opts.get("track", []):
track[name.strip_edges().trim_prefix("@")] = {"min": INF, "max": -INF, "sum": 0.0, "n": 0}
for run in runs:
var vars := {}
var ctx := Roller.new_context(board, rng, vars, {})
ctx.max_actions = max_actions
var counter := [0]
ctx.prompt = func(req: Dictionary) -> Variant:
counter[0] += 1
var texts: Array = [str(req.get("prompt", ""))]
for o: Dictionary in req.get("options", []):
texts.append(str(o.get("text", "")))
for txt: String in texts:
for m in _marker_re().search_all(txt):
var what := Formatter.strip_tags(m.get_string())
var tid := str(req.get("table_id", ""))
var mk := tid + ":prompt|" + what
if not markers.has(mk):
markers[mk] = {"table": "%s (%s)" % [Formatter.strip_tags(str(req.get("title", ""))), tid], "entry": "(prompt)", "text": what, "count": 0}
markers[mk]["count"] += 1
return answer(req, answer_rng, prefer)
var root: Dictionary = await Roller.roll_async(board, start, ctx)
prompts_total += counter[0]
actions.append(ctx.actions)
if ctx.halted == "":
completed += 1
else:
var why := "Action limit" if ctx.halted.begins_with("Stopped after") else ctx.halted
halted[why] = int(halted.get(why, 0)) + 1
for name: String in track:
var v: Variant = Expr.to_value((vars.get(name, {}) as Dictionary).get("value") if vars.get(name) is Dictionary else null)
if v is int or v is float:
var tr: Dictionary = track[name]
tr["min"] = minf(tr["min"], v)
tr["max"] = maxf(tr["max"], v)
tr["sum"] += v
tr["n"] += 1
var run_hits := {}
for st: Dictionary in Roller.flatten(root, []):
var tid := str(st.get("table_id", ""))
run_hits[tid] = int(run_hits.get(tid, 0)) + 1
var eid := str(st.get("entry_id", ""))
var tname := Formatter.strip_tags(str(st.get("table", "")))
if st.get("stop", false):
if not st.get("limit", false) and not st.get("cancelled", false):
var dk := tid + "|" + str(st.get("text", ""))
if not dead_ends.has(dk):
dead_ends[dk] = {"table": "%s (%s)" % [tname, tid], "text": Formatter.strip_tags(str(st.get("text", ""))), "count": 0}
dead_ends[dk]["count"] += 1
continue
table_hits[tid] = int(table_hits.get(tid, 0)) + 1
if eid != "" and not st.has("pass") and not st.has("after"):
entry_hits[tid + ":" + eid] = int(entry_hits.get(tid + ":" + eid, 0)) + 1
elif st.has("pass"):
entry_hits[tid + ":" + _loop_entry_id(board, tid, 0)] = 1
elif st.has("after"):
entry_hits[tid + ":" + _loop_entry_id(board, tid, 1)] = 1
for l: Variant in st.get("effects", []):
if l is Dictionary and (l as Dictionary).get("error", false):
var text := str((l as Dictionary).get("text", ""))
var ek := tid + ":" + eid + "|" + text
if not errors.has(ek):
errors[ek] = {"table": "%s (%s)" % [tname, tid], "entry": _entry_label(board, tid, eid), "text": text, "count": 0}
errors[ek]["count"] += 1
for m in _marker_re().search_all(str(st.get("text", ""))):
var what := Formatter.strip_tags(m.get_string())
var mk := tid + ":" + eid + "|" + what
if not markers.has(mk):
markers[mk] = {"table": "%s (%s)" % [tname, tid], "entry": _entry_label(board, tid, eid), "text": what, "count": 0}
markers[mk]["count"] += 1
if ctx.actions > int(longest["actions"]):
var top: Array = []
for k: String in run_hits:
top.append({"table": k, "count": run_hits[k]})
top = _sorted_by_count(top).slice(0, 8)
longest = {"actions": ctx.actions, "run": run + 1, "top": top}
if run == runs - 1 or (sample_sheet == "" and ctx.halted == ""):
var sheet := Roller.last_sheet(root)
if not sheet.is_empty():
sample_sheet = Formatter.strip_tags(str(sheet.get("summary", "")))
sample_vars = vars.duplicate(true)
sample_halted = ctx.halted
var unreached: Array[String] = []
var unchosen := {}
for t in board.tables:
if t.kind == RollTable.KIND_VARIABLE:
continue
if not table_hits.has(t.id):
unreached.append(t.id)
continue
var missing: Array[String] = []
for e in t.entries:
if t.kind == RollTable.KIND_ROLL and not t.can_come_up(e):
continue
if not entry_hits.has(t.id + ":" + e.id):
missing.append(Formatter.strip_tags(e.text).substr(0, 60))
if not missing.is_empty():
unchosen[t.id] = missing
var sorted_actions := actions.duplicate()
sorted_actions.sort()
var total := 0
for a in actions:
total += a
var p95: int = sorted_actions[clampi(ceili(0.95 * sorted_actions.size()) - 1, 0, sorted_actions.size() - 1)]
return {
"runs": runs,
"completed": completed,
"halted": halted,
"actions": {"max": sorted_actions.back(), "mean": float(total) / runs, "p95": p95},
"longest": longest,
"track": track,
"prompts_mean": float(prompts_total) / runs,
"errors": _sorted_by_count(errors.values()),
"dead_ends": _sorted_by_count(dead_ends.values()),
"unset_markers": _sorted_by_count(markers.values()),
"unreached": unreached,
"unchosen": unchosen,
"table_hits": table_hits,
"sample_sheet": sample_sheet,
"sample_vars": sample_vars,
"sample_halted": sample_halted,
}
## The simulated player's reply to a prompt request (docs/LOGIC.md §8): a
## random option or Random for a pick (or an option matching `prefer`), a
## random number in range, a short random word for text.
static func answer(req: Dictionary, rng: RandomNumberGenerator, prefer: RegEx = null) -> Variant:
match str(req.get("kind", "pick")):
"number":
return rng.randi_range(int(req.get("min", 0)), int(req.get("max", 0)))
"text":
var letters := "abcdefghijklmnopqrstuvwxyz"
var s := ""
for k in rng.randi_range(3, 8):
s += letters[rng.randi_range(0, letters.length() - 1)]
return s.capitalize()
var options: Array = req.get("options", [])
if prefer != null:
for o: Dictionary in options:
if prefer.search(Formatter.strip_tags(str(o.get("text", "")))) != null:
return int(o["index"])
if options.is_empty():
return -1
# Random (-1) is offered beside every option.
var k := rng.randi_range(-1, options.size() - 1)
return -1 if k < 0 else int(options[k]["index"])
## True when no run hit an error, a dead end or the action limit.
static func is_clean(report: Dictionary) -> bool:
return (report["errors"] as Array).is_empty() and (report["dead_ends"] as Array).is_empty() \
and not (report["halted"] as Dictionary).has("Action limit")
static func format_report(r: Dictionary, list: int = 40, show_sheet: bool = true) -> String:
var out := PackedStringArray()
var a: Dictionary = r["actions"]
out.append("Runs: %d completed: %d prompts per run: %.1f" % [r["runs"], r["completed"], r["prompts_mean"]])
var hl := PackedStringArray()
for k: String in r["halted"]:
hl.append("%s %d" % [k, r["halted"][k]])
out.append("Halted: %s" % (", ".join(hl) if not hl.is_empty() else "none"))
out.append("Actions: max %d, mean %.1f, p95 %d" % [a["max"], a["mean"], a["p95"]])
var lg: Dictionary = r.get("longest", {})
if not (lg.get("top", []) as Array).is_empty():
var parts := PackedStringArray()
for x: Dictionary in lg["top"]:
parts.append("%s %d" % [x["table"], x["count"]])
out.append("Longest run (#%d) most-rolled tables: %s" % [lg["run"], ", ".join(parts)])
var tr: Dictionary = r.get("track", {})
for name: String in tr:
var t: Dictionary = tr[name]
if int(t["n"]) == 0:
out.append("@%s: never a number" % name)
else:
out.append("@%s: min %s, mean %.1f, max %s (%d runs)" % [name, Expr.format_value(t["min"]), t["sum"] / t["n"], Expr.format_value(t["max"]), t["n"]])
_section(out, "Effect / expression errors", r["errors"], list, func(e: Dictionary) -> String:
return "%dx %s, entry \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]])
_section(out, "Dead ends (rolls that stopped)", r["dead_ends"], list, func(e: Dictionary) -> String:
return "%dx %s: %s" % [e["count"], e["table"], e["text"]])
_section(out, "Unset variables, missing tables and {= } errors in text", r["unset_markers"], list, func(e: Dictionary) -> String:
return "%dx %s, entry \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]])
var un: Array = r["unreached"]
out.append("Tables never reached: %d" % un.size())
for k in mini(list, un.size()):
out.append(" " + str(un[k]))
if un.size() > list:
out.append(" ... and %d more" % (un.size() - list))
var uc: Dictionary = r["unchosen"]
var n_entries := 0
for k: String in uc:
n_entries += (uc[k] as Array).size()
out.append("Entries never chosen: %d in %d reached tables" % [n_entries, uc.size()])
var shown := 0
for k: String in uc:
if shown >= list:
out.append(" ... and %d more tables" % (uc.size() - shown))
break
var items: Array = uc[k]
var names := PackedStringArray()
for x in mini(4, items.size()):
names.append("\"%s\"" % items[x])
out.append(" %s: %d (%s%s)" % [k, items.size(), ", ".join(names), ", ..." if items.size() > 4 else ""])
shown += 1
if show_sheet:
out.append("Sample final sheet%s:" % (" (" + str(r["sample_halted"]) + ")" if str(r["sample_halted"]) != "" else ""))
out.append(str(r["sample_sheet"]) if str(r["sample_sheet"]) != "" else " (no sheet card was reached)")
return "\n".join(out)
static func _section(out: PackedStringArray, title: String, items: Array, list: int, fmt: Callable) -> void:
out.append("%s: %d" % [title, items.size()])
for k in mini(list, items.size()):
out.append(" " + str(fmt.call(items[k])))
if items.size() > list:
out.append(" ... and %d more" % (items.size() - list))
static func _sorted_by_count(list: Array) -> Array:
var out := list.duplicate()
out.sort_custom(func(x: Dictionary, y: Dictionary) -> bool: return int(x["count"]) > int(y["count"]))
return out
static func _entry_label(board: TowerBoard, tid: String, eid: String) -> String:
var t := board.get_table(tid)
if t == null:
return eid
var e := t.find_entry(eid)
return eid if e == null else Formatter.strip_tags(e.text).substr(0, 50)
static func _loop_entry_id(board: TowerBoard, tid: String, index: int) -> String:
var t := board.get_table(tid)
if t == null or t.entries.size() <= index:
return ""
return t.entries[index].id
static var _marker: RegEx = null
static func _marker_re() -> RegEx:
if _marker == null:
_marker = RegEx.create_from_string("\\[url=(?:unset|missing|error):[^\\]]*\\][^\\[]*\\[/url\\]")
return _marker