TableTower/tests/test_logic_ui.gd
RobinFiredrake 5941733af1 Sheets phase D: sheets on spreads as linked Sheet cards
- A Sheet card can show a sheet file (sheet, prefix): first-tab preview,
  Open sheet with a way back, the spread's Play/Build in the editor.
- Rolls read and write "Use in tables" boxes as @name or @prefix_name;
  locked boxes and formulas/lists keep their values; changed boxes glow.
- A roll reaching the card shows the sheet's text (SheetText) in the
  tray; text boxes also show spread values when on the spread.
- Old template Sheet cards migrate to a sheet with one text box (not in
  Help demos). Card palette lists your sheets.
- Sheet canvas: tiled grid (smooth panning); boxes no longer overlap
  (nearest free spot, drags stop short; Alt places freely).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 16:52:41 -06:00

447 lines
20 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 AppTestBase
## 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: tools/run_tests.sh logic_ui
## (--sample keeps the app from reading or writing saved collections.)
const DEMO := "res://examples/logic_demo.json"
func run() -> void:
if not await start_main(false):
return
main.rng.seed = 11
_test_demo_file()
await _load_demo()
_test_cards()
await _test_scripted()
await _test_question_animates()
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()
finish()
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 Spread ▾ → Import: %s" % str(r["errors"]))
var b := TowerBoard.new()
_check(b.load_json(text), "the demo loads as a spread")
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.dice == "2d6" and check.dice_mod == "@luck", "the demo's room check rolls 2d6 with Luck as its modifier")
_check(check.clamps() and not RollRange.natural_reach(check, check.entries[3]), "its vault result is only reached with luck")
_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() == 4, "the check table shows its four ranges")
var nums: Array = []
for eid: String in check.rows_ui.parts:
var num: Label = check.rows_ui.parts[eid]["num"]
nums.append(num.text if num else "")
_eq(nums, ["≤6", "7–9", "10–12", "13+"], "a table with a modifier labels 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 repeat 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(TableCardText.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", true)
_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 fast 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 repeat")
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.value_ui.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(sheet.table.sheet_id != "" and sheet.find_child("SheetPreview", true, false) != null, "the old sheet card was migrated to a sheet file")
_check(Formatter.strip_tags(main.tray._headline_text.text).contains("HP %s" % Expr.format_value(_var("hp"))), "the headline shows the sheet up to date")
main.prompt_hook = main.rolling._ask_player
## A normal (not fast) roll animates up to a question and on after it, as a
## pause does, and its pop-up fades in; Skip animations makes it all instant.
func _test_question_animates() -> void:
var log: Array = []
main.prompt_hook = _scripted({"text": "Brin", "number": 1, "pick": 1}, log)
main.start_roll("start")
_eq(log.size(), 0, "a normal roll animates before its first question")
for i in 1200:
await process_frame
if main.current.get("done", false):
break
_check(main.current.get("done", false) and not main.current.get("fast", false), "the roll animates on after the answers")
SkipAnimations.set_on(main, true)
log.clear()
main.start_roll("start")
_check(log.size() >= 3, "Skip animations: the questions come at once")
SkipAnimations.set_on(main, false)
main.prompt_hook = main.rolling._ask_player
var dialog := ModalCard.new("Plain")
_check(not dialog.animate_in, "pop-ups don't animate unless a roll asks for it")
dialog.free()
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 repeat'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", true)
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", true)
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", true)
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", true)
_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", true)
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").value_ui.var_value.text, "42", "the variable card follows an edit")
var report := main.data.get_table("report")
var report_doc := main.sheet_links.load_doc(report.sheet_id)
var shown := main.sheet_links.expand(report_doc, str(report_doc.tabs[0]["boxes"][0].value))
_check(Formatter.strip_tags(shown).contains("Gold 42"), "the sheet's text box follows a spread value")
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").value_ui.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 spread 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)
# ---------------------------------------------------------------- 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 threads 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"), "", "thread counts take expressions")
_check(PipePopover._count_error("@terms +") != "", "bad thread 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 thread")
# 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 item: Dictionary in CardCatalog.ITEMS:
var t := main.editing.add_table(str(item["kind"]), str(item["sub"]), Vector2.INF, str(item["variant"]))
_check(t.kind == item["kind"] and main.card_for(t.id) != null and t.name == item["name"], "the palette adds a %s" % str(item["label"]))
if item["variant"] == CardCatalog.VARIANT_DICE:
_check(t.is_ranged() and t.entries[0].has_range, "a dice table starts ranged")
if item["variant"] == CardCatalog.VARIANT_DECK:
_check(t.card_mode, "a deck starts in Deck mode")
_eq(main.data.tables.size(), n + CardCatalog.ITEMS.size(), "one card per catalog 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(320)
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(), 321, "a 321-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 == "+309 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 320 steps is quick (%d ms)" % ms)
print(" (321-step roll, lit and shown in %d ms)" % ms)
_check(main.rolling.result_text(all, ResultTray.COPY_TEXT).length() < 321 * 40, "copy text indents are capped")
var line := EarlierRolls.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
# ---------------------------------------------------------------- checks