TableTower/tests/test_check_inputs.gd

653 lines
28 KiB
GDScript3
Raw Normal View History

extends TestBase
## Headless checks for the new engine features of docs/PLAIN.md §3–§4: check
## cards, card inputs (pipe "with" values), collections, "nat" on roll tables,
## the why facts they record, the file format and the lint.
## Run: godot --headless --path . -s res://tests/test_check_inputs.gd
func _init() -> void:
_test_check_success_failure()
_test_check_le_and_dice()
_test_check_errors()
_test_inputs_two_pipes()
_test_inputs_scope_restored()
_test_inputs_defaults()
_test_inputs_nested()
_test_inputs_dice_conditions_text()
_test_inputs_snapshot()
_test_inputs_loops_routers_choices_inline()
_test_inputs_limit()
_test_inputs_errors()
_test_collections()
_test_nat()
_test_json()
_test_lint()
finish()
# ---------------------------------------------------------------- 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 = "check-inputs"
for t in tables:
b.tables.append(t)
return b
func _one(id: String, text: String, effects: String = "") -> RollTable:
var t := RollTable.new(id, id.capitalize())
var e := TableEntry.new("e1", text)
e.effects = effects
t.entries.append(e)
return t
## Rolls `id`; returns [tree, ctx].
func _roll(b: TowerBoard, id: String, vars: Dictionary = {}, seed_value: int = 1) -> Array:
var ctx := Roller.new_context(b, _rng(seed_value), vars)
var tree := Roller.roll(b, id, ctx.rng, 0, {}, ctx)
return [tree, ctx]
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
## Plain text of each step, in order.
func _texts(tree: Dictionary) -> Array:
var out := []
for s: Dictionary in Roller.flatten(tree):
out.append(Formatter.strip_tags(str(s["text"])))
return out
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
func _check_card(dice: String, mod: String, cmp: String, target: String) -> RollTable:
var t := RollTable.create(RollTable.KIND_CHECK, "chk", "Check")
t.check_dice = dice
t.check_mod = mod
t.check_cmp = cmp
t.check_target = target
t.entries[0].effects = "@res = \"S\"; @n = nat; @t = total; @eff = effect"
t.entries[1].effects = "@res = \"F\"; @n = nat; @t = total; @eff = effect"
return t
# ---------------------------------------------------------------- checks
func _test_check_success_failure() -> void:
var t := RollTable.create(RollTable.KIND_CHECK, "c", "Check")
_eq(t.check_dice, "2d6", "default dice")
_eq(t.check_target, "8", "default target")
_eq(t.check_cmp, "ge", "default cmp")
_eq(t.entries.size(), 2, "two entries")
_eq(t.entries[0].text, "Success", "Success first")
_eq(t.entries[1].text, "Failure", "Failure second")
_eq(t.dice_label(), "2d6", "dice label")
# 7 + dm(9) = 8 vs 8: success with effect 0.
var b := _board([_check_card("7", "dm(@str)", "ge", "8")])
var vars := {"str": {"value": 9, "source": ""}}
var r := _roll(b, "chk", vars)
var node: Dictionary = r[0]
_eq(node["kind"], "check", "node kind")
_eq(node["index"], 0, "Success index")
_eq(node["check"], {"nat": 7, "mod": 1, "total": 8, "target": 8, "success": true}, "check info")
_eq(node["value"], 8, "value is the total")
_eq(_var(vars, "res"), "S", "success effects ran")
_eq([_var(vars, "n"), _var(vars, "t"), _var(vars, "eff")], [7, 8, 0], "nat, total, effect")
_eq((r[1] as RollContext).actions, 1, "one action")
var step: Dictionary = Roller.flatten(node)[0]
_eq(step["check"], node["check"], "step carries check")
_eq(step["kind"], "check", "step kind")
var fact: Dictionary = (step["why"] as Array)[0]
_eq(fact["type"], "check", "why check fact")
_eq([fact["nat"], fact["mod"], fact["total"], fact["target"], fact["cmp"], fact["success"]], [7, 1, 8, 8, "ge", true], "fact values")
# 7 + dm(3) = 6 vs 8: failure, effect -2.
vars = {"str": {"value": 3, "source": ""}}
r = _roll(b, "chk", vars)
_eq(r[0]["index"], 1, "Failure index")
_eq(_var(vars, "res"), "F", "failure effects ran")
_eq([_var(vars, "n"), _var(vars, "t"), _var(vars, "eff")], [7, 6, -2], "failure nat, total, effect")
_eq(Describe.why(r[0]["why"][0], b), "Rolled 7, −1 = 6: needed 8 or more, failure", "check why sentence")
func _test_check_le_and_dice() -> void:
# Roll-under: 5 + 1 = 6 <= @skill 7: success.
var b := _board([_check_card("5", "1", "le", "@skill")])
var vars := {"skill": {"value": 7, "source": ""}}
var r := _roll(b, "chk", vars)
_eq(r[0]["check"], {"nat": 5, "mod": 1, "total": 6, "target": 7, "success": true}, "le success")
_eq(_var(vars, "eff"), -1, "le effect is total minus target")
vars = {"skill": {"value": 5, "source": ""}}
r = _roll(b, "chk", vars)
_eq(r[0]["check"]["success"], false, "le failure")
# Real dice: the faces are recorded and nat is their sum.
b = _board([_check_card("2d6", "", "ge", "8")])
for s in 20:
vars = {}
r = _roll(b, "chk", vars, s + 1)
var c: Dictionary = r[0]["check"]
var f: Dictionary = r[0]["why"][0]
_eq((f["faces"] as Array).size(), 2, "two faces")
_eq(int(f["faces"][0]) + int(f["faces"][1]), c["nat"], "nat is the faces' sum")
_eq(c["success"], int(c["total"]) >= 8, "success matches total")
_eq(_var(vars, "res"), "S" if c["success"] else "F", "the right entry ran")
# Pipes from Success and Failure.
var chk := _check_card("10", "", "ge", "8")
chk.entries[0].add_pipe("win")
chk.entries[1].add_pipe("lose")
b = _board([chk, _one("win", "Won with {total}"), _one("lose", "Lost")])
_eq(_texts(_roll(b, "chk")[0]), ["Success", "Won with 10"], "success threads, total in text")
func _test_check_errors() -> void:
var b := _board([_check_card("2d6", "", "ge", "8 +")])
var r := _roll(b, "chk")
_check(r[0].has("stop") and str(r[0]["stop"]).begins_with("Can't roll the check"), "bad target stops: %s" % r[0].get("stop"))
_eq(r[0]["kind"], "check", "stop node kind")
b = _board([_check_card("2d6", "@name", "ge", "8")])
var vars := {"name": {"value": "Bob", "source": ""}}
r = _roll(b, "chk", vars)
_check(r[0].has("stop"), "text modifier stops")
var t := _check_card("2d6", "", "ge", "8")
t.entries.remove_at(1)
b = _board([t])
var found := false
for s in 10:
var rr := _roll(b, "chk", {}, s + 1)
if rr[0].has("stop"):
found = true
_eq(rr[0]["stop"], "This check has no Failure result", "missing Failure entry")
_check(found, "a failure without a Failure entry stops")
# ---------------------------------------------------------------- inputs
## A card that shows its input tier: "Tier {tier}".
func _show() -> RollTable:
var t := _one("show", "Tier {tier}")
t.inputs = [{"name": "tier", "label": "Tier", "default": "1"}]
return t
func _test_inputs_two_pipes() -> void:
var start := RollTable.new("start", "Start")
var e := TableEntry.new("e1", "go")
e.add_pipe("a")
e.add_pipe("b")
start.entries.append(e)
var a := _one("a", "A")
a.entries[0].add_pipe("show")
a.entries[0].set_pipe_with("show", {"tier": "2"})
var bb := _one("b", "B")
bb.entries[0].add_pipe("show")
bb.entries[0].set_pipe_with("show", {"tier": "3"})
var b := _board([start, a, bb, _show()])
var r := _roll(b, "start")
_eq(_texts(r[0]), ["go", "A", "Tier 2", "B", "Tier 3"], "two threads pass different values")
var steps := Roller.flatten(r[0])
_eq(steps[2]["inputs"], {"tier": 2}, "step inputs")
_eq(steps[2]["why"][0], {"type": "input", "name": "tier", "value": 2, "from": "pipe"}, "input fact")
_eq(Describe.why(steps[2]["why"][0], b), "Tier was 2 (from the thread)", "input sentence")
_check(not (r[1] as RollContext).chain_vars.has("tier"), "tier is gone after the roll")
func _test_inputs_scope_restored() -> void:
var start := RollTable.new("start", "Start")
var e := TableEntry.new("e1", "go")
e.effects = "tier = 9"
e.add_pipe("show")
e.set_pipe_with("show", {"tier": "5"})
e.add_pipe("after")
start.entries.append(e)
var after := _one("after", "after {tier}")
var b := _board([start, _show(), after])
_eq(_texts(_roll(b, "start")[0]), ["go", "Tier 5", "after 9"], "previous value comes back")
# Without a previous value, the input is unset again afterwards.
e.effects = ""
_eq(_texts(_roll(b, "start")[0]), ["go", "Tier 5", "after {tier?}"], "unset again afterwards")
# Count 3: each pass is scoped.
e.set_pipe_count("show", 3)
_eq(_texts(_roll(b, "start")[0]), ["go", "Tier 5", "Tier 5", "Tier 5", "after {tier?}"], "count passes")
func _test_inputs_defaults() -> void:
var start := RollTable.new("start", "Start")
var e := TableEntry.new("e1", "go")
e.add_pipe("show")
start.entries.append(e)
var b := _board([start, _show()])
_eq(_texts(_roll(b, "start")[0]), ["go", "Tier 1"], "missing input uses the default")
var r := _roll(b, "show")
_eq(_texts(r[0]), ["Tier 1"], "a roll starting on the card uses the defaults")
_eq(r[0]["why"][0], {"type": "input", "name": "tier", "value": 1, "from": "default"}, "default fact")
var sh := b.get_table("show")
sh.inputs = [{"name": "tier", "label": "", "default": "@level * 2"}]
_eq(_texts(_roll(b, "show", {"level": {"value": 4, "source": ""}})[0]), ["Tier 8"], "default expression")
sh.inputs = [{"name": "tier", "label": "", "default": ""}]
_eq(_texts(_roll(b, "show")[0]), ["Tier 0"], "empty default is 0")
sh.inputs = [{"name": "tier", "label": "", "default": "\"High\""}]
_eq(_texts(_roll(b, "show")[0]), ["Tier High"], "text default")
func _test_inputs_nested() -> void:
var show := _show()
show.entries[0].add_pipe("inner")
show.entries[0].set_pipe_with("inner", {"level": "tier + 1"})
var inner := _one("inner", "{tier}/{level}")
inner.inputs = [{"name": "level", "label": "Level", "default": "0"}]
inner.entries[0].add_pipe("show2")
inner.entries[0].set_pipe_with("show2", {"tier": "level * 10"})
var show2 := _one("show2", "deep {tier}/{level}")
show2.inputs = [{"name": "tier", "label": "", "default": "0"}]
show2.entries[0].add_pipe("tail")
var tail := _one("tail", "tail {tier}")
var start := RollTable.new("start", "Start")
var e := TableEntry.new("e1", "go")
e.add_pipe("show")
e.set_pipe_with("show", {"tier": "3"})
start.entries.append(e)
var b := _board([start, show, inner, show2, tail])
_eq(_texts(_roll(b, "start")[0]), ["go", "Tier 3", "3/4", "deep 40/4", "tail 40"], "nested inputs")
func _test_inputs_dice_conditions_text() -> void:
# Dice: a ranged table whose dice expression reads the input.
var ranged := RollTable.new("ranged", "Ranged")
ranged.dice = "tier * 10"
for spec: Array in [[1, 9, "low"], [10, 19, "ten"], [20, 29, "twenty"]]:
var re := TableEntry.new("r%d" % spec[0], spec[2])
re.has_range = true
re.range_lo = spec[0]
re.range_hi = spec[1]
ranged.entries.append(re)
ranged.inputs = [{"name": "tier", "label": "", "default": "0"}]
# Conditions: pipes on the input card.
var show := _one("show", "Tier {tier} ({= tier * 2})")
show.inputs = [{"name": "tier", "label": "", "default": "1"}]
show.entries[0].add_pipe("big")
show.entries[0].set_pipe_when("big", "tier >= 2")
show.entries[0].add_pipe("ranged")
show.entries[0].set_pipe_with("ranged", {"tier": "tier"})
var big := _one("big", "big")
var start := RollTable.new("start", "Start")
var e := TableEntry.new("e1", "go")
e.add_pipe("show")
e.set_pipe_with("show", {"tier": "2"})
start.entries.append(e)
var b := _board([start, show, big, ranged])
_eq(_texts(_roll(b, "start")[0]), ["go", "Tier 2 (4)", "big", "twenty"], "inputs in dice, conditions and text")
e.set_pipe_with("show", {"tier": "1"})
_eq(_texts(_roll(b, "start")[0]), ["go", "Tier 1 (2)", "ten"], "condition false with a smaller input")
# Pipe count from an input.
show.entries[0].set_pipe_count("big", "tier")
e.set_pipe_with("show", {"tier": "3"})
_eq(_texts(_roll(b, "start")[0]), ["go", "Tier 3 (6)", "big", "big", "big", "twenty"], "count from an input (30 clamps to the top range)")
func _test_inputs_snapshot() -> void:
# The with values are worked out in the entry's snapshot: the first pipe's
# subtree changes @x, the second pipe still passes the old value.
var start := RollTable.new("start", "Start")
var e := TableEntry.new("e1", "go")
e.effects = "@x = 1"
e.add_pipe("bump")
e.add_pipe("show")
e.set_pipe_with("show", {"tier": "@x + 1d1 * 0"})
start.entries.append(e)
var b := _board([start, _one("bump", "bump", "@x = 5"), _show()])
var vars := {}
_eq(_texts(_roll(b, "start", vars)[0]), ["go", "bump", "Tier 1"], "snapshot value")
_eq(_var(vars, "x"), 5, "the subtree did change @x")
func _test_inputs_loops_routers_choices_inline() -> void:
# Loop: each pass passes i.
var loop := RollTable.create(RollTable.KIND_LOOP, "loop", "Repeat")
loop.loop_expr = "3"
loop.entries[0].add_pipe("show")
loop.entries[0].set_pipe_with("show", {"tier": "i * 10"})
var b := _board([loop, _show()])
var texts := _texts(_roll(b, "loop")[0])
_eq(texts.filter(func(s: String) -> bool: return s.begins_with("Tier")), ["Tier 10", "Tier 20", "Tier 30"], "loop passes")
# A loop card with its own input: the passes see it, and it's gone after.
loop.inputs = [{"name": "tier", "label": "", "default": "7"}]
loop.entries[0].remove_pipe("show")
loop.entries[0].text = "pass {i} of tier {tier}"
var r := _roll(b, "loop")
_eq(_texts(r[0]).slice(1, 4), ["pass 1 of tier 7", "pass 2 of tier 7", "pass 3 of tier 7"], "loop card input")
_check(not (r[1] as RollContext).chain_vars.has("tier"), "loop input restored")
# Router: a case reads the input, its pipe passes a new value.
var router := RollTable.create(RollTable.KIND_ROUTER, "route", "Route")
router.inputs = [{"name": "tier", "label": "", "default": "0"}]
router.entries[0].when = "tier >= 2"
router.entries[0].text = "high"
router.entries[0].add_pipe("show")
router.entries[0].set_pipe_with("show", {"tier": "tier * 100"})
router.entries[1].text = "low"
var start := RollTable.new("start", "Start")
var e := TableEntry.new("e1", "go")
e.add_pipe("route")
e.set_pipe_with("route", {"tier": "2"})
start.entries.append(e)
b = _board([start, router, _show()])
r = _roll(b, "start")
_eq(_texts(r[0]), ["go", "high", "Tier 200"], "branch with inputs")
var rstep: Dictionary = Roller.flatten(r[0])[1]
var types: Array = []
for f: Dictionary in rstep["why"]:
types.append(f["type"])
_eq(types, ["input", "case"], "branch facts: input then case")
_eq(Describe.why(rstep["why"][1], b), "Case 1 matched because Tier was 2 (needs 2 or more)", "case sentence with input")
e.set_pipe_with("route", {"tier": "1"})
_eq(_texts(_roll(b, "start")[0]), ["go", "low"], "branch otherwise")
# Number choice: the Answer's pipe passes answer.
var ask := RollTable.create(RollTable.KIND_CHOICE, "ask", "Ask", "number")
ask.min_expr = "4"
ask.entries[0].add_pipe("show")
ask.entries[0].set_pipe_with("show", {"tier": "answer"})
b = _board([ask, _show()])
_eq(_texts(_roll(b, "ask")[0]), ["4", "Tier 4"], "choice answer passed")
# Pick choice options with different values.
var pick := RollTable.create(RollTable.KIND_CHOICE, "pick", "Pick", "pick")
for k in 3:
pick.entries[k].add_pipe("show")
pick.entries[k].set_pipe_with("show", {"tier": str(k + 1)})
b = _board([pick, _show()])
for s in 6:
var rr := _roll(b, "pick", {}, s + 1)
var tx := _texts(rr[0])
_eq(tx[1], "Tier %d" % (int(rr[0]["index"]) + 1), "pick option passes its value")
# Inline reference: an inline card without inputs sees the outer value;
# an inline card with inputs gets its defaults inside, and the outer value
# is back afterwards.
var show := _show()
show.entries[0].text = "Tier {tier} [[Peek]] [[Inner]] {tier}"
var peek := _one("peek", "peek {tier}")
peek.name = "Peek"
var inner := _one("inner", "inner {tier}")
inner.name = "Inner"
inner.inputs = [{"name": "tier", "label": "", "default": "0"}]
start = RollTable.new("start", "Start")
e = TableEntry.new("e1", "go")
e.add_pipe("show")
e.set_pipe_with("show", {"tier": "3"})
start.entries.append(e)
b = _board([start, show, peek, inner])
_eq(_texts(_roll(b, "start")[0])[1], "Tier 3 peek 3 inner 0 3", "inline references")
func _test_inputs_limit() -> void:
# An endless chain passing n + 1: stops at the action limit, no crash, and
# the input is restored after the halt.
var rec := _one("rec", "n{n}")
rec.inputs = [{"name": "n", "label": "", "default": "0"}]
rec.entries[0].add_pipe("rec")
rec.entries[0].set_pipe_with("rec", {"n": "n + 1"})
var b := _board([rec])
var r := _roll(b, "rec")
var ctx: RollContext = r[1]
_eq(ctx.halted, Roller.limit_text(), "halted at the limit")
_check(not ctx.chain_vars.has("n"), "n restored after the halt")
var steps := Roller.flatten(r[0])
_eq(steps.size(), RollContext.DEFAULT_MAX_ACTIONS + 1, "every action plus the stop marker")
_eq(Formatter.strip_tags(str(steps[9999]["text"])), "n9999", "the deepest value")
_check(steps.back().get("limit", false), "limit marker")
func _test_inputs_errors() -> void:
var start := RollTable.new("start", "Start")
var e := TableEntry.new("e1", "go")
e.add_pipe("show")
e.set_pipe_with("show", {"tier": "2 +", "extra": "7"})
start.entries.append(e)
var show := _show()
show.entries[0].text = "Tier {tier} extra {extra}"
var b := _board([start, show])
var r := _roll(b, "start")
_eq(_texts(r[0]), ["go", "Tier 1 extra 7"], "bad value uses the default; undeclared names still pass")
_eq(_errors(r[0]).size(), 1, "one error line")
_check(str(_errors(r[0])[0]).begins_with("Thread input tier = 2 +"), "error names the input")
show.inputs = [{"name": "tier", "label": "", "default": "1 +"}]
e.set_pipe_with("show", {})
r = _roll(b, "start")
_eq(_texts(r[0]), ["go", "Tier 0 extra {extra?}"], "bad default is 0")
_check(str(_errors(r[0])[0]).begins_with("Input tier default"), "default error line")
# ---------------------------------------------------------------- collections
func _test_collections() -> void:
var c := RollTable.create(RollTable.KIND_VARIABLE, "skills", "Skills", "collection")
_eq(c.var_type, "collection", "spread type")
_eq(c.var_name, "skill", "stem from the name")
_eq(c.initial, "", "no starting value")
_check(c.is_collection(), "is_collection")
_eq(RollTable.create(RollTable.KIND_VARIABLE, "b", "Boss", "collection").var_name, "boss", "a double s stays")
var raise := RollTable.create(RollTable.KIND_CHOICE, "raise", "Raise", "pick")
raise.options_from = "@skill_*"
raise.options_where = "option_value >= 1"
raise.entries[0].effects = "@[option] += 1"
raise.entries.resize(1)
var start := _one("start", "go", "@skill_pilot += 1; @skill_gun_combat = 2; @skill_admin = 0")
start.entries[0].add_pipe("raise")
var b := _board([c, start, raise])
var vars := {}
var r := _roll(b, "start", vars)
_eq(Describe.options(raise, b), "your Skills, level 1 or more", "options description")
var shown := Roller.variable_display(b, vars, c)
_check(shown["set"], "spread display is set")
_check(str(shown["text"]).contains("Pilot") and str(shown["text"]).contains("Gun Combat"), "members listed: %s" % shown["text"])
var raised := int(_var(vars, "skill_pilot")) + int(_var(vars, "skill_gun_combat"))
_eq(raised, 4, "one member raised")
var fx: Array = []
for st: Dictionary in Roller.flatten(r[0]):
for f: Dictionary in st.get("why", []):
if f["type"] == "options_where":
fx.append(f)
_eq(fx.size(), 1, "options_where fact")
_eq(Describe.why(fx[0], b), "Offered 2 of 3 Skills (level 1 or more)", "options_where sentence")
_eq(Roller.variable_display(b, {}, c), {"text": "", "set": false, "error": ""}, "empty spread")
# reset @skill_* still clears every member; a collection isn't declared.
var clear := _one("clear", "clear", "reset @skill_*")
b.tables.append(clear)
_roll(b, "clear", vars)
_eq(_var(vars, "skill_pilot"), null, "reset clears members")
# count() and {@skill_*} as before.
var probe := _one("probe", "{@skill_*} / {= count(@skill_*)}")
b.tables.append(probe)
var v2 := {"skill_pilot": {"value": 1, "source": ""}}
_eq(_texts(_roll(b, "probe", v2)[0]), ["Pilot 1 / 1"], "list text and count")
# JSON.
var back := RollTable.from_dict(JSON.parse_string(JSON.stringify(c.to_dict())))
_eq(back.var_type, "collection", "spread survives JSON")
_eq(back.var_name, "skill", "stem survives JSON")
# ---------------------------------------------------------------- nat
func _test_nat() -> void:
var t := RollTable.new("r", "Ranged")
t.dice = "2d6+5"
var e := TableEntry.new("e1", "all")
e.has_range = true
e.range_lo = 7
e.range_hi = 17
e.effects = "@n = nat"
t.entries.append(e)
var b := _board([t])
for s in 10:
var vars := {}
var r := _roll(b, "r", vars, s + 1)
var f: Dictionary = r[0]["why"][0]
_eq(f["type"], "roll", "roll fact")
_eq(_var(vars, "n"), int(r[0]["value"]) - 5, "nat is the dice alone")
_eq(f["nat"], _var(vars, "n"), "fact nat")
_eq(f["mod"], 5, "fact modifier")
_eq((f["faces"] as Array).size(), 2, "two faces")
# Expression dice: "natural 2" rules.
t.dice = "2d6 + dm(@str)"
e.range_lo = -10
e.range_hi = 40
e.effects = "@n = nat; @nat2 = if(nat = 2, 1, 0)"
var vars2 := {"str": {"value": 15, "source": ""}}
var r2 := _roll(b, "r", vars2, 3)
_eq(_var(vars2, "n"), int(r2[0]["value"]) - 3, "nat without dm(15) = +3")
# Weighted tables: nat is the die value.
var w := RollTable.new("w", "Weighted")
for k in 6:
var we := TableEntry.new("e%d" % k, "r%d" % (k + 1))
we.effects = "@n = nat"
w.entries.append(we)
b = _board([w])
var vars3 := {}
var r3 := _roll(b, "w", vars3)
_eq(_var(vars3, "n"), r3[0]["value"], "weighted nat")
_eq(r3[0]["why"][0]["pick"], "weighted", "weighted fact")
_check(not r3[0].has("nat"), "no stray nat key on the node")
# An expression without dice doesn't set nat.
var x := RollTable.new("x", "X")
x.dice = "@terms"
var xe := TableEntry.new("e1", "x")
xe.has_range = true
xe.range_lo = 0
xe.range_hi = 9
xe.effects = "@n = nat"
x.entries.append(xe)
b = _board([x])
var vars4 := {"terms": {"value": 3, "source": ""}}
var r4 := _roll(b, "x", vars4)
_eq(_var(vars4, "n"), 0, "no dice: nat unset (reads 0)")
_eq(Describe.why(r4[0]["why"][0], b), "Worked out 3", "no-dice roll sentence")
# ---------------------------------------------------------------- JSON
func _test_json() -> void:
var chk := RollTable.create(RollTable.KIND_CHECK, "chk", "Check")
chk.check_dice = "3d6"
chk.check_mod = "dm(@str)"
chk.check_cmp = "le"
chk.check_target = "@skill"
chk.inputs = [{"name": "tier", "label": "Tier", "default": "1"}, {"name": "bonus", "label": "", "default": ""}]
chk.entries[0].add_pipe("next")
chk.entries[0].set_pipe_with("next", {"level": "tier + 1"})
var plain := RollTable.create(RollTable.KIND_CHECK, "plain", "Plain")
var next := _one("next", "n")
next.inputs = [{"name": "level", "label": "Level", "default": "0"}]
var b := _board([chk, plain, next])
b.name = "Check inputs"
var d := chk.to_dict()
_eq(d["kind"], "check", "kind written")
_eq([d["check_dice"], d["check_mod"], d["check_cmp"], d["check_target"]], ["3d6", "dm(@str)", "le", "@skill"], "check keys")
_eq(d["inputs"], [{"name": "tier", "label": "Tier", "default": "1"}, {"name": "bonus"}], "inputs written without empty keys")
_eq(d["entries"][0]["pipes"], [{"table": "next", "with": {"level": "tier + 1"}}], "thread with written")
var pd := plain.to_dict()
for k in ["check_dice", "check_mod", "check_cmp", "check_target", "inputs"]:
_check(not pd.has(k), "default %s left out" % k)
var text := JsonIO.export_json(b.to_dict())
var imp := JsonIO.import_json(text)
_check(imp["ok"], "imports")
var b2 := TowerBoard.new()
_check(b2.load_json(JSON.stringify(imp["collection"])), "loads")
var c2 := b2.get_table("chk")
_eq([c2.kind, c2.check_dice, c2.check_mod, c2.check_cmp, c2.check_target], ["check", "3d6", "dm(@str)", "le", "@skill"], "check round trip")
_eq(c2.inputs, chk.inputs, "inputs round trip")
_eq(c2.entries[0].with_for("next"), {"level": "tier + 1"}, "with round trip")
_eq(JsonIO.export_json(b2.to_dict()), text, "export is stable")
# Numbers in JSON become expression text; junk is cleaned.
var raw := {"id": "t", "name": "T", "kind": "check", "check_target": 9, "check_cmp": "weird",
"inputs": [{"name": " @tier ", "default": 2}, {"name": ""}, "bare"],
"entries": [{"id": "e1", "text": "S", "pipes": [{"table": "t", "with": {"tier": 3, "": "1", "x": ""}}]}]}
var t := RollTable.from_dict(raw)
_eq(t.check_target, "9", "number target")
_eq(t.check_cmp, "ge", "bad cmp falls back")
_eq(t.inputs, [{"name": "tier", "label": "", "default": "2"}, {"name": "bare", "label": "", "default": ""}], "inputs cleaned")
_eq(t.entries[0].with_for("t"), {"tier": "3"}, "with cleaned")
var canon := JsonIO.canonical({"tables": [raw]})
_eq(canon["tables"][0]["inputs"], [{"name": "tier", "default": "2"}, {"name": "bare"}], "canonical inputs")
_eq(canon["tables"][0]["entries"][0]["pipes"][0]["with"], {"tier": "3"}, "canonical with")
_eq(canon["tables"][0]["check_target"], "9", "canonical check target")
_eq(JsonIO.pipe_info({"table": "t", "with": {"tier": "3"}})["with"], {"tier": "3"}, "pipe_info with")
_eq(JsonIO.pipe_label(JsonIO.pipe_info({"table": "t", "with": {"tier": "3"}})), "tier=3", "pipe_label with")
# Why facts survive the history (JSON).
var r := _roll(b, "chk", {"str": {"value": 9, "source": ""}, "skill": {"value": 12, "source": ""}})
var steps := Roller.flatten(r[0])
var back: Array = JSON.parse_string(JSON.stringify(steps))
_eq(back[0]["why"].size(), steps[0]["why"].size(), "facts survive JSON")
_eq(Describe.why(back[0]["why"][2], b), Describe.why(steps[0]["why"][2], b), "same sentence after JSON")
# ---------------------------------------------------------------- lint
func _test_lint() -> void:
var chk := RollTable.create(RollTable.KIND_CHECK, "chk", "Check")
chk.check_target = "8 +"
chk.check_mod = "dm(@str"
var short := RollTable.create(RollTable.KIND_CHECK, "short", "Short")
short.entries.resize(1)
var show := _show()
show.inputs.append({"name": "Bad Name", "label": "", "default": "1 +"})
show.inputs.append({"name": "tier", "label": "", "default": ""})
var start := RollTable.new("start", "Start")
var e := TableEntry.new("e1", "go")
e.add_pipe("show")
e.set_pipe_with("show", {"tier": "2 +", "extra": "1"})
start.entries.append(e)
var b := _board([chk, short, show, start])
var lint := Roller.lint_pipes(b)
var msgs := {}
for item: Dictionary in lint:
msgs[str(item["message"])] = item
var find := func(prefix: String) -> Dictionary:
for m: String in msgs:
if m.begins_with(prefix):
return msgs[m]
return {}
var target: Dictionary = find.call("Check target 8 +")
_check(not target.is_empty() and target["level"] == "error" and target["kind"] == "check", "bad check target")
_check(not find.call("Check modifier dm(@str").is_empty(), "bad check modifier")
_check(not find.call("A check needs a Success").is_empty(), "missing Failure entry")
var bad_with: Dictionary = find.call("Thread input tier = 2 +")
_check(not bad_with.is_empty() and bad_with["level"] == "error" and bad_with["entry_id"] == "e1", "bad with expression is an error")
var hint: Dictionary = find.call("The thread to Show passes extra")
_check(not hint.is_empty() and hint["level"] == "hint" and hint["kind"] == "inputs", "undeclared input is a hint")
_check(not find.call("Input \"Bad Name\" isn't a name").is_empty(), "bad input name")
_check(not find.call("Input Bad Name default").is_empty(), "bad input default")
_check(not find.call("Input tier is declared twice").is_empty(), "duplicate input")
_check(Roller.lint_check(show).is_empty(), "lint_check only on checks")
_check(Roller.lint_check(RollTable.create(RollTable.KIND_CHECK, "ok", "Ok")).is_empty(), "a new check is clean")
# BoardTester carries kind and level through.
var probs := BoardTester.static_checks(b)
var kinds := {}
var hint_level := false
for p: Dictionary in probs:
kinds[p["kind"]] = true
if str(p["text"]).begins_with("The thread to Show passes extra"):
hint_level = p.get("level", "") == "hint"
_check(kinds.has("check") and kinds.has("inputs"), "static checks have check and inputs kinds: %s" % [kinds.keys()])
_check(hint_level, "static check keeps the hint level")
# A clean board with checks and inputs has no static problems.
var good := _board([RollTable.create(RollTable.KIND_CHECK, "c", "C"), _show()])
good.get_table("c").entries[0].add_pipe("show")
good.get_table("c").entries[0].set_pipe_with("show", {"tier": "total"})
_eq(BoardTester.static_checks(good), [] as Array[Dictionary], "clean spread")