TableTower/tests/test_groups.gd
RobinFiredrake 9fdf65c00b Group cards and templates
Groups: an optional groups list on a collection (frame rect, collapsed,
members, details), saved by TowerBoard and kept by JsonIO. Expanded groups
draw a frame behind their cards with a title bar; collapsed ones become one
compact card that lists the members' lit results, with pipes re-routed to
its inlet and right edge. Build mode adds multi-select (Ctrl/Shift-click,
Ctrl-drag), Group (Ctrl+G), drop in/out of frames, rename, ungroup, delete
with undo and a details editor.

Templates: TemplateKit saves cards, groups or selections with relative
positions, internal pipes and outside pipes by name, detects {$name}
parameters and inserts with fresh ids. TemplateLibrary keeps user templates
in user://templates and lists the built-in ones in templates/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 17:01:34 -06:00

345 lines
16 KiB
GDScript

extends SceneTree
## Group cards: the model and file format, membership, and in the app the
## frame, collapsing (hidden members, re-routed pipes, lit results, choice
## pop-ups), moving, dropping cards in and out, ungroup and delete.
## Run: godot --headless --path . -s res://tests/test_groups.gd -- --sample
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_model()
_test_json()
_test_import()
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
main.rng.seed = 5
await _load(_board_dict())
await _test_group_from_selection()
await _test_collapse()
await _test_lit_and_choice()
await _test_move()
await _test_drop_in_and_out()
await _test_collapse_all_and_fit()
await _test_ungroup_and_delete()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
## start -> a (in G) -> b (choice, in G) -> out
func _board_dict() -> Dictionary:
return {"format_version": 2, "id": "groups-test", "name": "Groups test", "tables": [
{"id": "start", "name": "Start", "x": 40, "y": 60, "entries": [{"id": "e1", "text": "Go", "pipes": ["a"]}]},
{"id": "a", "name": "Alpha", "x": 420, "y": 60, "entries": [
{"id": "e1", "text": "A one", "pipes": ["b"]}, {"id": "e2", "text": "A two", "pipes": ["b"]}]},
{"id": "b", "name": "Bravo", "kind": "choice", "prompt": "Which?", "x": 760, "y": 60, "entries": [
{"id": "e1", "text": "B one", "pipes": ["out"]}, {"id": "e2", "text": "B two", "pipes": ["out"]}]},
{"id": "out", "name": "Outside", "x": 1200, "y": 60, "entries": [{"id": "e1", "text": "Done"}]},
{"id": "loose", "name": "Loose", "x": 40, "y": 520, "entries": [{"id": "e1", "text": "Free"}]},
]}
func _load(d: Dictionary) -> void:
main.data.load_dict(d)
main.lit_entries.clear()
main.lit_pipes.clear()
main.lit_texts.clear()
main._rebuild_cards()
for i in 4:
await process_frame
# ---------------------------------------------------------------- model
func _test_model() -> void:
var b := TowerBoard.new()
b.load_dict(_board_dict())
var g := b.add_group("G", ["a", "b"])
_check(b.group_of("a") == g and b.group_of("b") == g and b.group_of("start") == null, "add_group puts tables in the group")
var h := b.add_group("H", ["b", "nope"])
_check(b.group_of("b") == h and not g.has("b"), "a table moves to its new group (one group per table)")
_check(h.members == ["b"], "missing tables aren't added: %s" % str(h.members))
b.remove_from_group("b")
_check(b.group_of("b") == null and h.members.is_empty(), "remove_from_group")
_check(b.add_to_group("b", g.id) and g.members == ["a", "b"], "add_to_group")
b.move_group(g.id, Vector2(10, 20))
_check(b.get_table("a").position == Vector2(430, 80) and g.position == Vector2(10, 20), "move_group moves the frame and members")
b.remove_table("a")
_check(not g.has("a"), "removing a table removes its membership")
var r := g.fit_rect([Rect2(100, 100, 50, 50)])
_check(r == Rect2(100 - TableGroup.PAD, 100 - TableGroup.PAD - TableGroup.TITLE_H, 50 + TableGroup.PAD * 2, 50 + TableGroup.PAD * 2 + TableGroup.TITLE_H), "fit_rect pads the members and leaves room for the title: %s" % str(r))
var gone := b.delete_group(g.id)
_check(gone == ["b"] and b.get_table("b") == null and b.get_group(g.id) == null, "delete_group removes the group and its tables")
b.ungroup(h.id)
_check(b.groups.is_empty(), "ungroup removes the group")
_check(b.get_table("start").entries[0].pipes.is_empty(), "pipes into deleted tables go")
func _test_json() -> void:
var b := TowerBoard.new()
b.load_dict(_board_dict())
var g := b.add_group("Middle", ["a", "b"])
g.collapsed = true
g.details = "The [b]middle[/b] bit"
g.position = Vector2(400, 0)
g.size = Vector2(700, 300)
var text := b.to_json()
var b2 := TowerBoard.new()
_check(b2.load_json(text), "a board with groups loads")
_check(b2.groups.size() == 1, "one group back")
var g2 := b2.groups[0]
_check(g2.id == g.id and g2.name == "Middle" and g2.collapsed and g2.details == g.details, "id, name, collapsed and details round-trip")
_check(g2.position == Vector2(400, 0) and g2.size == Vector2(700, 300), "rect round-trips")
_check(g2.members == ["a", "b"], "members round-trip")
_check(b2.to_json() == text, "JSON round trip is exact")
# Old files without groups load unchanged, and save without a groups key.
var old := TowerBoard.new()
var src := SampleBoard.create().to_dict()
_check(not src.has("groups"), "boards without groups write no groups key")
_check(old.load_dict(src) and old.groups.is_empty(), "an old file loads with no groups")
_check(old.to_json() == SampleBoard.create().to_json() or JSON.parse_string(old.to_json())["tables"].size() == src["tables"].size(), "an old file saves the same tables")
var v1 := TowerBoard.new()
_check(v1.load_json(JSON.stringify({"format_version": 1, "tables": src["tables"]})) and v1.groups.is_empty(), "a version 1 file still loads")
# Bad group data is cleaned on load.
var messy := _board_dict()
messy["groups"] = [{"id": "g1", "name": "One", "members": ["a", "ghost", "a"]},
{"id": "g1", "name": "Two", "members": ["a", "b"]}, "not a group"]
var b3 := TowerBoard.new()
b3.load_dict(messy)
_check(b3.groups.size() == 2 and b3.groups[0].members == ["a"], "unknown and repeated members dropped: %s" % str(b3.groups[0].members))
_check(b3.groups[1].members == ["b"], "a table stays in its first group only")
_check(b3.groups[0].id != b3.groups[1].id, "duplicate group ids are made unique")
func _test_import() -> void:
var d := _board_dict()
d["groups"] = [{"id": "g", "name": "G", "x": 1, "y": 2, "w": 300, "h": 200, "collapsed": true,
"members": ["a", "Bravo", "ghost"], "details": ""}]
var canon := JsonIO.canonical(d)
_check(canon.has("groups") and canon["groups"][0] == {"id": "g", "name": "G", "x": 1, "y": 2, "w": 300, "h": 200, "collapsed": true, "members": ["a", "Bravo", "ghost"]},
"canonical keeps groups and drops empty details: %s" % str(canon.get("groups")))
_check(not JsonIO.canonical(_board_dict()).has("groups"), "canonical has no groups key without groups")
var r := JsonIO.import_dict(d)
var gl: Array = r["collection"]["groups"]
_check(r["ok"] and gl[0]["members"] == ["a", "b"], "import maps members by id or name and drops unknown ones: %s" % str(gl[0]["members"]))
_check(str(r["warnings"]).contains("ghost"), "import warns about unknown members")
var b := TowerBoard.new()
_check(b.load_dict(r["collection"]) and b.groups.size() == 1 and b.groups[0].collapsed, "an imported collection keeps its groups")
var res := JsonIO.import_json(JsonIO.export_json(b.to_dict()))
_check(res["ok"] and res["collection"]["groups"][0]["members"] == ["a", "b"], "export and import round-trip groups")
# ---------------------------------------------------------------- app
func _group() -> TableGroup:
return main.data.groups[0] if not main.data.groups.is_empty() else null
func _test_group_from_selection() -> void:
main.set_mode(Main.Mode.BUILD)
main.set_selection(["a", "b"])
_check(main.card_for("a").is_selected() and main.selection.size() == 2, "cards show as selected")
_check(main._sel_bar.visible, "the selection toolbar shows in Build")
var g := main.group_selection()
for i in 3:
await process_frame
_check(g != null and g.members == ["a", "b"], "Group makes a group of the selection")
_check(main.selection.is_empty() and not main._sel_bar.visible, "grouping clears the selection")
var node := main.group_node(g.id)
_check(node != null and node.get_parent() == main.board.groups, "an expanded group's frame sits behind the pipes")
var ra := Rect2(main.card_for("a").position, main.card_for("a").size)
var rb := Rect2(main.card_for("b").position, main.card_for("b").size)
_check(g.rect().encloses(ra) and g.rect().encloses(rb), "the frame fits around its members")
_check(is_equal_approx(g.position.x, ra.position.x - TableGroup.PAD), "with padding: %s vs %s" % [str(g.position), str(ra.position)])
_check(node.position == g.position and node.size == g.size, "the frame node follows the group")
main.set_mode(Main.Mode.PLAY)
func _test_collapse() -> void:
var g := _group()
main.toggle_group(g.id)
for i in 3:
await process_frame
var node := main.group_node(g.id)
_check(g.collapsed and node.get_parent() == main.board.cards, "a collapsed group shows as a card")
_check(not main.card_for("a").visible and not main.card_for("b").visible, "its members are hidden")
_check(main.card_for("start").visible and main.card_for("out").visible, "other cards stay")
var paths: Dictionary = main.board.pipes._paths
var into: PackedVector2Array = paths.get("start:e1>a", PackedVector2Array())
_check(not into.is_empty() and into[into.size() - 1].distance_to(node.inlet_point()) < 0.5, "a pipe into a member attaches to the group's inlet")
var outp: PackedVector2Array = paths.get("b:e1>out", PackedVector2Array())
_check(not outp.is_empty() and is_equal_approx(outp[0].x, node.position.x + node.size.x), "a pipe out of a member leaves from the group's right edge")
_check(outp.is_empty() or outp[outp.size() - 1].distance_to(main.card_for("out").inlet_point()) < 0.5, "and still reaches its target")
_check(not paths.has("a:e1>b"), "pipes inside the collapsed group aren't drawn")
_check(main.board.pipes.pipe_at(into[into.size() / 2], 3.0) == "", "re-routed pipes can't be clicked")
var gp: Dictionary = main.board.pipes.group_ports
_check(not gp.is_empty(), "the group card gets an outlet port")
_check(main.data.to_dict()["groups"][0]["collapsed"] == true, "collapsed is saved")
func _test_lit_and_choice() -> void:
var g := _group()
var node := main.group_node(g.id)
# A real roll through the hidden choice card: the pop-up opens and answers.
main.prompt_hook = main._ask_player
main.start_roll("start")
var d: ChoiceDialog = null
for i in 60:
await process_frame
d = main.pending_choice()
if d:
break
_check(d != null, "a choice card hidden in a collapsed group still asks")
_check(main.is_entry_lit("start", "e1") and main.lit_pipes.has("start:e1>a"), "the steps so far light up behind the pop-up")
if d:
d.answer(1)
for i in 240:
await process_frame
if main.current.get("done", false):
break
_check(main.current.get("done", false), "the roll finishes after the answer")
_check(main.is_entry_lit("b", "e2") and main.is_entry_lit("out", "e1"), "the picked option and what follows are lit")
_check(main.lit_pipes.has("b:e2>out"), "the pipe out of the group is lit")
node = main.group_node(g.id)
var keys := main.lit_keys_for_group(g)
_check(keys.has("b:e2") and (keys.has("a:e1") or keys.has("a:e2")), "the group knows its members' lit results: %s" % str(keys))
_check(node.lit_rows.has("b:e2"), "the collapsed group card lists the lit results")
await process_frame
var outp: PackedVector2Array = main.board.pipes._paths.get("b:e2>out", PackedVector2Array())
var row: Control = node.lit_rows.get("b:e2")
if row and not outp.is_empty():
var to_world := main.board.world.get_global_transform().affine_inverse()
var mid := (to_world * row.get_global_rect().get_center()).y
_check(absf(outp[0].y - mid) < 1.0, "a lit result's pipe leaves from its row on the group card")
main.prompt_hook = func(_req: Dictionary) -> Variant: return 0
# Fast roll: lights at once.
main.start_roll("start", true)
for i in 30:
await process_frame
if main.current.get("done", false):
break
_check(main.is_entry_lit("b", "e1"), "a fast roll lights hidden members too")
main.set_group_collapsed(g.id, false)
for i in 3:
await process_frame
_check(main.card_for("a").visible and main.group_node(g.id).get_parent() == main.board.groups, "expanding shows the members again")
func _test_move() -> void:
var g := _group()
var before_a := main.data.get_table("a").position
var before_g := g.position
main.move_group(g.id, Vector2(100, 50))
_check(main.data.get_table("a").position == before_a + Vector2(100, 50), "moving a group moves its members")
_check(main.card_for("b").position == main.data.get_table("b").position, "member cards follow")
_check(g.position == before_g + Vector2(100, 50) and main.group_node(g.id).position == g.position, "and the frame")
_check(main.data.get_table("start").position == Vector2(40, 60), "non-members stay put")
# Collapsed groups move their hidden members too.
main.set_group_collapsed(g.id, true)
await process_frame
main.move_group(g.id, Vector2(-100, -50))
_check(main.data.get_table("a").position == before_a, "a collapsed group moves its hidden members")
main.set_group_collapsed(g.id, false)
for i in 3:
await process_frame
func _test_drop_in_and_out() -> void:
main.set_mode(Main.Mode.BUILD)
for i in 3:
await process_frame
var g := _group()
var loose := main.card_for("loose")
main.begin_card_drag(loose)
var inside := g.position + Vector2(40, TableGroup.TITLE_H + 30)
main.drag_card(loose, inside)
_check(main._drag_over == main.group_node(g.id), "the frame under a dragged card lights as a drop target")
main.end_card_drag(loose)
_check(g.has("loose"), "dropping a card in a frame adds it to the group")
for i in 3:
await process_frame
_check(g.rect().encloses(Rect2(loose.position, loose.size)), "the frame grows to fit")
main.begin_card_drag(loose)
main.drag_card(loose, g.position + g.size + Vector2(300, 300))
main.end_card_drag(loose)
_check(not g.has("loose") and main.data.group_of("loose") == null, "dragging a card out of its frame takes it out")
# Multi-select drag moves every selected card.
main.set_selection(["start", "loose"])
var s0 := main.card_for("start").position
var l0 := loose.position
main.begin_card_drag(loose)
main.drag_card(loose, l0 + Vector2(30, 40))
main.end_card_drag(loose)
_check(main.card_for("start").position == s0 + Vector2(30, 40) and loose.position == l0 + Vector2(30, 40), "selected cards move together")
main.clear_selection()
main.select_in_rect(Rect2(main.card_for("out").position - Vector2(5, 5), Vector2(20, 20)))
_check(main.selection.keys() == ["out"], "a rubber band selects the cards it touches: %s" % str(main.selection.keys()))
main.clear_selection()
main.set_mode(Main.Mode.PLAY)
for i in 3:
await process_frame
func _test_collapse_all_and_fit() -> void:
var g := _group()
main.set_all_collapsed(true)
await process_frame
_check(g.collapsed and not main.card_for("a").visible, "Collapse all collapses groups too")
_check(main._collapse_all.text == "Expand all", "the button then offers Expand all")
# Fit ignores hidden members: move one far away; the bounds don't reach it.
main.data.get_table("a").position = Vector2(30000, 30000)
main.card_for("a").position = Vector2(30000, 30000)
var bounds := main.board.content_bounds()
_check(bounds.end.x < 5000.0 and bounds.has_point(main.group_node(g.id).position + Vector2(5, 5)),
"Fit counts the group card and leaves out its hidden cards: %s" % str(bounds))
main.data.get_table("a").position = Vector2(420, 60)
main.card_for("a").position = Vector2(420, 60)
main.set_all_collapsed(false)
await process_frame
_check(not g.collapsed and main.card_for("a").visible, "Expand all expands groups")
func _test_ungroup_and_delete() -> void:
var g := _group()
main.ungroup(g.id)
await process_frame
_check(main.data.groups.is_empty() and main.data.get_table("a") != null and main.card_for("a").visible, "Ungroup keeps the cards")
main._undo()
await process_frame
g = _group()
_check(g != null and g.members == ["a", "b"], "Ungroup can be undone")
main.confirm_delete_group(g.id)
await process_frame
var modal: ModalCard = null
for c in main.get_children():
if c is ModalCard:
modal = c
_check(modal != null, "Delete group asks first")
if modal:
for b in modal.footer.get_children():
if b is Button and (b as Button).text == "Delete group and cards":
(b as Button).pressed.emit()
await process_frame
_check(main.data.groups.is_empty() and main.data.get_table("a") == null and main.data.get_table("b") == null, "deleting the group deletes its cards")
_check(main.card_for("a") == null and main.data.get_table("start").entries[0].pipes.is_empty(), "their cards and the pipes into them go")
_check(main._toast.visible and main._toast_undo.visible, "with an undo toast")
main._undo()
await process_frame
_check(main.data.groups.size() == 1 and main.data.get_table("a") != null and main.card_for("b") != null, "undo brings the group and its cards back")
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print("FAIL ", what)