TableTower/tests/test_logic_ui.gd
RobinFiredrake 0202312688 Split ui/main.gd into area helpers (no behaviour change)
Main (3679 lines) becomes a shell: shared state, start-up, cards, input,
rules view and one-line delegators for the methods other files call. Each
area moves with its state into a RefCounted helper holding a back-reference
(m: Main):

  main_cli.gd          command-line and screenshot flags
  main_top_bar.gd      top bar, toast, endless-loop chip
  main_editing.gd      add/delete cards, results and pipes, selection bar
  main_groups.gd       groups and card drags
  main_templates.gd    templates
  main_rolling.gd      rolling, choice questions, playback, session seed, copy
  main_collections.gd  collections, import/export, table settings, test board
  main_state.gd        decks, variables, roll history (local state)
  main_navigation.gd   search, focus, minimap, arrange/pack
  main_history.gd      undo/redo and mark_dirty
  main_inspector.gd    inspector selection and refresh

Tests that reached moved private members now go through the helper
(main.undo_redo.edits, main.rolling.pending_choice(), ...).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:14:19 -06:00

454 lines
19 KiB
GDScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

extends SceneTree
## Logic cards in the app: the choice pop-up, progress while it's open,
## cancelling, a new roll replacing an open question, live variable and sheet
## cards, the long-chain tray and the Build-mode settings rules.
## Run: godot --headless --path . -s res://tests/test_logic_ui.gd -- --sample
## (--sample keeps the app from reading or writing saved collections.)
const DEMO := "res://examples/logic_demo.json"
var _failures := 0
var main: Main
func _init() -> void:
if not OS.get_cmdline_user_args().has("--sample"):
print("Run with -- --sample so the test can't touch saved data.")
quit(2)
return
main = load("res://ui/main.tscn").instantiate()
root.add_child(main)
for i in 5:
await process_frame
if main._saving_enabled:
print("Saving is enabled; refusing to roll.")
quit(2)
return
main.rng.seed = 11
_test_demo_file()
await _load_demo()
_test_cards()
await _test_scripted()
await _test_dialog_answers()
await _test_cancel()
await _test_replace()
await _test_keys()
await _test_live_edits()
_test_settings_rules()
_test_add_kinds()
await _test_long_chain()
await _test_action_limit()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
func _load_demo() -> void:
main.prompt_hook = main.rolling._ask_player
await main.cli._load_board_file(DEMO)
for i in 3:
await process_frame
## A prompt hook answering from a script by kind (scripts can be Callables).
func _scripted(answers: Dictionary, log: Array) -> Callable:
return func(req: Dictionary) -> Variant:
log.append(req)
var a: Variant = answers.get(str(req["kind"]))
if a is Callable:
return (a as Callable).call(req)
return a
## When the open question is the demo's optional "Spend a find" (asked only
## when the delver found loot), answers "Keep everything" and returns the
## next question; otherwise returns `d` unchanged.
func _past_spend(d: ChoiceDialog) -> ChoiceDialog:
if d == null or str(d.request.get("table_id", "")) != "spend_find":
return d
for o: Dictionary in d.request["options"]:
if Formatter.strip_tags(str(o["text"])) == "Keep everything":
d.answer(int(o["index"]))
break
await process_frame
return main.rolling.pending_choice()
func _var(name: String) -> Variant:
var v: Variant = main.persistent_vars.get(name)
return (v as Dictionary).get("value") if v is Dictionary else null
# ---------------------------------------------------------------- demo file
func _test_demo_file() -> void:
var text := FileAccess.get_file_as_string(DEMO)
var r := IoMenu.parse_import(text, IoMenu.detect_format("logic_demo.json", text))
_check(r["ok"] and (r["errors"] as Array).is_empty(), "the demo imports through Board ▾ → Import: %s" % str(r["errors"]))
var b := TowerBoard.new()
_check(b.load_json(text), "the demo loads as a board")
var kinds := {}
for t in b.tables:
kinds[t.kind + ("/" + t.choice if t.kind == "choice" else "")] = true
for k in ["roll", "choice/pick", "choice/number", "choice/text", "loop", "variable", "sheet"]:
_check(kinds.has(k), "the demo has a %s card" % k)
var check := b.get_table("room_check")
_check(check != null and check.is_expr_dice(), "the demo has an expression check table")
_check(not b.to_json().to_lower().contains("traveller"), "the demo is original")
func _test_cards() -> void:
var check := main.card_for("room_check")
_check(check != null and check.rows.size() == 3, "the check table shows its three ranges")
var nums: Array = []
for eid: String in check._row_parts:
var num: Label = check._row_parts[eid]["num"]
nums.append(num.text if num else "")
_eq(nums, ["≤6", "7–9", "10+"], "expression dice label the ends ≤N and N+")
var loop := main.card_for("explore")
_check(loop.rows.size() == 2 and loop.anchor_for("e1").size() > 0 and loop.anchor_for("e2").size() > 0,
"a loop card has Each time and Afterwards rows with outlets")
_eq(TableCard.loop_rule(loop.table), "× @rooms", "the loop rule reads × @rooms")
var hp := main.card_for("v_hp")
_check(hp.rows.is_empty() and hp.anchor_for("x").is_empty(), "a variable card has no outlets")
var sheet := main.card_for("report")
_check(sheet.rows.size() == 1 and not sheet.anchor_for("e1").is_empty(), "a sheet card has one outlet")
_eq(TableCard.effect_summary("@hp -= 2\n@gold += 1; @luck = 3", main.data), "Hit points -= 2 · Gold += 1 · +1",
"effect summaries use the variable card's name")
# ---------------------------------------------------------------- prompts
func _test_scripted() -> void:
var log: Array = []
main.prompt_hook = _scripted({"text": "Brin", "number": 3, "pick": 1}, log)
main.start_roll("start")
_eq(log.size(), 3, "three questions: name, rooms, way out")
var kinds: Array = []
for r: Dictionary in log:
kinds.append(r["kind"])
_eq(kinds, ["text", "number", "pick"], "asked in chain order")
_check(main.current.get("done", false), "a roll with questions shows at once after the last answer")
_eq(_var("name"), "Brin", "text answer saved")
_eq(_var("rooms"), 3, "number answer saved")
var passes := 0
for s: Dictionary in main.current["all"]:
if s.has("pass"):
passes += 1
_eq(passes, 3, "the number answer drives the loop")
var last: Dictionary = (main.current["all"] as Array).back()
_eq(last.get("table_id"), "report", "the chain ends at the sheet")
_check(main.tray._headline.visible and Formatter.strip_tags(main.tray._headline_text.text).begins_with("Brin the delver"),
"the tray headline is the rendered sheet")
# Option 1 is "Fight through", which costs 1d3 HP.
var picked := false
for s: Dictionary in main.current["all"]:
if s.get("table_id") == "way_out" and s.get("picked", false) and Formatter.strip_tags(str(s["text"])) == "Fight through":
picked = true
_check(picked, "the picked option is the step")
# Live cards after the roll.
var hp := main.card_for("v_hp")
_eq(hp._var_value.text, Expr.format_value(_var("hp")), "the HP card shows the new value after the roll")
var sheet := main.card_for("report")
_check(Formatter.strip_tags(sheet._sheet_label.text).contains("HP %s" % Expr.format_value(_var("hp"))), "the sheet card is up to date")
_check(Formatter.strip_tags(sheet._sheet_label.text).begins_with("Brin the delver"), "the sheet shows the name")
main.prompt_hook = main.rolling._ask_player
func _test_dialog_answers() -> void:
main.start_roll("start", true)
await process_frame
var d := main.rolling.pending_choice()
_check(d != null and d.kind == "text", "the text pop-up opens (fast roll still asks)")
if d == null:
return
_eq(d.title_label.text, "Name your delver", "pop-up title")
# Partial progress is lit before the pop-up: the start card's result.
_check(main.is_entry_lit("start", "e1"), "steps so far are lit while the question is open")
_check(not main.is_entry_lit("name_q", "e1"), "the question's own row isn't lit yet")
_check((main.current["steps"] as Array).size() == 1 and str(main.current.get("asking", "")) == "Name your delver",
"the tray shows the steps so far and the open question")
d._text.text = "Ann"
d._confirm()
await process_frame
d = main.rolling.pending_choice()
_check(d != null and d.kind == "number", "then the number pop-up")
if d == null:
return
_check(main.is_entry_lit("name_q", "e1") and main.is_entry_lit("start", "e1"), "progress grows with each answer")
_check(d._spin.min_value == 1 and d._spin.max_value == 5 and int(d._spin.value) == 1, "number pop-up has min, max and default")
d._spin.value = 2
d._confirm()
await process_frame
d = await _past_spend(main.rolling.pending_choice())
_check(d != null and d.kind == "pick" and d._options.size() == 3, "then the pick pop-up with three options")
if d == null:
return
_check(main.is_entry_lit("explore", "e1") and main.is_entry_lit("explore", "e2"), "the loop's steps are lit before the pick")
d.answer(-1)
await process_frame
_check(main.rolling.pending_choice() == null and main.current.get("done", false), "Random finishes the roll")
_eq(_var("name"), "Ann", "typed name saved")
_eq(_var("rooms"), 2, "typed number saved")
var random := false
for s: Dictionary in main.current["all"]:
if s.get("table_id") == "way_out" and s.get("random", false):
random = true
_check(random, "Random rolls the pick card normally")
func _test_cancel() -> void:
main.start_roll("start")
await process_frame
var d := main.rolling.pending_choice()
_check(d != null, "a pop-up is open")
if d == null:
return
d.close() # Esc does this
await process_frame
_check(main.rolling.pending_choice() == null, "Esc closes the pop-up")
_eq(main.current.get("halted", ""), "Cancelled", "Cancel stops the roll with Cancelled")
_check(main.current.get("done", false), "the cancelled roll is shown, not left hanging")
var last: Dictionary = (main.current["all"] as Array).back()
_check(last.get("cancelled", false) and last.get("stop", false), "the chain ends with a Cancelled marker")
_check(main.tray._halt.visible and main.tray._halt_label.text.contains("Cancelled"), "the tray says Cancelled")
_check(main.rolling_ctx == null, "no roll is left running")
# Freeing the dialog some other way also answers Cancel.
main.start_roll("start")
await process_frame
d = main.rolling.pending_choice()
if d:
d.free()
await process_frame
_check(main.current.get("done", false) and main.current.get("halted", "") == "Cancelled", "a freed pop-up cancels its roll instead of hanging")
func _test_replace() -> void:
main.start_roll("start")
await process_frame
var first := main.rolling.pending_choice()
_check(first != null, "first roll asks")
var first_reply := first.reply if first else null
var history := main.history.size()
main.start_roll("start")
_check(first_reply != null and first_reply.finished, "a new roll answers the old question with Cancel")
await process_frame
var second := main.rolling.pending_choice()
_check(second != null and second != first, "the new roll opens its own pop-up")
_check(not is_instance_valid(first) or first.is_queued_for_deletion(), "the old pop-up goes away")
_check(not main.current.has("halted"), "the old roll doesn't overwrite the new one")
_eq(main.history.size(), history, "the replaced (unanswered) roll isn't added to Earlier")
if second == null:
return
second._text.text = "Cy"
second._confirm()
await process_frame
var n := main.rolling.pending_choice()
if n:
n.answer(1)
await process_frame
var p := main.rolling.pending_choice()
if p:
p.answer(2)
await process_frame
_check(main.current.get("done", false) and main.current.get("halted", "") == "", "the new roll finishes normally")
_eq(_var("name"), "Cy", "with its own answers")
func _test_keys() -> void:
main.start_roll("start")
await process_frame
var d := main.rolling.pending_choice()
if d:
d._text.text = "Dee"
d._confirm()
await process_frame
d = main.rolling.pending_choice()
if d:
# Typing in the number field, then Enter.
var le := d._spin.get_line_edit()
le.text = "4"
le.text_changed.emit(le.text) # what typing does
le.text_submitted.emit(le.text)
await process_frame
_eq(_var("rooms"), 4, "a typed number is used")
d = await _past_spend(main.rolling.pending_choice())
_check(d != null and d.kind == "pick", "pick pop-up for the key test")
if d == null:
return
var ev := InputEventKey.new()
ev.keycode = KEY_3
ev.pressed = true
d._input(ev)
await process_frame
_check(main.rolling.pending_choice() == null and main.current.get("done", false), "pressing 3 answers")
var paid := false
for s: Dictionary in main.current["all"]:
if s.get("table_id") == "way_out" and Formatter.strip_tags(str(s["text"])) == "Pay the toll":
paid = true
_check(paid, "key 3 picks the third option")
# ---------------------------------------------------------------- live cards
func _test_live_edits() -> void:
main.set_variable("gold", "42")
_eq(_var("gold"), 42, "a number variable stays a number")
_eq(main.card_for("v_gold")._var_value.text, "42", "the variable card follows an edit")
_check(Formatter.strip_tags(main.card_for("report")._sheet_label.text).contains("Gold 42"), "the sheet follows an edit")
main.reset_variable("gold")
_eq(_var("gold"), 0, "reset goes back to the starting value")
main.set_variable("hp", "3")
main.persistent_vars["stray"] = {"value": "x", "source": ""}
main.reset_all_variables()
_check(_var("hp") == 10 and not main.persistent_vars.has("stray"), "Reset all: declared to start, undeclared cleared")
_eq(main.card_for("v_hp")._var_value.text, "10", "cards show the reset values")
main.tray.set_side(ResultTray.Side.VARIABLES)
main.tray.render()
var rows := 0
for c in main.tray._vars._list.get_children():
if c is HBoxContainer:
rows += 1
_check(rows >= 4, "the Variables tab lists every board variable, numbers included (%d rows)" % rows)
var dlg := main.tray._vars.confirm_reset_all()
_check(dlg != null and dlg.is_inside_tree(), "Reset all asks first, in the app")
dlg.close()
main.tray.set_side(ResultTray.Side.EARLIER)
# Rendering live cards doesn't happen per frame: the sheet's text stays put.
var before := main.card_for("report")._sheet_label.text
for i in 3:
await process_frame
_eq(main.card_for("report")._sheet_label.text, before, "live cards only re-render on change")
# ---------------------------------------------------------------- build rules
func _test_settings_rules() -> void:
var c := RollTable.create(RollTable.KIND_CHOICE, "c", "C", "pick")
c.entries[0].effects = "@a = 1"
c.entries[0].add_pipe("x")
var r := TableSettingsDialog.apply_settings(c, {"name": "C", "choice": "number", "min": "1", "max": "@top", "prompt": "How many?", "save_as": "@n"})
_check(r["ok"] and c.choice == "number" and c.entries.size() == 1 and c.entries[0].text == "Answer", "pick → number keeps one Answer row")
_check(Array(c.entries[0].pipes) == ["x"] and c.entries[0].effects == "@a = 1", "…with the first option's pipes and effects")
_check(c.max_expr == "@top" and c.save_as == "@n", "min/max and save as applied")
var bad := TableSettingsDialog.apply_settings(c, {"name": "C", "choice": "number", "min": "1 +", "max": "5"})
_check(not bad["ok"] and c.min_expr == "1", "a bad min is refused and nothing changes")
var back := TableSettingsDialog.apply_settings(c, {"name": "C", "choice": "pick"})
_check(back["ok"] and c.entries.size() == 3 and c.entries[0].text == "Option 1", "number → pick gives three options")
var l := RollTable.create(RollTable.KIND_LOOP, "l", "L", "times")
_check(not TableSettingsDialog.apply_settings(l, {"loop_mode": "while", "loop_expr": "@hp >"})["ok"], "a bad loop rule is refused")
_check(TableSettingsDialog.apply_settings(l, {"loop_mode": "while", "loop_expr": "@hp > 0"})["ok"] and l.loop_mode == "while", "a loop rule is applied")
var v := RollTable.create(RollTable.KIND_VARIABLE, "v", "V")
_check(not TableSettingsDialog.apply_settings(v, {"var_name": "Bad Name"})["ok"], "variable names are checked")
_check(TableSettingsDialog.apply_settings(v, {"var_name": "@str", "var_type": "number", "initial": "2d6"})["ok"] and v.var_name == "str",
"variable name, type and starting value applied")
var t := RollTable.create(RollTable.KIND_ROLL, "t", "T")
_check(TableSettingsDialog.apply_settings(t, {"ranged": true, "dice": "2d6 + dm(@end)"})["ok"], "expression dice are accepted")
var s := RollTable.create(RollTable.KIND_SHEET, "s", "S")
TableSettingsDialog.apply_settings(s, {"template": "HP {@hp}"})
_eq(s.entries[0].text, "HP {@hp}", "sheet template applied")
_eq(PipePopover._count_error("@terms"), "", "pipe counts take expressions")
_check(PipePopover._count_error("@terms +") != "", "bad pipe counts are flagged")
var e := TableEntry.new("e", "x")
e.set_pipe_count("y", "@terms")
_eq(PipeLayer._pipe_tag(e, "y"), "×@terms", "expression counts show on the pipe")
# Previews.
var pv := RichText.preview("{@skill_*} and {= dm(@str)} and {= 1 +}", main.data)
_check(pv.contains("{@skill_*}") and pv.contains("{= dm(@str)}"), "previews show {@x_*} and {= expr} readably")
_check(pv.contains("error:expr"), "a broken {= expr} is marked")
_check(RichText.decorate(TextExpander.error_marker("oops")).contains(Style.DANGER_INK.to_html(false)), "error markers are red")
func _test_add_kinds() -> void:
main.set_mode(Main.Mode.BUILD)
var n := main.data.tables.size()
for k: Array in MainEditing.ADD_KINDS:
var t := main.editing.add_table(str(k[1]), str(k[2]))
_check(t.kind == k[1] and main.card_for(t.id) != null, "+ Table adds a %s" % str(k[0]))
_eq(main.data.tables.size(), n + MainEditing.ADD_KINDS.size(), "one card per menu item")
var v1 := main.editing.add_table(RollTable.KIND_VARIABLE, "number")
var v2 := main.editing.add_table(RollTable.KIND_VARIABLE, "number")
_check(v1.var_name != v2.var_name, "new variable cards get distinct names")
main.set_mode(Main.Mode.PLAY)
# ---------------------------------------------------------------- long chains
func _long_chain(n: int) -> void:
for id in ["long_start", "long_link"]:
if main.data.get_table(id):
main.data.remove_table(id)
var head := RollTable.create(RollTable.KIND_ROLL, "long_start", "Long chain")
head.entries.resize(1)
head.entries[0].text = "Go"
head.entries[0].effects = "@k = 0"
head.entries[0].add_pipe("long_link")
var link := RollTable.create(RollTable.KIND_ROLL, "long_link", "Link")
link.entries.resize(1)
link.entries[0].text = "Link {@k}"
link.entries[0].effects = "@k += 1"
link.entries[0].add_pipe("long_link", "@k < %d" % n)
head.position = Vector2(40, 1200)
link.position = Vector2(360, 1200)
main.data.tables.append(head)
main.data.tables.append(link)
main._rebuild_cards()
func _chips() -> int:
var k := 0
for c in main.tray._flow.get_children():
if c is PanelContainer:
k += 1
return k
func _test_long_chain() -> void:
_long_chain(3000)
await process_frame
var t0 := Time.get_ticks_msec()
main.start_roll("long_start")
var ms := Time.get_ticks_msec() - t0
var all: Array = main.current["all"]
_eq(all.size(), 3001, "a 3,001-step chain")
_check(main.current.get("done", false), "a long chain shows at once, without animating")
_check(main.is_entry_lit("long_link", "e1"), "its path is lit")
_eq(_chips(), ResultTray.TAIL, "the tray shows only the last %d steps" % ResultTray.TAIL)
var toggle: Button = null
for c in main.tray._flow.get_children():
if c is HBoxContainer and c.get_child(0) is Button:
toggle = c.get_child(0)
_check(toggle != null and toggle.text == "+2,989 earlier steps", "a +N earlier steps toggle: %s" % (toggle.text if toggle else "none"))
if toggle:
toggle.pressed.emit()
_eq(_chips(), ResultTray.MAX_EXPANDED, "expanding shows more steps (capped)")
_check(ms < 4000, "lighting 3,000 steps is quick (%d ms)" % ms)
print(" (3,001-step roll, lit and shown in %d ms)" % ms)
_check(main.rolling.result_text(all, ResultTray.COPY_TEXT).length() < 3001 * 40, "copy text indents are capped")
var line := ResultTray.earlier_line({"root_name": "x", "steps": all})
_check(line.length() < 2000, "Earlier rows show the last few steps of a long chain")
await process_frame
func _test_action_limit() -> void:
_long_chain(20000)
await process_frame
main.start_roll("long_start")
_check(str(main.current.get("halted", "")).begins_with("Stopped after 10,000"), "the action limit is reported: %s" % str(main.current.get("halted", "")))
_check(main.tray._halt.visible and main.tray._halt_label.text.contains("10,000"), "the tray shows the limit clearly")
await process_frame
# ---------------------------------------------------------------- checks
func _eq(got: Variant, want: Variant, what: String) -> void:
if typeof(got) != typeof(want) or got != want:
_failures += 1
print(" ✗ %s (got %s, want %s)" % [what, str(got), str(want)])
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print(" ✗ ", what)