TableTower/tests/test_plain_display.gd
RobinFiredrake 44a814cba9 Plain Build display: plain rules on cards, pipes and tray, Why this?, check/collection/inputs visuals
- RulesView (ui/rules_view.gd): plain-or-text helpers over Describe, reading
  Main.rules_plain() when present (else StateStore, else plain; --rules=text
  for screenshots) and refreshing on Main.rules_view_changed.
- Cards: effect chips, router cases, option sources, show_if, loop rules,
  expression dice and variable kinds read in plain words. Build cards drop the
  inline effects / show_if / condition / details editors for plain chips;
  result text and names stay inline. Row clicks call main.select_result();
  the selected row gets a copper bar (set_selected_entry / inspector_selection).
- Check cards: 2D badge, the rule as a sentence, Success / Failure outlets.
  Collection cards: live members and "+ Add" (main.select_card). Inputs:
  a dashed "Input Tier · starts at 1" box.
- Pipe labels via Describe.pipe, nudged apart and cut to the gap.
- Tray: plain captions (inputs, checks, cases), effect lines from why facts,
  and a "Why this?" button opening a WhyPopover; hovers show the same reasons.
- Previews and the choice pop-up read conditions, effects and option sources
  in plain words. Style.rules_switch() for the Plain words / Text switch.
- Describe: empty text reads "empty" ("Loot is not empty").
- tests/test_plain_display.gd; option and choice tests pin the Text view
  where they check stored text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:30:55 -06:00

408 lines
20 KiB
GDScript
Raw Permalink 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
## The display side of Plain Build (docs/PLAIN.md §6): plain chips and lines
## on cards and their text-mode twins, the switch refreshing them, pipe
## labels, check / collection / inputs visuals, "Why this?" sentences and the
## tray's button, and Build-mode row selection.
## Run: godot --headless --path . -s res://tests/test_plain_display.gd -- --sample
##
## Main here is a small subclass with the hooks the Build inspector adds
## (rules_plain(), rules_view_changed, select_result(), select_card()), so the
## display can be tested on its own.
var _failures := 0
var main: Main
const FAKE_MAIN := """extends Main
%s
var fake_plain := true
var picked: Array = []
func rules_plain() -> bool:
return fake_plain
func select_result(tid: String, eid: String) -> void:
picked.append([tid, eid])
func select_card(tid: String) -> void:
picked.append(["card", tid])
"""
const BOARD := {
"format_version": 2, "id": "plain-display", "name": "Plain display",
"tables": [
{"id": "v_str", "name": "Strength", "kind": "variable", "var_name": "str", "initial": "9", "x": 40, "y": 600, "entries": []},
{"id": "v_luck", "name": "Luck", "kind": "variable", "var_name": "luck", "initial": "2", "x": 360, "y": 600, "entries": []},
{"id": "gate", "name": "Force the gate", "kind": "check", "check_dice": "2d6", "check_mod": "dm(@str)", "check_target": "8",
"x": 40, "y": 40, "entries": [
{"id": "ok", "text": "the bars give", "pipes": ["beyond"]},
{"id": "no", "text": "it holds", "effects": "@luck -= 1"}]},
{"id": "beyond", "name": "Beyond the gate", "x": 380, "y": 40, "entries": [
{"id": "e1", "text": "A storeroom", "pipes": [{"table": "loot", "with": {"tier": "1"}}]},
{"id": "e2", "text": "The warden's vault", "effects": "@luck -= 1",
"pipes": [{"table": "loot", "when": "@luck >= 2", "with": {"tier": "3"}}, {"table": "learn", "otherwise": true}]}]},
{"id": "loot", "name": "Loot", "dice": "1d6 + tier", "inputs": [{"name": "tier", "label": "Tier", "default": "1"}],
"x": 760, "y": 40, "entries": [
{"id": "e1", "text": "A purse of coins", "range": [2, 3]},
{"id": "e2", "text": "A curio", "range": [4, 6]},
{"id": "e3", "text": "A relic", "range": [7, 9], "effects": "@skill_recon += 1"}]},
{"id": "skills", "name": "Skills", "kind": "variable", "var_type": "collection", "var_name": "skill", "x": 760, "y": 600, "entries": []},
{"id": "learn", "name": "Learn from it", "kind": "choice", "prompt": "Raise one of your skills.",
"options_from": "@skill_*", "options_where": "option_value >= 1", "x": 1100, "y": 40, "entries": [
{"id": "chosen", "text": "Chosen", "effects": "@[option] += 1"},
{"id": "rest", "text": "Rest instead", "show_if": "@luck <= 1"}]},
{"id": "climb", "name": "Climb out", "kind": "router", "x": 380, "y": 400, "entries": [
{"id": "c1", "text": "Haul yourself up", "when": "@str >= 10"},
{"id": "c2", "text": "Slip back", "effects": "@luck -= 1"}]},
{"id": "rounds", "name": "Rounds", "kind": "loop", "loop": "while", "loop_expr": "@luck > 0", "x": 1100, "y": 400,
"entries": [{"id": "e1", "text": "Each time"}, {"id": "e2", "text": "Afterwards"}]},
]}
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_why_sentences()
_test_rules_view_helpers()
main = _make_main()
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 = 7
main.data.load_json(JSON.stringify(BOARD))
main.current = {}
main._rebuild_cards()
main.tray.render()
for i in 3:
await process_frame
_test_card_chips()
await _test_switch()
_test_pipe_labels()
_test_router_and_choice()
await _test_check_card()
await _test_collection_and_inputs()
await _test_tray_why()
await _test_roll_why()
await _test_build_rows()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
## Main with the inspector's hooks (only the signal is skipped when Main
## already declares it).
func _make_main() -> Main:
var has_signal := false
for s: Dictionary in (load("res://ui/main.gd") as Script).get_script_signal_list():
if str(s["name"]) == "rules_view_changed":
has_signal = true
var sc := GDScript.new()
sc.source_code = FAKE_MAIN % ("" if has_signal else "signal rules_view_changed")
sc.reload()
var m: Main = sc.new()
m.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
return m
func _set_plain(on: bool) -> void:
main.set("fake_plain", on)
main.emit_signal("rules_view_changed")
# ---------------------------------------------------------------- helpers
func _texts(n: Node, out: PackedStringArray = PackedStringArray()) -> PackedStringArray:
if n is Label:
out.append((n as Label).text)
elif n is RichTextLabel:
out.append(Formatter.strip_tags((n as RichTextLabel).text))
elif n is Button:
out.append((n as Button).text)
elif n is LineEdit:
out.append((n as LineEdit).text)
for c in n.get_children():
_texts(c, out)
return out
func _has(n: Node, needle: String) -> bool:
for t in _texts(n):
if t.contains(needle):
return true
return false
func _with_meta(n: Node, key: String, out: Array = []) -> Array:
if n.has_meta(key):
out.append(n)
for c in n.get_children():
_with_meta(c, key, out)
return out
func _chips(card: TableCard) -> PackedStringArray:
var out := PackedStringArray()
for c: Node in _with_meta(card, "effects_chip"):
out.append(str(c.get_meta("effects_chip")))
return out
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print(" ✗ ", what)
func _eq(got: Variant, want: Variant, what: String) -> void:
if got != want:
_failures += 1
print(" ✗ %s: got %s, want %s" % [what, var_to_str(got), var_to_str(want)])
# ---------------------------------------------------------------- pure parts
func _board() -> TowerBoard:
var b := TowerBoard.new()
b.load_json(JSON.stringify(BOARD))
return b
func _test_why_sentences() -> void:
var b := _board()
var check := {"type": "check", "dice": "2d6", "mod_expr": "dm(@str)", "target_expr": "8", "faces": [3, 4],
"nat": 7, "mod": 1, "total": 8, "target": 8, "cmp": "ge", "success": true}
var when_f := {"type": "when", "to": "loot", "expr": "@luck >= 2", "values": {"@luck": 1}, "result": false}
var other := {"type": "otherwise", "to": "learn", "result": true}
var case_f := {"type": "case", "index": 0, "expr": "@str >= 10", "values": {"@str": 9}, "result": false}
var eff := {"type": "effect", "var": "@luck", "op": "-=", "before": 2, "after": 1}
var inp := {"type": "input", "name": "tier", "value": 3, "from": "pipe"}
_eq(Describe.why(check, b), "Rolled 3 + 4 = 7, +1 = 8: needed 8 or more, success", "check fact")
_eq(Describe.why(when_f, b), "Skipped Loot because Luck was 1 (needs 2 or more)", "when fact")
_eq(Describe.why(other, b), "Took Learn from it because no condition was true", "otherwise fact")
_eq(Describe.why(case_f, b), "Case 1 didn't match because Strength was 9 (needs 10 or more)", "case fact")
_eq(Describe.why(eff, b), "Luck went from 2 to 1", "effect fact")
_eq(Describe.why(inp, b), "Tier was 3 (from the pipe)", "input fact")
_check(Describe.why(when_f, b, false).contains("@luck >= 2"), "text mode keeps the rule as written")
# A step's reasons: the parent's pipe choices aimed at it, the parent's
# effects on the values they read, then its own facts.
var steps := [
{"table": "Beyond the gate", "table_id": "beyond", "text": "The warden's vault", "depth": 0, "why": [eff, when_f, other]},
{"table": "Learn from it", "table_id": "learn", "text": "Rest instead", "depth": 1, "why": [inp]},
{"table": "Old", "table_id": "learn", "text": "From an old record", "depth": 0},
]
var ls := WhyPopover.why_lines(steps, 1, b, true)
_eq(ls.size(), 2, "the child's reasons: the otherwise choice and its own input")
_check(ls.size() == 2 and ls[0].begins_with("Took Learn from it") and ls[1].begins_with("Tier was 3"), "reasons come in order")
var lp := WhyPopover.why_lines(steps, 0, b, true)
_check(lp.size() == 3 and lp[0] == "Luck went from 2 to 1.", "a step's own facts end with full stops")
var steps2 := [steps[0], {"table": "Loot", "table_id": "loot", "text": "A curio", "depth": 1}]
var lw := WhyPopover.why_lines(steps2, 1, b, true)
_check(lw.size() == 2 and lw[0].begins_with("The warden's vault: Luck went from 2 to 1") and lw[1].begins_with("Skipped Loot"),
"the parent's effect on a value its condition read comes first, named by the parent")
_check(not WhyPopover.has_why(steps, 2), "an old record without facts has no reasons")
_check(WhyPopover.title_for(steps[1]) == "Why Learn from it · Rest instead", "the pop-over title")
func _test_rules_view_helpers() -> void:
var b := _board()
var beyond := b.get_table("beyond")
var vault := beyond.entries[1]
_eq(RulesView.effects_line(vault.effects, b, beyond, true), "Luck −1", "plain effects line")
_eq(RulesView.effects_line(vault.effects, b, beyond, false), "@luck -= 1", "text effects line")
_eq(RulesView.effects_line("@a += 1; @b = 2; @c -= 3", b, null, true), "A +1 · B = 2 · +1", "long effects show two and a count")
_eq(RulesView.loop_rule(b.get_table("rounds"), b, true), "repeat while Luck is more than 0", "plain loop rule")
_eq(RulesView.loop_rule(b.get_table("rounds"), b, false), "while @luck > 0", "text loop rule")
var times := RollTable.create(RollTable.KIND_LOOP, "t", "T")
times.loop_expr = "@terms"
_eq(RulesView.loop_rule(times, b, true), "× Terms", "a count loop reads × Terms")
_eq(RulesView.dice("2d6 + dm(@str)", b, true), "2D + Strength modifier", "expression dice")
_eq(Describe.condition("@luck != \"\"", b), "Luck is not empty", "empty text reads as empty")
_eq(RulesView.check_outlets(b.get_table("gate")), ["8+", "≤7"] as Array[String], "check outlets")
_eq(ResultTray.effect_fact_line({"type": "effect", "var": "@luck", "op": "-=", "before": 2, "after": 1}, b), "Luck 2 → 1", "tray effect line")
_eq(ResultTray.effect_fact_line({"type": "effect", "var": "@skill_*", "op": "reset", "count": 3}, b), "Cleared all Skills (3)", "tray prefix reset line")
# ---------------------------------------------------------------- cards
func _test_card_chips() -> void:
var beyond := main.card_for("beyond")
_check(_chips(beyond).has("Luck −1"), "an effects chip reads Luck −1")
var loot := main.card_for("loot")
_check(_has(loot, "Roll 1D + Tier · 3 ranges"), "expression dice read in words under the title")
_check(_has(main.card_for("rounds"), "repeat while Luck is more than 0"), "a loop's rule reads in words")
_check(_has(main.card_for("v_luck"), "Number · kept between rolls"), "a variable card says it's kept")
func _test_switch() -> void:
_set_plain(false)
await process_frame
var beyond := main.card_for("beyond")
_check(_chips(beyond).has("@luck -= 1"), "Text view: the chip shows the stored statement")
_check(_has(main.card_for("rounds"), "while @luck > 0"), "Text view: the loop rule as written")
_check(_has(main.card_for("learn"), "Options from @skill_* · where option_value >= 1"), "Text view: the options source as written")
_check(_has(main.card_for("loot"), "input tier · default 1"), "Text view: inputs by name")
main.board.pipes._process(0.0)
_check(main.board.pipes._drawn_state.back() == false, "the pipe layer redraws for the Text view")
_set_plain(true)
await process_frame
_check(_chips(main.card_for("beyond")).has("Luck −1"), "switching back refreshes the chips")
main.board.pipes._process(0.0)
_check(main.board.pipes._drawn_state.back() == true, "and the pipes")
func _test_pipe_labels() -> void:
var b := main.data
var vault := b.get_table("beyond").entries[1]
_eq(RulesView.pipe_label(vault, "loot", b, true), "Tier 3 · only if Luck is 2 or more", "plain pipe label")
_eq(RulesView.pipe_label(vault, "learn", b, true), "otherwise", "otherwise label")
_eq(RulesView.pipe_label(vault, "loot", b, false), "tier=3 if @luck >= 2", "text pipe label")
_eq(RulesView.pipe_label(b.get_table("gate").entries[0], "beyond", b, true), "", "a plain pipe has no label")
func _test_router_and_choice() -> void:
var climb := main.card_for("climb")
_check(_has(climb, "if Strength is 10 or more"), "a router case reads in words")
_check(_has(climb, "Otherwise"), "the last case reads Otherwise")
var learn := main.card_for("learn")
_check(_has(learn, "Options: your Skills, level 1 or more"), "a choice's options source reads in words")
_check(_has(learn, "only if Luck is at most 1"), "show_if reads only if …")
_check(_chips(learn).has("Chosen skill +1"), "the Chosen row's effect names the collection's member")
func _test_check_card() -> void:
var gate := main.card_for("gate")
_check(_has(gate, "Roll 2D + Strength modifier, need 8 or more"), "the check card's sentence")
_check(_has(gate, "2D"), "the 2D badge")
_check(_has(gate, "Success · the bars give") and _has(gate, "Failure · it holds"), "Success and Failure outlets with their labels")
_check(_has(gate, "8+") and _has(gate, "≤7"), "outlet ranges")
await process_frame
for eid in ["ok", "no"]:
_check(not gate.anchor_for(eid).is_empty(), "the %s outlet has a pipe anchor" % eid)
var ok_y: float = gate.anchor_for("ok").get("pos", Vector2.ZERO).y
var no_y: float = gate.anchor_for("no").get("pos", Vector2.ZERO).y
_check(no_y > ok_y, "Failure sits below Success")
func _test_collection_and_inputs() -> void:
main.persistent_vars["skill_mechanic"] = {"value": 2, "source": ""}
main.persistent_vars["skill_athletics"] = {"value": 1, "source": ""}
main.refresh_live()
var skills := main.card_for("skills")
var members := _with_meta(skills, "member")
var names := []
for m: Node in members:
names.append(str(m.get_meta("member")))
_eq(names, ["@skill_athletics", "@skill_mechanic", "@skill_recon"], "members: set ones by label, then ones the rules name")
_check(_has(skills, "Mechanic") and _has(skills, "2") and _has(skills, "—"), "members show live values")
_check(_has(skills, "Collection · kept between rolls"), "the collection's kind line")
main.persistent_vars["skill_mechanic"] = {"value": 3, "source": ""}
main.refresh_live()
_check(_has(skills, "3"), "values refresh live")
var loot := main.card_for("loot")
_check(not _with_meta(loot, "inputs_box").is_empty(), "a card with inputs has the dashed box")
_check(_has(loot, "Input Tier · starts at 1"), "the inputs box reads Input Tier · starts at 1")
await process_frame
for e in loot.table.entries:
_check(not loot.anchor_for(e.id).is_empty(), "every row of the inputs card has an anchor")
func _test_tray_why() -> void:
var b := main.data
main.current = {"root": "beyond", "root_name": "Beyond the gate", "done": true, "steps": [
{"table": "Beyond the gate", "table_id": "beyond", "entry_id": "e2", "text": "The warden's vault", "depth": 0, "num": "2", "dice": "d2",
"effects": [{"text": "Luck −1 → 1"}],
"why": [{"type": "roll", "pick": "dice", "dice": "d2", "total": 2, "faces": [2]},
{"type": "effect", "var": "@luck", "op": "-=", "before": 2, "after": 1},
{"type": "when", "to": "loot", "expr": "@luck >= 2", "values": {"@luck": 1}, "result": false},
{"type": "otherwise", "to": "learn", "result": true}]},
{"table": "Old step", "table_id": "climb", "text": "Slip back", "depth": 1},
]}
main.tray.render()
await process_frame
_check(main.tray.why_buttons.has(0), "a step with facts gets a Why this? button")
_check(not main.tray.why_buttons.has(1), "a step without facts (old history) gets none")
_check(_has(main.tray, "Luck 2 → 1"), "the chip's effect line reads Luck 2 → 1")
(main.tray.why_buttons[0] as Button).emit_signal("pressed")
await process_frame
var pop := main.tray.why_popover()
_check(pop.visible, "the button opens the pop-over")
_check(pop.lines.size() == 4 and pop.lines[2] == "Skipped Loot because Luck was 1 (needs 2 or more).", "it lists the step's reasons")
_check(_has(pop, "WHY BEYOND THE GATE · THE WARDEN'S VAULT"), "it's titled by the step")
(main.tray.why_buttons[0] as Button).emit_signal("pressed")
_check(not pop.visible, "pressing again closes it")
# Text view: the same facts as rule text, and the effect log as it is.
_set_plain(false)
await process_frame
_check(_has(main.tray, "Luck −1 → 1"), "Text view keeps the effect log")
(main.tray.why_buttons[0] as Button).emit_signal("pressed")
_check(main.tray.why_popover().lines.size() == 4 and main.tray.why_popover().lines[2].contains("@luck >= 2"), "Text view reasons quote the rule")
main.tray.why_popover().close()
_set_plain(true)
await process_frame
# Hover summaries carry the same reasons.
var why := DetailsPopup.why_bbcode(main.current["steps"], 0, b, true)
_check(why.contains("Skipped Loot because Luck was 1"), "hover pop-ups get the reasons too")
_check(DetailsPopup.why_bbcode(main.current["steps"], 1, b, true) == "", "and nothing for a step without facts")
var rules := DetailsPopup.rules_bbcode(b.get_table("beyond"), b.get_table("beyond").entries[1], b, true)
_check(rules.contains("Luck −1") and rules.contains("Tier 3 · only if Luck is 2 or more"), "an entry's hover summary reads in words")
func _test_roll_why() -> void:
main.current = {}
main.prompt_hook = func(_req: Dictionary) -> Variant: return 1
main.start_roll("gate", true)
for i in 10:
await process_frame
var steps: Array = main.current.get("steps", [])
_check(not steps.is_empty() and str(steps[0].get("kind", "")) == RollTable.KIND_CHECK, "the check rolled")
if steps.is_empty():
return
var cap := ResultTray.caption_for(steps[0], main.data, true)
_check(cap.begins_with("Force the gate · rolled ") and cap.contains("→"), "the check's caption reads rolled N, ±M → total: " + cap)
_check(main.tray.why_buttons.has(0), "a real check step has a Why button")
var lines := WhyPopover.why_lines(steps, 0, main.data, true)
_check(not lines.is_empty() and lines[0].begins_with("Rolled ") and lines[0].contains("needed 8 or more"), "its reason reads the roll against the target")
var lit := "ok" if main.is_entry_lit("gate", "ok") else "no"
_check(main.is_entry_lit("gate", lit), "an outlet lights after the roll")
# A lit row's hover finds its step.
_check(not main.details().step_for("gate", lit).is_empty(), "a lit row finds its step for the hover reasons")
for s: Dictionary in steps:
if str(s.get("table_id", "")) == "loot":
_check(ResultTray.caption_for(s, main.data, true).contains("Tier "), "an inputs step's caption names its input")
func _test_build_rows() -> void:
main.set_mode(Main.Mode.BUILD)
await process_frame
var beyond := main.card_for("beyond")
_check(_chips(beyond).has("Luck −1"), "Build rows show plain chips")
_check(not _has(beyond, "ƒ") and not _has(beyond, "Details"), "the inline effects / details editors are gone")
_check(_with_meta(beyond, "effects_chip").size() == 1, "one chip for the one entry with effects")
var climb := main.card_for("climb")
_check(not _with_meta(climb, "case_line").is_empty() and _has(climb, "if Strength is 10 or more"), "a Build router case shows its condition in words")
var row: Control = beyond.rows["e2"]
var ev := InputEventMouseButton.new()
ev.button_index = MOUSE_BUTTON_LEFT
ev.pressed = true
row.emit_signal("gui_input", ev)
_eq(main.get("picked").back(), ["beyond", "e2"], "clicking a result row calls select_result")
_eq(beyond.selected_entry(), "e2", "the row is selected")
var sb := row.get_theme_stylebox("panel") as StyleBoxFlat
_check(sb != null and sb.border_width_left == 3 and sb.border_color == Style.COPPER, "the selected row has a copper bar")
var gate := main.card_for("gate")
(gate.rows["ok"] as Control).emit_signal("gui_input", ev)
_eq(beyond.selected_entry(), "", "selecting on another card clears this one")
_eq(main.get("picked").back(), ["gate", "ok"], "check outlets are selectable too")
gate.set_selected_entry("no")
_eq(gate.selected_entry(), "no", "the inspector can set the selection directly")
var adds := _with_meta(main.card_for("skills"), "collection_add")
_check(adds.size() == 1 and (adds[0] as Button).text == "+ Add skill", "the collection card has + Add skill in Build")
if adds.size() == 1:
(adds[0] as Button).emit_signal("pressed")
_eq(main.get("picked").back(), ["card", "skills"], "+ Add selects the card for the inspector")
_check(_has(main.card_for("loot"), "Input Tier · starts at 1"), "the inputs box shows in Build too")
main.set_mode(Main.Mode.PLAY)
await process_frame