TableTower/tests/test_templates.gd
RobinFiredrake 9fcaf5c123 No more drag walls; drag box selects; middle/Space-drag pans; groups move with the selection
Cards, selections, new cards and inserted templates may sit anywhere,
including left of or above the old edge. In Build a drag on empty space
draws a selection box (Ctrl/Shift adds); middle-drag or Space+drag pans
(a plain drag still pans in Play). The box also picks up collapsed groups
it touches and expanded groups it covers, and dragging any selected card
or group moves the whole selection (MainSelection). Ctrl-click a group's
title to add it to the selection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 18:30:13 -06:00

335 lines
17 KiB
GDScript

extends SceneTree
## Templates: saving (placeholder detection, relative positions, pipes kept or
## recorded by name), inserting (substitution, fresh ids, internal pipes kept,
## outside pipes relinked or reported), the library and the built-in
## templates, and the app's save, list and insert.
## Run: godot --headless --path . -s res://tests/test_templates.gd -- --sample
const TMP_ROOT := "user://test_templates_tmp"
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
_test_make()
_test_insert()
_test_validate()
_test_library_memory()
_test_library_files()
_test_builtins()
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 run.")
quit(2)
return
await _test_app()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
## A check table and its outcome table, piping to "Wounds" outside.
func _board() -> TowerBoard:
var b := TowerBoard.new()
b.load_dict({"tables": [
{"id": "chk", "name": "{$skill} check", "x": 300, "y": 200, "dice": "2d6 + @{$skill} - {$target}",
"details": "Target {$target}", "entries": [
{"id": "e1", "text": "Fail", "range": [-1, -1], "effects": "@{$skill}_fails += 1", "pipes": ["wounds"]},
{"id": "e2", "text": "Pass", "range": [0, 0], "pipes": [{"table": "outcome", "count": "{$n}", "save_as": "{$skill}_result"}]}]},
{"id": "outcome", "name": "Outcome", "kind": "choice", "prompt": "How did {$skill} go?", "save_as": "@{$skill}_how",
"x": 600, "y": 260, "entries": [{"id": "e1", "text": "Well"}, {"id": "e2", "text": "Badly", "pipes": ["wounds"]}]},
{"id": "wounds", "name": "Wounds", "x": 900, "y": 200, "entries": [{"id": "e1", "text": "Ouch"}]},
]})
return b
func _test_make() -> void:
var b := _board()
var tpl := TemplateKit.make(b, ["chk", "outcome"], "selection", "Skill check", "A check")
_check(tpl["format_version"] == 1 and tpl["kind"] == "selection" and tpl["name"] == "Skill check", "header fields")
var names: Array = []
for p: Dictionary in tpl["params"]:
names.append(p["name"])
_check(names == ["skill", "target", "n"], "placeholders detected in order: %s" % str(names))
var t0: Dictionary = tpl["tables"][0]
var t1: Dictionary = tpl["tables"][1]
_check(t0["x"] == 0 and t0["y"] == 0 and t1["x"] == 300 and t1["y"] == 60, "positions are relative to the top-left: %s %s" % [str(t0["x"]), str(t1["x"])])
_check(t0["entries"][1]["pipes"] == [{"table": "outcome", "count": "{$n}", "save_as": "{$skill}_result"}], "internal threads keep their target and options: %s" % str(t0["entries"][1]["pipes"]))
_check(t0["entries"][0]["pipes"] == [{"table": "Wounds", "outside": true}], "an outside thread is recorded by name: %s" % str(t0["entries"][0]["pipes"]))
_check(not JSON.stringify(tpl).contains("\"wounds\""), "the outside table itself isn't in the template")
_check(TemplateKit.summary(tpl) == "2 cards: roll, choice", "summary: %s" % TemplateKit.summary(tpl))
# A group template keeps its group, relative to the frame's corner.
var g := b.add_group("Check {$skill}", ["chk", "outcome"])
g.position = Vector2(270, 130)
g.size = Vector2(620, 400)
var gt := TemplateKit.make(b, [], "group", "Group", "", [g.id])
_check((gt["tables"] as Array).size() == 2 and (gt["groups"] as Array).size() == 1, "a group template has its members and the group")
_check(gt["groups"][0]["x"] == 0 and gt["groups"][0]["y"] == 0 and gt["tables"][0]["x"] == 30 and gt["tables"][0]["y"] == 70, "positions relative to the group's corner")
_check(gt["groups"][0]["members"] == ["chk", "outcome"] and not gt["groups"][0].has("id"), "group members by template table id")
_check(TemplateKit.detect_params(gt).has("skill"), "placeholders in a group name count")
_check(TemplateKit.probe("2d6 + @{$skill} - {$target}") == "2d6 + @p - p" and Expr.check(TemplateKit.probe("@{$x} + {$y}")) == "", "probe makes placeholder text checkable")
_check(TableSettingsDialog.dice_ok_text("2d6 + @{$skill} - {$target}"), "Build accepts placeholders in dice")
func _test_insert() -> void:
var src := _board()
var tpl := TemplateKit.make(src, ["chk", "outcome"], "selection", "Skill check")
var b := TowerBoard.new()
b.load_dict({"tables": [{"id": "w1", "name": "wounds", "x": 0, "y": 0, "entries": [{"id": "e1", "text": "Hurt"}]}]})
var r := TemplateKit.insert(tpl, {"skill": "pilot", "target": "8", "n": "2"}, b, Vector2(1000, 500))
var tables: Array = r["tables"]
_check(tables.size() == 2 and b.tables.size() == 3, "insert adds the template's tables")
var chk: RollTable = tables[0]
var oc: RollTable = tables[1]
_check(chk.name == "pilot check" and chk.dice == "2d6 + @pilot - 8" and chk.details == "Target 8", "names, dice and details substituted: %s / %s" % [chk.name, chk.dice])
_check(chk.entries[0].effects == "@pilot_fails += 1", "effects substituted")
_check(oc.prompt == "How did pilot go?" and oc.save_as == "@pilot_how", "prompts and save_as substituted")
_check(chk.id != "chk" and oc.id != "outcome" and chk.id != oc.id, "fresh table ids")
_check(chk.entries[0].id != "e1" and chk.entries[0].id != chk.entries[1].id, "fresh entry ids")
_check(chk.position == Vector2(1000, 500) and oc.position == Vector2(1300, 560), "placed at the origin, keeping the layout")
_check(chk.entries[1].pipes == [oc.id] and chk.entries[1].count_expr(oc.id) == "" and chk.entries[1].count_for(oc.id) == 2, "internal threads follow the new ids, with their count")
_check(chk.entries[1].save_for(oc.id) == "pilot_result", "and their save_as, substituted")
_check(chk.entries[0].pipes == ["w1"] and oc.entries[1].pipes == ["w1"], "outside threads relink to the table with that name (any case)")
_check((r["relinked"] as Array).size() == 2 and (r["dropped"] as Array).is_empty(), "relinked threads are reported: %s" % str(r["relinked"]))
var again := TemplateKit.insert(tpl, {}, b, Vector2.ZERO)
_check((again["tables"][0] as RollTable).id != chk.id, "a second insert gets new ids again")
_check((again["tables"][0] as RollTable).name == "{$skill} check", "missing values without a default stay as typed")
var empty := TowerBoard.new()
var r2 := TemplateKit.insert(tpl, {"skill": "a", "target": "1", "n": "1"}, empty, Vector2.ZERO)
_check((r2["dropped"] as Array).size() == 2 and (r2["tables"][0] as RollTable).entries[0].pipes.is_empty(), "outside threads with no table of that name are dropped and listed: %s" % str(r2["dropped"]))
# Group templates make the group.
var gsrc := _board()
var g := gsrc.add_group("{$skill} block", ["chk", "outcome"])
g.position = Vector2(280, 140)
var gt := TemplateKit.make(gsrc, [], "group", "G", "", [g.id])
var b3 := TowerBoard.new()
var r3 := TemplateKit.insert(gt, {"skill": "stealth"}, b3, Vector2(100, 100))
_check(b3.groups.size() == 1 and b3.groups[0].name == "stealth block", "inserting a group template creates the group")
_check(b3.groups[0].members.size() == 2 and b3.groups[0].members[0] == (r3["tables"][0] as RollTable).id, "with the new tables as members")
_check(b3.groups[0].id != g.id and b3.groups[0].position == Vector2(100, 100), "a fresh group id, placed at the origin")
func _test_validate() -> void:
_check(not TemplateKit.validate("nope")["ok"], "text isn't a template")
_check(not TemplateKit.validate({"tables": []})["ok"], "a template needs tables")
_check(not TemplateKit.validate({"format_version": 9, "tables": [{"entries": []}]})["ok"], "newer versions are refused")
var r := TemplateKit.validate({"tables": [{"name": "{$a}", "entries": []}], "params": [{"name": "b"}]})
var names: Array = []
for p: Dictionary in r["template"]["params"]:
names.append(p["name"])
_check(r["ok"] and names == ["b", "a"], "listed params are kept and unlisted placeholders added: %s" % str(names))
_check(r["template"]["name"] == "Untitled template" and r["template"]["kind"] == "selection", "defaults filled in")
func _test_library_memory() -> void:
var lib := TemplateLibrary.new("")
var tpl := TemplateKit.make(_board(), ["chk"], "card", "My check")
var id := lib.add(tpl)
_check(id == "my-check" and lib.exists(id), "add saves under a slug of the name")
_check(lib.add(tpl) == "my-check-2", "names that are taken get a number")
_check(lib.get_template(id)["name"] == "My check", "get_template")
_check(lib.rename(id, "Renamed") and lib.get_template(id)["name"] == "Renamed", "rename keeps the id")
var text := lib.export_text(id)
_check(text.contains("\"Renamed\""), "export text")
var imp := lib.import_text(text)
_check(imp["ok"] and lib.get_template(imp["id"])["name"] == "Renamed", "import text")
_check(not lib.import_text("{\"tables\": 3}")["ok"] and not lib.import_text("garbage")["ok"], "bad files are refused")
_check(lib.delete(id) and not lib.exists(id), "delete")
var builtin_id := ""
for row: Dictionary in lib.list():
if row["builtin"]:
builtin_id = row["id"]
_check(builtin_id != "" and not lib.rename(builtin_id, "x") and not lib.delete(builtin_id), "built-in templates can't be renamed or deleted")
func _test_library_files() -> void:
_wipe(TMP_ROOT)
var lib := TemplateLibrary.new(TMP_ROOT)
var id := lib.add(TemplateKit.make(_board(), ["chk", "outcome"], "selection", "Two cards"))
_check(FileAccess.file_exists(TMP_ROOT.path_join("templates/two-cards.json")), "user templates are files in templates/")
var lib2 := TemplateLibrary.new(TMP_ROOT)
var found := false
for row: Dictionary in lib2.list():
if row["id"] == id and not row["builtin"]:
found = true
_check(found, "a new library lists the saved template")
_check(lib2.rename(id, "Renamed") and TemplateLibrary.new(TMP_ROOT).get_template(id)["name"] == "Renamed", "rename is saved")
_check(lib2.delete(id) and not FileAccess.file_exists(TMP_ROOT.path_join("templates/two-cards.json")), "delete removes the file")
_wipe(TMP_ROOT)
func _test_builtins() -> void:
var lib := TemplateLibrary.new("")
var rows: Array = []
for row: Dictionary in lib.list():
if row["builtin"]:
rows.append(row)
_check(rows.size() >= 5, "five built-in templates ship: %d" % rows.size())
_check(lib.errors.is_empty(), "every built-in template reads: %s" % str(lib.errors))
var want := {"builtin:skill-check": false, "builtin:ask-and-repeat": false, "builtin:pick-menu": false, "builtin:counter": false, "builtin:simple-sheet": false}
for row: Dictionary in rows:
if want.has(row["id"]):
want[row["id"]] = true
var tpl: Dictionary = row["template"]
var b := TowerBoard.new()
var r := TemplateKit.insert(tpl, {}, b, Vector2(50, 50))
var text := b.to_json()
_check(not text.contains("{$"), "%s: defaults fill every placeholder" % row["id"])
_check((r["dropped"] as Array).is_empty(), "%s: no threads lead outside" % row["id"])
var declared := TemplateKit.detect_params(tpl)
for p: Dictionary in tpl["params"]:
_check(declared.has(str(p["name"])), "%s: param %s is used" % [row["id"], p["name"]])
_check(str(p.get("label", "")) != "" and str(p.get("default", "")) != "", "%s: param %s has a label and default" % [row["id"], p["name"]])
# Every inserted card rolls headless without errors.
for t in b.tables:
if t.kind == RollTable.KIND_VARIABLE:
continue
var ctx := Roller.new_context(b, RandomNumberGenerator.new())
var n := Roller.roll(b, t.id, ctx.rng, 0, {}, ctx)
_check(not n.is_empty() and not n.has("stop"), "%s: %s rolls" % [row["id"], t.name])
var steps := Roller.flatten(n, [])
for s: Dictionary in steps:
for l: Variant in s.get("log", []):
if l is Dictionary and l.get("error", false):
_check(false, "%s: %s logs an error: %s" % [row["id"], t.name, str(l)])
for k: String in want:
_check(want[k], "built-in %s is listed" % k)
var chk := lib.get_template("builtin:skill-check")
var b2 := TowerBoard.new()
var r2 := TemplateKit.insert(chk, {"skill": "pilot", "target": "8"}, b2, Vector2.ZERO)
var t2: RollTable = r2["tables"][0]
_check(t2.kind == RollTable.KIND_CHECK and t2.check_dice == "2d6" and t2.check_mod == "@pilot" and t2.check_target == "8" and t2.name == "pilot check, 8+",
"the skill check is a Check card: 2d6 + @pilot against 8 (%s + %s vs %s)" % [t2.check_dice, t2.check_mod, t2.check_target])
var passes := 0
var rng := RandomNumberGenerator.new()
rng.seed = 3
for i in 400:
var ctx := Roller.new_context(b2, rng, {"pilot": {"value": 2, "source": ""}})
var n := Roller.roll(b2, t2.id, rng, 0, {}, ctx)
if n.get("entry") and (n["entry"] as TableEntry).text == "Success":
passes += 1
# 2d6 + 2 >= 8 means 2d6 >= 6: 26/36 = 72%.
_check(passes > 250 and passes < 330, "with a +2 modifier, a target of 8 succeeds about 72%% of the time (%d/400)" % passes)
func _test_app() -> void:
main.data.load_dict({"id": "tpl-test", "name": "Templates", "tables": [
{"id": "start", "name": "Start", "x": 40, "y": 40, "entries": [{"id": "e1", "text": "Go"}]},
{"id": "wounds", "name": "Wounds", "x": 40, "y": 400, "entries": [{"id": "e1", "text": "Ouch"}]}]})
main._rebuild_cards()
await process_frame
var lib := main.templating.templates()
_check(lib.root == "", "with --sample, templates stay in memory")
# Save a card from the board through the dialog.
var before := lib.list().size()
main.data.get_table("start").name = "{$who} starts"
main.save_template_from(["start"], "card")
await process_frame
var dlg := _top_modal()
_check(dlg != null and dlg.title_label.text == "Save as template", "the save dialog opens")
if dlg:
_check(dlg.body.get_child_count() > 3, "it lists the parameters")
_press(dlg, "Save template")
await process_frame
_check(lib.list().size() == before + 1, "Save template adds it to the library")
main.data.get_table("start").name = "Start"
# The picker lists built-ins and user templates, and searches.
var picker := main.templating.open_template_picker()
await process_frame
var ids := picker.shown_ids()
_check(ids.has("builtin:skill-check") and ids.has("builtin:counter"), "the list shows the built-in templates")
picker._search.text = "counter"
picker.refresh()
_check(picker.shown_ids() == ["builtin:counter"], "search filters the list: %s" % str(picker.shown_ids()))
picker.select("builtin:counter")
_press(picker, "Insert")
await process_frame
var form := _top_modal()
_check(form != null and form.title_label.text.begins_with("Insert"), "a template with parameters asks for them")
if form:
_press(form, "Insert")
for i in 3:
await process_frame
var counter := main.data.groups.back() as TableGroup if not main.data.groups.is_empty() else null
_check(counter != null and counter.name == "Counter" and counter.members.size() == 2, "inserting the counter makes its group")
var var_card: RollTable = null
for t in main.data.tables:
if t.kind == RollTable.KIND_VARIABLE and t.var_name == "counter":
var_card = t
_check(var_card != null and main.card_for(var_card.id) != null, "its variable card is on the spread")
# Insert with values and an outside pipe that relinks.
var tpl := TemplateKit.make(_board(), ["chk", "outcome"], "selection", "Check")
var r := main.templating.insert_template(tpl, {"skill": "stealth", "target": "9", "n": "1"})
await process_frame
var chk: RollTable = r["tables"][0]
_check(main.card_for(chk.id) != null and chk.name == "stealth check", "the inserted cards appear")
_check(chk.entries[0].pipes == ["wounds"], "an outside thread relinks to Wounds on this spread")
var center := main.board.screen_to_world(main.board.size / 2.0)
var ext := TemplateKit.extent(tpl)
_check(chk.position.distance_to((center - ext / 2.0).round()) < 2.0, "placed around the view centre")
_check(main.top_bar._toast.visible and main.top_bar._toast_undo.visible, "an undo toast follows")
main.top_bar._undo()
await process_frame
_check(main.data.get_table(chk.id) == null, "undo removes the inserted cards")
# Dropped pipes get a report.
main.data.remove_table("wounds")
main._rebuild_cards()
main.templating.insert_template(tpl, {"skill": "x", "target": "1", "n": "1"})
await process_frame
var rep := _top_modal()
_check(rep != null and rep.title_label.text.begins_with("Inserted"), "threads that can't relink are listed in a report")
if rep:
rep.close()
# The card settings dialog offers Save as template.
main.set_mode(Main.Mode.BUILD)
main.open_table_settings("start")
await process_frame
var sd := _top_modal()
var has_btn := false
if sd:
for b in sd.footer.get_children():
if b is Button and (b as Button).text == "Save as template…":
has_btn = true
_press(sd, "Save as template…")
await process_frame
_check(has_btn and _top_modal() != null and _top_modal().title_label.text == "Save as template", "settings → Save as template opens the save dialog")
main.set_mode(Main.Mode.PLAY)
func _top_modal() -> ModalCard:
var top: ModalCard = null
for c in main.get_children():
if c is ModalCard and not c.is_queued_for_deletion():
top = c
return top
func _press(d: ModalCard, text: String) -> void:
for b in d.footer.get_children():
if b is Button and (b as Button).text == text:
(b as Button).pressed.emit()
return
_check(false, "no button %s" % text)
func _wipe(dir: String) -> void:
var tdir := dir.path_join("templates")
if DirAccess.dir_exists_absolute(tdir):
for f in DirAccess.get_files_at(tdir):
DirAccess.remove_absolute(tdir.path_join(f))
DirAccess.remove_absolute(tdir)
if DirAccess.dir_exists_absolute(dir):
DirAccess.remove_absolute(dir)
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print("FAIL ", what)