TableTower/tests/test_options.gd

609 lines
29 KiB
GDScript3
Raw Normal View History

extends SceneTree
## Headless checks for dynamic pick options (options_from / options_where),
## conditional options (show_if) and indirect variable names (@[expr]), as in
## docs/LOGIC.md §2a: candidates, labels and values, fixed extras, Random,
## "No options available", the file format, lint, a small "raise a skill you
## already have" board and the choice pop-up's rendering.
## Run: godot --headless --path . -s res://tests/test_options.gd -- --sample
var _failures := 0
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_prefix_options()
_test_list_options()
_test_fixed_and_dynamic()
_test_random_distribution()
_test_no_options()
_test_show_if()
_test_indirect()
_test_json()
_test_lint()
await _test_raise_skill_board()
await _test_tester()
await _test_dialog()
_test_settings()
await _test_card()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
# ---------------------------------------------------------------- helpers
func _rng(seed_value: int = 1) -> RandomNumberGenerator:
var r := RandomNumberGenerator.new()
r.seed = seed_value
return r
func _board(tables: Array) -> TowerBoard:
var b := TowerBoard.new()
b.id = "options-test"
for t in tables:
b.tables.append(t)
return b
## Board variables as stored: name -> {value, source}.
func _vars(d: Dictionary) -> Dictionary:
var out := {}
for k: String in d:
out[k] = {"value": d[k], "source": ""}
return out
func _var(vars: Dictionary, name: String) -> Variant:
var v: Variant = vars.get(name)
return (v as Dictionary).get("value") if v is Dictionary else null
## A dynamic pick card: entries[0] is the Chosen entry.
func _dyn(id: String, from: String, where: String = "", effects: String = "", text: String = "Chosen") -> RollTable:
var t := RollTable.create(RollTable.KIND_CHOICE, id, id.capitalize(), "pick")
t.entries.clear()
var e := TableEntry.new("chosen", text)
e.effects = effects
t.entries.append(e)
t.options_from = from
t.options_where = where
return t
func _ctx(b: TowerBoard, vars: Dictionary, seed_value: int = 1) -> RollContext:
return Roller.new_context(b, _rng(seed_value), vars)
func _texts_of(req: Dictionary) -> Array:
var out := []
for o: Dictionary in req["options"]:
out.append(Formatter.strip_tags(str(o["text"])))
return out
## Replies with the option whose plain text is `want` (or Cancel when none).
func _answer_text(want: String) -> Callable:
return func(req: Dictionary) -> Variant:
for o: Dictionary in req["options"]:
if Formatter.strip_tags(str(o["text"])) == want:
return int(o["index"])
return null
func _errors(tree: Dictionary) -> Array:
var out := []
for s: Dictionary in Roller.flatten(tree):
for fx: Dictionary in s.get("effects", []):
if fx.get("error", false):
out.append(str(fx["text"]))
return out
# ---------------------------------------------------------------- options_from
func _test_prefix_options() -> void:
var t := _dyn("raise", "@skill_*", "option_value >= 1")
var b := _board([t])
var vars := _vars({"skill_pilot": 1, "skill_gun_combat": 2, "skill_admin": 0, "str": 7})
var ctx := _ctx(b, vars)
var req := Roller.request_for(t, ctx)
_check(_texts_of(req) == ["Gun Combat 2", "Pilot 1"], "prefix options are filtered, sorted and show their values (%s)" % [_texts_of(req)])
var o: Dictionary = req["options"][1]
_check(str(o["option"]) == "skill_pilot" and str(o["label"]) == "Pilot" and int(o["value"]) == 1, "an option carries its variable name, label and value")
_check(int(o["entry"]) == 0 and o.get("dynamic", false), "a dynamic option maps to the Chosen entry")
_check(int(o["index"]) >= t.entries.size(), "a dynamic option's index is past the entries")
_check(not ctx.chain_vars.has("option"), "the filter's bindings don't leak")
# Without the filter, Admin 0 is there too.
t.options_where = ""
_check(_texts_of(Roller.request_for(t, ctx)) == ["Admin 0", "Gun Combat 2", "Pilot 1"], "without a filter every set variable is an option")
# Picking one sets the chain variables and save_as gets the label.
t.options_where = "option_value >= 1"
t.save_as = "@raised"
t.entries[0].effects = "@picked_name = option\n@picked_value = option_value"
ctx = _ctx(b, vars)
ctx.prompt = _answer_text("Pilot 1")
var tree: Dictionary = await Roller.roll_async(b, "raise", ctx)
_check(tree.get("picked", false) and str(tree["option"]) == "Pilot", "the picked node records the option's label")
_check(str(ctx.chain_vars.get("option")) == "skill_pilot" and str(ctx.chain_vars.get("option_label")) == "Pilot" \
and int(ctx.chain_vars.get("option_value")) == 1, "option, option_label and option_value are set")
_check(str(_var(vars, "raised")) == "Pilot", "save_as stores the label")
_check(str(_var(vars, "picked_name")) == "skill_pilot" and int(_var(vars, "picked_value")) == 1, "the Chosen entry's effects see the option")
_check(Formatter.strip_tags(str(tree["summary"])) == "Pilot", "a Chosen entry with its default text reads as the label")
var step: Dictionary = Roller.flatten(tree)[0]
_check(str(step.get("option", "")) == "Pilot" and str(step["entry_id"]) == "chosen", "the step keeps the option and the Chosen entry")
# Text of its own expands with the chain variables.
t.entries[0].text = "Trained {option_label} ({option_value})"
ctx = _ctx(b, vars)
ctx.prompt = _answer_text("Gun Combat 2")
tree = await Roller.roll_async(b, "raise", ctx)
_check(Formatter.strip_tags(str(tree["summary"])) == "Trained Gun Combat (2)", "the Chosen entry's own text expands (%s)" % tree["summary"])
func _test_list_options() -> void:
var t := _dyn("convert", "@contacts", "option != \"Rex\"", "@contacts -= option\n@allies += option")
var b := _board([t])
var vars := _vars({"contacts": "Ana, Rex, Old Bill"})
var ctx := _ctx(b, vars)
var req := Roller.request_for(t, ctx)
_check(_texts_of(req) == ["Ana", "Old Bill"], "list options keep list order and pass the filter (%s)" % [_texts_of(req)])
_check(str(req["options"][1]["option"]) == "Old Bill" and str(req["options"][1]["value_text"]) == "", "a list item is its own option, with no value shown")
ctx.prompt = _answer_text("Old Bill")
await Roller.roll_async(b, "convert", ctx)
_check(str(_var(vars, "contacts")) == "Ana, Rex" and str(_var(vars, "allies")) == "Old Bill", "the Chosen entry moves the picked item")
# An unset list has no candidates.
_check(Roller.dynamic_options(t, _ctx(b, {})).is_empty(), "an unset list gives no options")
func _test_fixed_and_dynamic() -> void:
var t := _dyn("spend", "@loot", "", "@loot -= option")
var none := TableEntry.new("none", "Keep everything")
none.effects = "@kept = 1"
t.entries.append(none)
var b := _board([t])
var vars := _vars({"loot": "gem, map"})
var ctx := _ctx(b, vars)
var req := Roller.request_for(t, ctx)
_check(_texts_of(req) == ["Keep everything", "gem", "map"], "fixed options come first, then the dynamic ones")
_check(int(req["options"][0]["index"]) == 1 and int(req["options"][0]["entry"]) == 1, "a fixed option's index is its entry")
ctx.prompt = _answer_text("Keep everything")
var tree: Dictionary = await Roller.roll_async(b, "spend", ctx)
_check(int(tree["index"]) == 1 and not tree.has("option") and int(_var(vars, "kept")) == 1, "a fixed option runs its own entry")
_check(str(_var(vars, "loot")) == "gem, map", "the Chosen entry didn't run")
ctx = _ctx(b, vars)
ctx.prompt = _answer_text("map")
tree = await Roller.roll_async(b, "spend", ctx)
_check(int(tree["index"]) == 0 and str(_var(vars, "loot")) == "gem", "a dynamic option runs the Chosen entry")
func _test_random_distribution() -> void:
var t := _dyn("pick3", "@skill_*")
var fixed := TableEntry.new("f", "Something else")
fixed.weight = 2
t.entries.append(fixed)
var b := _board([t])
var vars := _vars({"skill_a": 1, "skill_b": 1, "skill_c": 1})
var counts := {}
var ctx := _ctx(b, vars, 3)
for k in 5000:
var tree := Roller.roll(b, "pick3", ctx.rng, 0, {}, ctx)
var key := str(tree.get("option", "fixed"))
counts[key] = int(counts.get(key, 0)) + 1
# Weights: A, B, C 1 each (the Chosen entry's weight), fixed 2: 20/20/20/40%.
var ok := true
for key in ["A", "B", "C"]:
ok = ok and absf(float(counts.get(key, 0)) / 5000.0 - 0.2) < 0.03
ok = ok and absf(float(counts.get("fixed", 0)) / 5000.0 - 0.4) < 0.03
_check(ok, "Random weighs each dynamic option as the Chosen entry and fixed ones by weight (%s)" % [counts])
# A fixed extra with weight 0 is never chosen by Random.
fixed.weight = 0
var seen_fixed := false
for k in 300:
var tree2 := Roller.roll(b, "pick3", ctx.rng, 0, {}, ctx)
seen_fixed = seen_fixed or not tree2.has("option")
_check(not seen_fixed, "weight 0 keeps a fixed extra out of Random")
# The headless tester's answers map to real options.
var req := Roller.request_for(t, ctx)
var valid := {-1: true}
for o: Dictionary in req["options"]:
valid[int(o["index"])] = true
var all_ok := true
var r := _rng(9)
for k in 200:
all_ok = all_ok and valid.has(BoardTester.answer(req, r))
_check(all_ok, "BoardTester.answer() only replies with offered indices")
func _test_no_options() -> void:
var t := _dyn("raise", "@skill_*", "option_value >= 1")
var b := _board([t])
var tree := Roller.roll(b, "raise", _rng(), 0, {}, _ctx(b, _vars({"skill_x": 0})))
_check(str(tree.get("stop", "")) == Roller.NO_OPTIONS and str(tree.get("kind", "")) == RollTable.KIND_CHOICE, "nothing matching stops with \"No options available\"")
# A prompt is never shown for it.
var asked := [false]
var ctx := _ctx(b, {})
ctx.prompt = func(_req: Dictionary) -> Variant:
asked[0] = true
return -1
tree = await Roller.roll_async(b, "raise", ctx)
_check(not asked[0] and str(tree.get("stop", "")) == Roller.NO_OPTIONS, "no pop-up opens when there is nothing to choose")
# A filter error counts as false and is logged.
t.options_where = "option_value >= "
tree = Roller.roll(b, "raise", _rng(), 0, {}, _ctx(b, _vars({"skill_x": 3})))
_check(str(tree.get("stop", "")) == Roller.NO_OPTIONS and _errors(tree).size() == 1 and str(_errors(tree)[0]).begins_with("Only where"), "a bad filter hides everything with one error line")
func _test_show_if() -> void:
var t := RollTable.create(RollTable.KIND_CHOICE, "career", "Career", "pick")
t.entries.clear()
var army := TableEntry.new("army", "Army")
army.show_if = "@last_career != \"Army\""
var officer := TableEntry.new("officer", "Officer")
officer.show_if = "@commissioned"
officer.effects = "@ran = 1"
var drifter := TableEntry.new("drifter", "Drifter")
t.entries.append_array([army, officer, drifter] as Array[TableEntry])
var b := _board([t])
var vars := _vars({"last_career": "Army"})
var req := Roller.request_for(t, _ctx(b, vars))
_check(_texts_of(req) == ["Drifter"] and int(req["hidden"]) == 2, "show_if hides options that don't apply")
vars = _vars({"commissioned": 1})
_check(_texts_of(Roller.request_for(t, _ctx(b, vars))) == ["Army", "Officer", "Drifter"], "true conditions show their options")
# Random never picks a hidden option, and a hidden option never runs.
vars = _vars({"last_career": "Army"})
var ctx := _ctx(b, vars)
var only_drifter := true
for k in 200:
var tree := Roller.roll(b, "career", ctx.rng, 0, {}, ctx)
only_drifter = only_drifter and str(tree["entry"].id) == "drifter"
_check(only_drifter and _var(vars, "ran") == null, "Random only picks shown options; hidden ones never run")
# A stale reply for a hidden option is treated as Random among the shown ones.
ctx = _ctx(b, vars)
ctx.prompt = func(_r: Dictionary) -> Variant: return 1
var t2: Dictionary = await Roller.roll_async(b, "career", ctx)
_check(str(t2["entry"].id) == "drifter" and _var(vars, "ran") == null, "a reply naming a hidden option can't run it")
# Errors count as false with an error line; all hidden -> no options.
drifter.show_if = "@x >"
var tree3 := Roller.roll(b, "career", _rng(), 0, {}, _ctx(b, vars))
_check(str(tree3.get("stop", "")) == Roller.NO_OPTIONS, "every option hidden: \"No options available\"")
_check(_errors(tree3).size() == 1 and str(_errors(tree3)[0]).begins_with("Show only if"), "a bad show_if is an error line")
drifter.show_if = ""
# show_if on the Chosen entry hides all the dynamic options.
var d := _dyn("d", "@skill_*")
d.entries[0].show_if = "@allowed"
var fixed := TableEntry.new("f", "Fixed")
d.entries.append(fixed)
var b2 := _board([d])
_check(_texts_of(Roller.request_for(d, _ctx(b2, _vars({"skill_a": 1})))) == ["Fixed"], "show_if on the Chosen entry hides the dynamic options")
_check(Roller.available_count(d, _ctx(b2, _vars({"skill_a": 1, "allowed": 1}))) == 2, "available_count counts what's offered")
# ---------------------------------------------------------------- @[expr]
func _test_indirect() -> void:
var b := _board([])
var vars := _vars({"skill_pilot": 2, "which": "skill_pilot", "name": "Ana"})
var ctx := _ctx(b, vars)
ctx.chain_vars["option"] = "skill_pilot"
var r := Expr.evaluate("@[option] + 1", ctx)
_check(r["error"] == "" and int(r["value"]) == 3, "@[option] reads the variable it names")
r = Expr.evaluate("@[\"skill_\" + \"pilot\"] * 2", ctx)
_check(r["error"] == "" and int(r["value"]) == 4, "@[\"skill_\" + …] builds the name")
r = Expr.evaluate("@[@which]", ctx)
_check(r["error"] == "" and int(r["value"]) == 2, "@[@var] reads a name from a variable")
r = Expr.evaluate("@[\"skill_none\"] + 1", ctx)
_check(r["error"] == "" and int(r["value"]) == 1, "an unset indirect variable reads as 0")
r = Expr.evaluate("\"x\" + @[\"nothing\"]", ctx)
_check(r["error"] == "" and str(r["value"]) == "x", "an unset indirect variable beside text reads as \"\"")
r = Expr.evaluate("max(@[option], 5)", ctx)
_check(r["error"] == "" and int(r["value"]) == 5, "@[…] works inside function calls")
r = Expr.evaluate("[1, 2][1] + @[option]", ctx)
_check(r["error"] == "" and int(r["value"]) == 4, "plain brackets still work beside @[…]")
r = Expr.evaluate("@[\"Old Bill\"]", ctx)
_check(r["error"] != "" and str(r["error"]).contains("isn't a variable name"), "a bad computed name is an error, not a crash")
_check(Expr.check("@[option") != "", "Expr.check catches a missing ]")
_check(Expr.check("@[option] >= 1") == "", "Expr.check accepts @[…]")
# Effects: write, add, max and reset.
var log := Effects.run("@[option] += 1\n@[\"skill_\" + \"vacc_suit\"] = max(@[\"skill_vacc_suit\"], 0)", ctx, "t")
_check(int(_var(vars, "skill_pilot")) == 3 and int(_var(vars, "skill_vacc_suit")) == 0, "indirect effects write the named variables (%s)" % [Effects.log_text(log)])
_check(str(log[0]["text"]).begins_with("Skill Pilot"), "the effect log names the real variable")
Effects.run("reset @[option]", ctx, "t")
_check(_var(vars, "skill_pilot") == null, "reset @[option] resets the named variable")
ctx.chain_vars["option"] = "Old Bill"
log = Effects.run("@[option] += 1", ctx, "t")
_check(log.size() == 1 and log[0].get("error", false) and str(log[0]["text"]).contains("isn't a variable name"), "a bad computed name is an effect error")
_check(not vars.has("old bill") and not vars.has(""), "nothing is written for a bad name")
_check(Effects.validate("@[option] += 1\nreset @[option]").is_empty(), "Effects.validate accepts indirect statements")
_check(Effects.validate("@[option += 1").size() == 1, "Effects.validate catches a missing ]")
_check(Effects.validate("@[option +] = 1").size() == 1, "Effects.validate checks the name expression")
_check(Effects.validate("@[option] == 1").size() == 1, "== isn't an assignment")
# Text.
ctx.chain_vars["option"] = "name"
var ex := TextExpander.expand("Hi {@[option]}, {@[\"skill_x\"]} {@[\"Bad Name\"]}", ctx)
var plain := Formatter.strip_tags(str(ex["text"]))
_check(plain.begins_with("Hi Ana, {@skill_x?}") and plain.contains("isn't a variable name"), "{@[…]} shows the value, the unset marker or an error marker (%s)" % plain)
_check(Formatter.strip_tags(TextExpander.render("{@[option]}", ctx)) == "Ana", "{@[…]} renders live too")
# ---------------------------------------------------------------- file format and lint
func _test_json() -> void:
var t := _dyn("raise", "@skill_*", "option_value >= 1", "@[option] += 1")
var extra := TableEntry.new("none", "None of these")
extra.show_if = "@terms > 2"
t.entries.append(extra)
var d := t.to_dict()
_check(str(d.get("options_from", "")) == "@skill_*" and str(d.get("options_where", "")) == "option_value >= 1", "to_dict writes options_from and options_where")
_check(str((d["entries"][1] as Dictionary).get("show_if", "")) == "@terms > 2", "to_dict writes show_if")
_check(not (d["entries"][0] as Dictionary).has("show_if"), "an empty show_if is left out")
var back := RollTable.from_dict(d)
_check(back.options_from == "@skill_*" and back.options_where == "option_value >= 1" and back.entries[1].show_if == "@terms > 2", "from_dict reads them back")
var plain := RollTable.create(RollTable.KIND_CHOICE, "p", "P", "pick").to_dict()
_check(not plain.has("options_from") and not plain.has("options_where"), "a fixed pick card has no options keys")
var col := {"format_version": 2, "id": "c", "name": "C", "tables": [d]}
var res := JsonIO.import_json(JsonIO.export_json(col))
_check(res["ok"], "the collection imports")
var td: Dictionary = (res["collection"]["tables"] as Array)[0]
_check(str(td.get("options_from", "")) == "@skill_*" and str(td.get("options_where", "")) == "option_value >= 1" \
and str((td["entries"][1] as Dictionary).get("show_if", "")) == "@terms > 2", "export and import keep them")
var canon := JsonIO.canonical({"tables": [{"id": "x", "name": "X", "kind": "choice", "options_from": "", "entries": [{"text": "a", "show_if": ""}]}]})
var ct: Dictionary = (canon["tables"] as Array)[0]
_check(not ct.has("options_from") and not (ct["entries"][0] as Dictionary).has("show_if"), "canonical drops empty keys")
func _test_lint() -> void:
var bad := _dyn("bad", "skill_*", "option_value >=")
var bad2 := _dyn("bad2", "@Skill Name*")
var where_only := RollTable.create(RollTable.KIND_CHOICE, "w", "W", "pick")
where_only.options_where = "option_value > 1"
where_only.entries[1].show_if = "@x >"
var num := RollTable.create(RollTable.KIND_CHOICE, "n", "N", "number")
num.options_from = "@skill_*"
var good := _dyn("good", "@skill_*", "option_value >= 1")
good.entries[0].show_if = "@ok"
var b := _board([bad, bad2, where_only, num, good])
var msgs := {}
for item: Dictionary in Roller.lint_pipes(b):
var tid := str(item["table_id"])
if not msgs.has(tid):
msgs[tid] = []
(msgs[tid] as Array).append(str(item["message"]))
_check(msgs.has("bad") and (msgs["bad"] as Array).size() == 2, "a pattern without @ and a bad filter are flagged (%s)" % [msgs.get("bad")])
_check(msgs.has("bad2"), "a pattern that isn't a variable name is flagged")
_check(msgs.has("w") and (msgs["w"] as Array).size() == 2, "a filter without options_from and a bad show_if are flagged")
_check(msgs.has("n"), "options_from on a number card is flagged")
_check(not msgs.has("good"), "a good dynamic card is clean")
var problems := BoardTester.static_checks(b)
var seen := false
for p: Dictionary in problems:
seen = seen or (str(p["table_id"]) == "bad" and str(p["text"]).begins_with("Only where"))
_check(seen, "BoardTester's static checks include them")
# ---------------------------------------------------------------- a mini board
## "Raise a skill you already have": start -> raise (options from @skill_*
## where option_value >= 1, plus "Learn something new" when nothing is high
## enough... shown only if no skill is at 1+) -> sheet.
func _test_raise_skill_board() -> void:
var start := RollTable.new("start", "Start")
var se := TableEntry.new("e1", "Training")
se.effects = "@skill_pilot = 1\n@skill_admin = 0\n@skill_gun_combat = 2"
se.add_pipe("raise")
start.entries.append(se)
var raise := _dyn("raise", "@skill_*", "option_value >= 1", "@[option] += 1", "Raised {option_label} to {@[option]}")
raise.prompt = "Raise a skill you already have"
var fresh := TableEntry.new("fresh", "Learn Admin")
fresh.show_if = "count(@skill_*) = 0"
fresh.effects = "@skill_admin = 1"
raise.entries.append(fresh)
raise.entries[0].add_pipe("sheet")
var sheet := RollTable.create(RollTable.KIND_SHEET, "sheet", "Sheet")
sheet.entries[0].text = "Skills: {@skill_*}"
var b := _board([start, raise, sheet])
var vars := {}
var ctx := _ctx(b, vars)
var asked: Array = []
ctx.prompt = func(req: Dictionary) -> Variant:
asked.append(_texts_of(req))
for o: Dictionary in req["options"]:
if str(o.get("option", "")) == "skill_gun_combat":
return int(o["index"])
return -1
var tree: Dictionary = await Roller.roll_async(b, "start", ctx)
_check(asked.size() == 1 and asked[0] == ["Gun Combat 2", "Pilot 1"], "only skills already at 1+ are offered (%s)" % [asked])
_check(int(_var(vars, "skill_gun_combat")) == 3 and int(_var(vars, "skill_pilot")) == 1, "the picked skill went up by one")
var steps := Roller.flatten(tree)
_check(steps.size() == 3 and Formatter.strip_tags(str(steps[1]["text"])) == "Raised Gun Combat to 3", "the result text names the skill and its new level (%s)" % [steps[1]["text"] if steps.size() > 1 else ""])
_check(Formatter.strip_tags(str(Roller.last_sheet(tree).get("summary", ""))) == "Skills: Admin 0, Gun Combat 3, Pilot 1", "the sheet shows the raised skill")
_check(_errors(tree).is_empty(), "no errors")
## The simulator on a dynamic board: no errors, and the Chosen entry counts as
## chosen.
func _test_tester() -> void:
var start := RollTable.new("start", "Start")
var se := TableEntry.new("e1", "Go")
se.effects = "@loot = \"gem, map, idol\""
se.add_pipe("spend")
start.entries.append(se)
var spend := _dyn("spend", "@loot", "", "@loot -= option")
spend.entries.append(TableEntry.new("keep", "Keep it all"))
var b := _board([start, spend])
var report: Dictionary = await BoardTester.simulate(b, "start", {"runs": 100, "seed": 4})
_check(BoardTester.is_clean(report), "the simulator runs a dynamic board cleanly")
_check(not (report["unchosen"] as Dictionary).has("spend"), "both the Chosen entry and the fixed extra get chosen")
# ---------------------------------------------------------------- the pop-up
func _test_dialog() -> void:
var t := _dyn("raise", "@skill_*", "", "@[option] += 1")
t.prompt = "Raise which skill?"
t.entries[0].details = "Goes up by one"
t.entries[0].add_pipe("next")
var none := TableEntry.new("none", "None of these")
t.entries.append(none)
var next := RollTable.new("next", "Next step")
next.entries.append(TableEntry.new("e1", "Onwards"))
var b := _board([t, next])
var vars := _vars({"skill_pilot": 1, "skill_gun_combat": 2})
var req := Roller.request_for(t, _ctx(b, vars))
var d := ChoiceDialog.new(req)
d.board = b
d.vars = vars
root.add_child(d)
await process_frame
_check(d._options.size() == 3, "the pop-up lists the fixed option and both dynamic ones")
var texts0 := _texts(d._options[0])
var texts1 := _texts(d._options[1])
_check(texts0.has("1") and _joined(texts0).contains("None of these"), "the fixed option comes first, on key 1")
_check(texts1.has("2") and _joined(texts1).contains("Gun Combat") and texts1.has("2"), "a dynamic option shows its label and value")
var badge := false
for c in _all(d._options[2]):
if c is Label and (c as Label).text == "1" and c.has_meta("option_value"):
badge = true
_check(badge, "the value shows as a badge")
var p := d.preview_for_option(1)
_check(p != null and _has(p, "@[option] += 1") and _has(p, "Next step"), "a dynamic option's preview shows the Chosen entry's effects and pipes")
_check(_has(p, "skill_gun_combat"), "the preview names the variable behind the option")
p.free()
# Key 3 answers the third option (Pilot).
var got := [null]
d.reply.done.connect(func(v: Variant) -> void: got[0] = v)
var ev := InputEventKey.new()
ev.keycode = KEY_3
ev.pressed = true
d._input(ev)
_check(got[0] != null and int(got[0]) == int((req["options"][2] as Dictionary)["index"]), "number keys answer the dynamic options")
await process_frame
# TablePreview describes the card.
var tp := TablePreview.build(b, "raise")
_check(_has(tp, "Options: each @skill_* that's set"), "the preview describes where the options come from")
_check(_has(tp, "Chosen"), "the preview names the Chosen entry")
tp.free()
none.show_if = "@terms > 2"
tp = TablePreview.build(b, "raise")
_check(_has(tp, "only if @terms > 2"), "the preview shows show_if conditions")
tp.free()
# ---------------------------------------------------------------- settings and card
func _test_settings() -> void:
var t := RollTable.create(RollTable.KIND_CHOICE, "c", "C", "pick")
var keep := TableEntry.new("keep", "None of these")
t.entries.append(keep)
var s := {"choice": "pick", "options_mode": "vars", "options_from": "@skill_*", "options_where": "option_value >= 1",
"show_if": {"keep": "@terms > 1"}}
var r := TableSettingsDialog.apply_settings(t, s)
_check(r["ok"] and t.is_dynamic(), "From variables makes the card dynamic")
_check(t.entries.size() == 2 and t.entries[0].text == Roller.CHOSEN and t.entries[1].id == "keep", "a Chosen entry comes first; default options go, others stay as extras")
_check(t.options_where == "option_value >= 1" and keep.show_if == "@terms > 1", "the filter and show_if are applied")
var bad := s.duplicate(true)
bad["options_from"] = "skill"
bad["show_if"] = {"keep": "@x >"}
var probs := TableSettingsDialog.kind_problems(t, bad)
_check(probs.size() == 2, "a bad pattern and a bad show_if are refused (%s)" % [probs])
bad = s.duplicate(true)
bad["options_from"] = ""
_check(not TableSettingsDialog.apply_settings(t, bad)["ok"], "From variables needs a pattern")
# Back to a fixed list: the unused Chosen entry goes.
r = TableSettingsDialog.apply_settings(t, {"choice": "pick", "options_mode": "fixed"})
_check(r["ok"] and not t.is_dynamic() and t.entries.size() == 1 and t.entries[0].id == "keep", "a fixed list drops the unused Chosen entry")
# A Chosen entry that does something stays as an option.
TableSettingsDialog.apply_settings(t, s)
t.entries[0].effects = "@[option] += 1"
TableSettingsDialog.apply_settings(t, {"choice": "pick", "options_mode": "fixed"})
_check(t.entries.size() == 2 and t.entries[0].effects != "", "a Chosen entry with effects is kept as an option")
func _test_card() -> void:
var main: Main = load("res://ui/main.tscn").instantiate()
root.add_child(main)
for i in 5:
await process_frame
if main._saving_enabled:
_check(false, "saving must be off for the card test")
return
var t := _dyn("raise_card", "@skill_*", "option_value >= 1", "@[option] += 1")
t.prompt = "Raise which skill?"
var extra := TableEntry.new("none", "None of these")
extra.show_if = "@terms > 2"
t.entries.append(extra)
t.position = Vector2(40, 2000)
main.data.tables.append(t)
main.persistent_vars["skill_pilot"] = {"value": 1, "source": ""}
main.persistent_vars["skill_admin"] = {"value": 0, "source": ""}
main._rebuild_cards()
await process_frame
var card := main.card_for("raise_card")
_check(card != null and _has(card, "Options from @skill_* · where option_value >= 1"), "the card says where its options come from")
_check(_has(card, "1 option available now"), "in Play it counts the options available now")
_check(_has(card, "only if @terms > 2"), "a show_if option shows its condition")
_check(_has(card, "Chosen"), "the card has a Chosen row")
main.set_mode(Main.Mode.BUILD)
await process_frame
card = main.card_for("raise_card")
card._open_show_if["none"] = true
card.rebuild()
_check(_has(card, "Show only if"), "Build mode edits show_if under the option")
var d := TableSettingsDialog.new(t)
main.add_child(d)
await process_frame
_check(_has_ci(d, "Options from (@prefix_* or a @list)") and _has_ci(d, "Show only if") and _has_ci(d, "From variables (+ fixed extras)"), "the settings dialog has the options fields")
_check(d._options_box.visible and d._opt_from.text == "@skill_*", "From variables is selected with its pattern")
d._opt_where.text = "option_value >="
d._refresh()
_check(d._kind_problem.visible, "a bad filter is flagged live")
d.queue_free()
main.set_mode(Main.Mode.PLAY)
main.queue_free()
await process_frame
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))
for c in n.get_children():
_texts(c, out)
return out
func _joined(a: PackedStringArray) -> String:
return " | ".join(a)
func _all(n: Node, out: Array = []) -> Array:
out.append(n)
for c in n.get_children():
_all(c, out)
return out
func _has_ci(n: Node, needle: String) -> bool:
for s in _texts(n):
if s.to_lower().contains(needle.to_lower()):
return true
for c in _all(n):
if c is Button and (c as Button).text.to_lower().contains(needle.to_lower()):
return true
return false
func _has(n: Node, needle: String) -> bool:
for s in _texts(n):
if s.contains(needle):
return true
return false
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print(" ✗ ", what)