TableTower/ui/test_board_dialog.gd

402 lines
15 KiB
GDScript3
Raw Normal View History

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)
# Start on the run count of the last report, so the selector matches it.
var last_runs := int(last.get("report", {}).get("runs_planned", RUN_CHOICES[0])) if last.get("report") is Dictionary else RUN_CHOICES[0]
var runs_index := maxi(0, RUN_CHOICES.find(last_runs))
runs = RUN_CHOICES[runs_index]
row.add_child(field("Runs", segmented(RUN_CHOICES.map(func(n: int) -> String: return str(n)), runs_index,
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)