TableTower/tests/test_logic.gd

720 lines
35 KiB
GDScript3
Raw Normal View History

extends TestBase
## Headless checks for logic cards (docs/LOGIC.md): expressions, effects,
## variables, choice / loop / variable / sheet cards, the action limit, long
## chains and the file format.
## Run: tools/run_tests.sh logic
func run() -> void:
_test_expressions()
_test_effects()
_test_variables()
await _test_choices()
_test_loops()
await _test_loop_from_answer()
_test_cycles()
_test_long_chain()
_test_expression_dice()
_test_sheet()
_test_json()
await _test_character()
finish()
# ---------------------------------------------------------------- helpers
func _rng(seed_value: int) -> RandomNumberGenerator:
var r := RandomNumberGenerator.new()
r.seed = seed_value
return r
func _board(tables: Array) -> TowerBoard:
var b := TowerBoard.new()
b.id = "logic-test"
for t in tables:
b.tables.append(t)
return b
func _table(id: String, texts: Array) -> RollTable:
var t := RollTable.new(id, id.capitalize())
for i in texts.size():
t.entries.append(TableEntry.new("e%d" % (i + 1), texts[i]))
return t
func _ctx(vars: Dictionary = {}, board: TowerBoard = null) -> RollContext:
var ctx := RollContext.new(vars, _rng(1))
ctx.board = board
return ctx
func _ev(src: String, ctx: RollContext = null) -> Variant:
return Expr.evaluate(src, ctx)["value"]
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
func _vars(pairs: Dictionary) -> Dictionary:
var out := {}
for k: String in pairs:
out[k] = {"value": pairs[k], "source": ""}
return out
func _texts(steps: Array) -> Array:
var out := []
for s: Dictionary in steps:
out.append(Formatter.strip_tags(str(s["text"])))
return out
## A prompt hook that answers from a script: kind -> reply (or a Callable
## taking the request). Records every request in `log`.
func _scripted(answers: Dictionary, log: Array) -> Callable:
return func(req: Dictionary) -> Variant:
log.append(req)
var a: Variant = answers.get(str(req["kind"]))
if a is Callable:
return (a as Callable).call(req)
return a
# ---------------------------------------------------------------- expressions
func _test_expressions() -> void:
_eq(_ev("1 + 2 * 3"), 7, "arithmetic")
_eq(_ev("7 / 2"), 3, "whole-number division")
_eq(_ev("floor(2.5) + 1"), 3, "whole float results come back as ints")
_check(_ev("floor(2.5)") is int, "floor() result is an int")
_eq(_ev("min(3, 2) + max(1, 4) + clamp(9, 0, 5) + abs(-2)"), 13, "built-in functions")
_eq(_ev("not (1 = 2) and true"), true, "a lone = means equals; not/and")
_eq(Expr.rewrite("@a = 1"), "_v0 == 1", "rewrite turns = into ==")
_eq(_ev("1 == 1 && !false || false"), true, "&& || !")
_eq(_ev("\"ps\" in \"Psionic\""), false, "in is case-sensitive text contains")
_eq(_ev("\"Psi\" in \"Psionic\""), true, "in finds text")
# Dice.
var rng_ctx := _ctx()
var specs := {"2d6": [2, 12], "d20": [1, 20], "3D": [3, 18], "D3": [1, 3], "2D": [2, 12], "1d6 + 10": [11, 16]}
for src: String in specs:
var lo := 999
var hi := -999
for k in 400:
var v: int = _ev(src, rng_ctx)
lo = mini(lo, v)
hi = maxi(hi, v)
_check(lo == specs[src][0] and hi == specs[src][1], "%s rolls %d..%d (saw %d..%d)" % [src, specs[src][0], specs[src][1], lo, hi])
var seen := {}
for k in 50:
seen[_ev("2d6 - 2d6", rng_ctx)] = true
_check(seen.size() > 3, "every die in an expression is rolled fresh")
_check(Expr.check("1000d6") != "", "an absurd dice count is an error, not a hang")
# dm().
var dms := {0: -3, 1: -2, 2: -2, 3: -1, 5: -1, 6: 0, 8: 0, 9: 1, 11: 1, 12: 2, 14: 2, 15: 3, 20: 3}
for x: int in dms:
_eq(_ev("dm(%d)" % x), dms[x], "dm(%d)" % x)
var vars := _vars({"str": 9, "traits": "Psionic, Gun Combat", "skill_pilot": 0, "skill_gun_combat": 1, "name": "Aslan", "num_text": "12"})
var ctx := _ctx(vars)
_eq(_ev("dm(@str)", ctx), 1, "dm(@str)")
_eq(_ev("has(@traits, \"gun combat\")", ctx), true, "has() matches items case-insensitively")
_eq(_ev("has(@traits, \"Gun\")", ctx), false, "has() matches whole items")
_eq(_ev("count(\"skill_\")", ctx), 2, "count(prefix)")
_eq(_ev("count(@skill_*)", ctx), 2, "count(@prefix_*)")
_eq(_ev("@str = 9", ctx), true, "@var = n")
_eq(_ev("@STR >= 9 and @str < 10", ctx), true, "@names are case-insensitive")
_eq(_ev("@name == \"Aslan\"", ctx), true, "text comparison")
_eq(_ev("@num_text + 1", ctx), 13, "number-like text reads as a number")
# Unset variables.
_eq(_ev("@nope + 1", ctx), 1, "unset reads as 0 in arithmetic")
_eq(_ev("@nope + \"x\"", ctx), "x", "unset reads as \"\" next to text")
_eq(_ev("@nope == \"\"", ctx), true, "unset equals \"\"")
_eq(_ev("@nope == 0", ctx), true, "unset equals 0")
_eq(_ev("missing_chain + 2", ctx), 2, "an unset chain variable reads as 0")
ctx.chain_vars["answer"] = 4
_eq(_ev("answer * 2", ctx), 8, "bare names read chain variables")
# Errors are values.
for bad in ["1 +", "\"abc", "(1", "@", "nosuchfn(1)", "\"a\" - 1", ""]:
var r := Expr.evaluate(bad, ctx)
_check(r["error"] != "" and r["value"] == null, "error reported for %s (%s)" % [bad, r["error"]])
_check(Expr.check("2d6 + dm(@end)") == "", "check() accepts a good expression")
_check(Expr._cache.has("2d6 + dm(@end)"), "parsed expressions are cached")
_eq(Expr.format_value(9.0), "9", "format: no .0")
_eq(Expr.format_value(2.5), "2.5", "format: decimals kept")
# ---------------------------------------------------------------- effects
func _test_effects() -> void:
var str_card := RollTable.create(RollTable.KIND_VARIABLE, "v_str", "STR")
str_card.var_name = "str"
str_card.initial = "7"
var vacc := RollTable.create(RollTable.KIND_VARIABLE, "v_vacc", "Vacc Suit")
vacc.var_name = "skill_vacc_suit"
var board := _board([str_card, vacc])
var vars := {}
var ctx := _ctx(vars, board)
var log := Effects.run("@str = 9", ctx, "src")
_eq(_var(vars, "str"), 9, "= sets a number")
_check(_var(vars, "str") is int, "the value is an int")
_eq(Effects.log_text(log), PackedStringArray(["STR = 9"]), "log uses the variable card's name")
_eq(vars["str"]["source"], "src", "source table is kept")
_check(ctx.persistent_changed, "persistent_changed is set")
log = Effects.run("@n += 2; @n -= 5\n@n *= 3", ctx)
_eq(_var(vars, "n"), -9, "+= -= *= on numbers (unset counts as 0)")
_eq(Effects.log_text(log), PackedStringArray(["N +2 → 2", "N -5 → -3", "N ×3 → -9"]), "number log lines")
Effects.run("@n /= 2", ctx)
_eq(_var(vars, "n"), -5, "/= rounds down")
Effects.run("@m = 7; @m /= 2", ctx)
_eq(_var(vars, "m"), 3, "7 /= 2 is 3")
log = Effects.run("@skill_pilot += 1", ctx)
_eq(Effects.log_text(log), PackedStringArray(["Skill Pilot +1 → 1"]), "unset += 1 gives 1")
Effects.run("@skill_vacc_suit = max(@skill_vacc_suit, 0)", ctx)
_eq(_var(vars, "skill_vacc_suit"), 0, "gain at level 0")
# Text and lists.
Effects.run("@traits += \"Psionic\"", ctx)
_eq(_var(vars, "traits"), "Psionic", "+= text on unset")
Effects.run("@traits += \"psionic\"", ctx)
_eq(_var(vars, "traits"), "Psionic", "+= doesn't add an item twice")
log = Effects.run("@traits += \"Brave\"", ctx)
_eq(_var(vars, "traits"), "Psionic, Brave", "+= appends \", item\"")
_eq(Effects.log_text(log), PackedStringArray(["Traits + Brave → Psionic, Brave"]), "list log line")
Effects.run("@traits -= \"PSIONIC\"", ctx)
_eq(_var(vars, "traits"), "Brave", "-= removes the item")
Effects.run("@traits -= \"Brave\"", ctx)
_eq(_var(vars, "traits"), "", "-= the last item leaves empty text")
Effects.run("@name = \"Aslan\"", ctx)
_eq(_var(vars, "name"), "Aslan", "= sets text")
log = Effects.run("@name *= 2", ctx)
_check(log[0].get("error", false), "*= on text is an error")
Effects.run("hero = \"Mira\"", ctx)
_eq(ctx.chain_vars.get("hero"), "Mira", "a target without @ is a chain variable")
# reset.
Effects.run("@str = 12; reset @str", ctx)
_eq(_var(vars, "str"), 7, "reset goes back to the starting value")
Effects.run("@tmp = 1; reset @tmp", ctx)
_check(not vars.has("tmp"), "reset deletes an undeclared variable")
Effects.run("@skill_gun = 2; @skill_vacc_suit = 3", ctx)
log = Effects.run("reset @skill_*", ctx)
_check(not vars.has("skill_pilot") and not vars.has("skill_gun"), "reset @prefix_* deletes undeclared ones")
_eq(_var(vars, "skill_vacc_suit"), 0, "reset @prefix_* resets declared ones")
_check(not log[0].get("error", false) and str(log[0]["text"]).begins_with("Reset @skill_*"), "reset log: %s" % str(log))
# Bad statements don't stop the rest.
log = Effects.run("@x == 3; garbage; @y = (1; @z = 5", ctx)
_eq(log.size(), 4, "one log line per statement")
_check(log[0].get("error", false) and log[1].get("error", false) and log[2].get("error", false), "bad statements are errors")
_eq(_var(vars, "z"), 5, "statements after an error still run")
# Validation for the editor.
var probs := Effects.validate("@a = 1\n@b += (\nreset @c;reset c")
_eq(probs.size(), 2, "validate finds the two bad statements: %s" % str(probs))
_check(probs.size() == 2 and probs[0]["index"] == 1 and probs[1]["index"] == 3, "validate reports statement indexes")
_check(Effects.validate("@str = 2d6; @age *= 2; reset @skill_*").is_empty(), "good effects validate clean")
_eq(Effects.split("@a = \"x;y\"; @b = 1"), ["@a = \"x;y\"", "@b = 1"] as Array[String], "; inside quotes doesn't split")
# ---------------------------------------------------------------- variables
func _test_variables() -> void:
var ctx := _ctx(_vars({"skill_pilot": 0, "skill_gun_combat": 1, "skill_zero_g": 2, "str": 7}))
var list := ctx.list_vars("@skill_*")
_eq(list.size(), 3, "list_vars by prefix")
_check(list.size() == 3 and list[0]["label"] == "Gun Combat" and list[2]["label"] == "Zero G", "labels are title-cased and sorted")
_eq(ctx.list_text("skill_"), "Gun Combat 1, Pilot 0, Zero G 2", "list_text")
_eq(RollContext.vars_with_prefix(ctx.persistent_vars, "s").size(), 4, "vars_with_prefix works on plain dictionaries")
# StateStore keeps numbers as numbers.
var dir := "user://test_logic_state"
var st := StateStore.new(dir)
st.reload()
st.set_variable("c", "str", 9, "t")
st.set_variable("c", "ratio", 2.5)
st.set_variable("c", "name", "Aslan")
st.save()
var back := StateStore.new(dir).get_variables("c")
_check(back["str"]["value"] is int and back["str"]["value"] == 9, "an int survives the state file")
_check(back["ratio"]["value"] is float and back["ratio"]["value"] == 2.5, "a float survives")
_check(back["name"]["value"] is String, "text survives")
DirAccess.remove_absolute(st.state_path())
DirAccess.remove_absolute(dir.path_join("state"))
DirAccess.remove_absolute(dir)
# Variable cards.
var card := RollTable.create(RollTable.KIND_VARIABLE, "v", "Species", "text")
card.var_name = "species"
card.initial = "Aslan"
var b := _board([card])
var shown := Roller.variable_display(b, {}, card)
_check(shown["text"] == "Aslan" and not shown["set"], "variable card shows its starting value when unset")
shown = Roller.variable_display(b, _vars({"species": "Vargr"}), card)
_check(shown["text"] == "Vargr" and shown["set"], "variable card shows the live value")
_check(Roller.roll(b, "v", _rng(1)).is_empty(), "a variable card is never rolled")
# ---------------------------------------------------------------- choices
func _choice_board() -> TowerBoard:
var career := RollTable.create(RollTable.KIND_CHOICE, "career", "Career", "pick")
career.prompt = "Your EDU is {@edu}. Which career?"
career.save_as = "@career"
career.entries[0].text = "Navy"
career.entries[1].text = "Army"
career.entries[1].effects = "@branch = \"ground\""
career.entries[1].details = "Boots on the ground."
career.entries[2].text = "Scouts"
var after := _table("after", ["Then {@career}"])
for e in career.entries:
e.add_pipe("after")
var terms := RollTable.create(RollTable.KIND_CHOICE, "terms_q", "Terms", "number")
terms.min_expr = "1"
terms.max_expr = "@max_terms"
terms.save_as = "@terms"
terms.entries[0].effects = "@total += answer"
terms.entries[0].add_pipe("term", "answer")
var term := _table("term", ["A term"])
var hero := RollTable.create(RollTable.KIND_CHOICE, "hero_q", "Hero", "text")
hero.save_as = "hero"
hero.entries[0].add_pipe("greet")
var greet := _table("greet", ["Hello {hero} ({answer})"])
return _board([career, after, terms, term, hero, greet])
func _test_choices() -> void:
var b := _choice_board()
# pick: a scripted index.
var vars := _vars({"edu": 9})
var ctx := Roller.new_context(b, _rng(2), vars, {})
var reqs: Array = []
ctx.prompt = _scripted({"pick": 1}, reqs)
var n: Dictionary = await Roller.roll_async(b, "career", ctx)
_eq(reqs.size(), 1, "one prompt")
var req: Dictionary = reqs[0] if not reqs.is_empty() else {}
_check(req.get("kind") == "pick" and req.get("table_id") == "career" and (req.get("options", []) as Array).size() == 3, "pick request shape: %s" % str(req))
_eq(Formatter.strip_tags(str(req.get("prompt", ""))), "Your EDU is 9. Which career?", "prompt expands {@var}")
_check(req.has("min") and req.has("max") and req.get("default") == -1, "request has min, max and default")
_check((req.get("options", [{}, {}]) as Array)[1].get("details") == "Boots on the ground." and (req["options"] as Array)[1].get("index") == 1, "options carry index and details")
_check(n.get("picked", false) and (n["entry"] as TableEntry).text == "Army" and n.get("kind") == "choice", "picked entry is the node's entry")
_eq(_var(vars, "branch"), "ground", "picked entry's effects run")
_eq(_var(vars, "career"), "Army", "save_as gets the picked text")
_check((n["children"] as Array).size() == 1 and Formatter.strip_tags((n["children"] as Array)[0]["summary"]) == "Then Army", "picked entry's threads follow")
_check(not n.has("value"), "a picked entry has no die value")
# pick: Random.
var randoms := {}
for k in 30:
var c2 := Roller.new_context(b, ctx.rng, _vars({"edu": 9}), {})
c2.prompt = _scripted({"pick": -1}, [])
var r: Dictionary = await Roller.roll_async(b, "career", c2)
_check(r.get("random", false) and r.has("value"), "Random rolls the card")
randoms[(r["entry"] as TableEntry).text] = true
_eq(randoms.size(), 3, "Random can give every option")
# number with save_as, answer, the Answer entry's effects and pipes.
vars = _vars({"max_terms": 4, "total": 10})
ctx = Roller.new_context(b, _rng(3), vars, {})
reqs = []
ctx.prompt = _scripted({"number": 99}, reqs)
n = await Roller.roll_async(b, "terms_q", ctx)
_check(not reqs.is_empty() and reqs[0]["min"] == 1 and reqs[0]["max"] == 4 and reqs[0]["default"] == 1, "number request min/max/default from expressions")
_eq(n.get("answer"), 4, "number answer is clamped to max")
_eq(Formatter.strip_tags(str(n["summary"])), "4", "number result text is the number")
_eq(_var(vars, "terms"), 4, "save_as gets the number")
_check(_var(vars, "terms") is int, "...as an int")
_eq(ctx.chain_vars.get("answer"), 4, "chain variable answer")
_eq(_var(vars, "total"), 14, "the Answer entry's effects see answer")
_eq((n["children"] as Array).size(), 4, "the Answer entry's thread count can be an expression")
_check(n.has("effects") and Effects.log_text(n["effects"]) == PackedStringArray(["Total +4 → 14"]), "effects log on the node: %s" % str(n.get("effects")))
var steps := Roller.flatten(n, [])
_check(steps[0].get("answer") == 4 and steps[0].get("kind") == "choice" and steps[0].has("effects"), "steps carry kind, answer and effects")
# Headless: number answers min.
var hn := Roller.roll(b, "terms_q", _rng(4), 0, {}, Roller.new_context(b, _rng(4), _vars({"max_terms": 4}), {}))
_eq(hn.get("answer"), 1, "headless number answers min")
# text.
ctx = Roller.new_context(b, _rng(5), {}, {})
ctx.prompt = _scripted({"text": "Zed"}, [])
n = await Roller.roll_async(b, "hero_q", ctx)
_check(n.get("answer") == "Zed" and Formatter.strip_tags(str(n["summary"])) == "Zed", "text answer")
_eq(ctx.chain_vars.get("hero"), "Zed", "text save_as to a chain variable")
_eq(Formatter.strip_tags((n["children"] as Array)[0]["summary"]), "Hello Zed (Zed)", "later tables use the answer")
var ht := Roller.roll(b, "hero_q", _rng(5))
_eq(ht.get("answer"), "", "headless text answers \"\"")
# Cancel.
ctx = Roller.new_context(b, _rng(6), _vars({"edu": 9}), {})
ctx.prompt = _scripted({"pick": null}, [])
n = await Roller.roll_async(b, "career", ctx)
_check(n.get("stop") == "Cancelled" and n.get("cancelled", false), "Cancel gives a Cancelled stop node")
_eq(ctx.halted, "Cancelled", "ctx.halted says Cancelled")
# Cancel deeper in a chain keeps what came before and stops the rest.
var start := _table("start", ["Begin"])
start.entries[0].add_pipe("career")
start.entries[0].add_pipe("after")
b.tables.append(start)
ctx = Roller.new_context(b, _rng(7), _vars({"edu": 9}), {})
ctx.prompt = _scripted({"pick": null}, [])
n = await Roller.roll_async(b, "start", ctx)
_eq(_texts(Roller.flatten(n, [])), ["Begin", "Cancelled"], "nothing runs after Cancel")
# A prompt that really waits: the steps so far can be read meanwhile.
ctx = Roller.new_context(b, _rng(8), _vars({"edu": 9}), {})
var seen := {}
ctx.prompt = func(_r: Dictionary) -> Variant:
seen["steps"] = _texts(Roller.progress(ctx))
await process_frame
seen["resumed"] = true
return 2
seen["resumed"] = false
n = await Roller.roll_async(b, "start", ctx)
_eq(seen.get("steps"), ["Begin"], "progress() shows the steps before the question")
_check(seen.get("resumed", false), "the roll waited for the prompt")
ctx.prompt = Callable()
_eq(_texts(Roller.flatten(n, [])), ["Begin", "Scouts", "Then Scouts", "Then Scouts"], "the roll finishes after the answer")
# A [[reference]] into a choice card prompts too.
var ask := _table("ask", ["You chose [[Career]]!"])
b.tables.append(ask)
ctx = Roller.new_context(b, _rng(9), _vars({"edu": 9}), {})
reqs = []
ctx.prompt = _scripted({"pick": 0}, reqs)
n = await Roller.roll_async(b, "ask", ctx)
_check(reqs.size() == 1 and Formatter.strip_tags(str(n["summary"])) == "You chose Navy!", "a reference into a choice card prompts: %s" % Formatter.strip_tags(str(n["summary"])))
# ---------------------------------------------------------------- loops
func _test_loops() -> void:
# times
var loop := RollTable.create(RollTable.KIND_LOOP, "loop", "Repeat", "times")
loop.loop_expr = "3"
loop.entries[0].effects = "@sum += i"
loop.entries[0].text = "Pass {i}"
loop.entries[1].add_pipe("done")
var done := _table("done", ["Done after {= @sum}"])
var b := _board([loop, done])
var vars := {}
var ctx := Roller.new_context(b, _rng(1), vars, {})
var n := Roller.roll(b, "loop", ctx.rng, 0, {}, ctx)
_check(n.get("kind") == "loop" and n.get("passes") == 3, "times runs 3 passes")
_eq(n.get("summary"), "Repeated 3 times", "loop node text")
_eq(_var(vars, "sum"), 6, "i is 1, 2, 3")
_eq(_texts(Roller.flatten(n, [])), ["Repeated 3 times", "Pass 1", "Pass 2", "Pass 3", "Afterwards", "Done after 6"], "loop steps")
_check(not ctx.chain_vars.has("i"), "i is gone after the repeat")
var steps := Roller.flatten(n, [])
_check(steps[1].get("pass") == 1 and steps[1]["num"] == "1" and steps[4].get("after", false) and steps[0].get("passes") == 3, "pass and Afterwards steps are marked")
var le := {}
var lp := {}
Roller.collect_lit(n, le, lp)
_check(lp.has(Roller.pipe_key("loop", "e2", "done")) and not lp.has(Roller.pipe_key("loop", "e1", "loop")), "passes light no thread; Afterwards' thread is lit")
loop.loop_expr = "0"
n = Roller.roll(b, "loop", _rng(2))
_check(n.get("passes") == 0 and (n["children"] as Array).size() == 1, "times 0 runs only Afterwards")
loop.loop_expr = "1d3"
for k in 20:
var p: int = Roller.roll(b, "loop", _rng(k)).get("passes", -1)
_check(p >= 1 and p <= 3, "times 1d3")
loop.loop_expr = "nope("
n = Roller.roll(b, "loop", _rng(2))
_check(n.get("passes") == 0 and n.has("effects") and n["effects"][0].get("error", false), "a bad loop rule is logged, not fatal")
# while
loop.loop_mode = "while"
loop.loop_expr = "@hp > 0"
loop.entries[0].effects = "@hp -= 3"
vars = _vars({"hp": 10})
n = Roller.roll(b, "loop", _rng(3), 0, {}, Roller.new_context(b, _rng(3), vars, {}))
_check(n.get("passes") == 4 and _var(vars, "hp") == -2, "while stops when the condition is false (%s passes)" % str(n.get("passes")))
vars = _vars({"hp": 0})
n = Roller.roll(b, "loop", _rng(3), 0, {}, Roller.new_context(b, _rng(3), vars, {}))
_eq(n.get("passes"), 0, "while can run 0 times")
# until
loop.loop_mode = "until"
loop.loop_expr = "@n >= 5"
loop.entries[0].effects = "@n += 2"
vars = _vars({"n": 0})
n = Roller.roll(b, "loop", _rng(4), 0, {}, Roller.new_context(b, _rng(4), vars, {}))
_check(n.get("passes") == 3 and _var(vars, "n") == 6, "until stops when the condition is true")
vars = _vars({"n": 10})
n = Roller.roll(b, "loop", _rng(4), 0, {}, Roller.new_context(b, _rng(4), vars, {}))
_eq(n.get("passes"), 1, "until runs at least once")
# An endless while stops at the action limit.
loop.loop_mode = "while"
loop.loop_expr = "true"
loop.entries[0].effects = ""
ctx = Roller.new_context(b, _rng(5), {}, {})
n = Roller.roll(b, "loop", ctx.rng, 0, {}, ctx)
var last: Dictionary = (n["children"] as Array).back()
_check(last.get("limit", false) and n.get("passes") == RollContext.DEFAULT_MAX_ACTIONS - 1, "an endless loop stops at the limit (%s passes)" % str(n.get("passes")))
func _test_loop_from_answer() -> void:
var q := RollTable.create(RollTable.KIND_CHOICE, "q", "How many?", "number")
q.max_expr = "10"
q.entries[0].add_pipe("loop")
var loop := RollTable.create(RollTable.KIND_LOOP, "loop", "Repeat", "times")
loop.loop_expr = "answer"
loop.entries[0].effects = "@count += 1"
var b := _board([q, loop])
var vars := {}
var ctx := Roller.new_context(b, _rng(1), vars, {})
ctx.prompt = _scripted({"number": 4}, [])
var n: Dictionary = await Roller.roll_async(b, "q", ctx)
var header: Dictionary = (n["children"] as Array)[0] if not (n["children"] as Array).is_empty() else {}
_check(header.get("passes") == 4 and _var(vars, "count") == 4, "a loop driven by a number answer")
n = Roller.roll(b, "q", _rng(2))
_eq(((n["children"] as Array)[0] as Dictionary).get("passes"), 0, "headless answer 0 runs no passes")
# ---------------------------------------------------------------- cycles
func _test_cycles() -> void:
# A pipe cycle that ends on a condition (the count is 1 while @k < 5).
var a := _table("a", ["Step {@k}"])
a.entries[0].effects = "@k += 1"
a.entries[0].add_pipe("a", "@k < 5")
var b := _board([a])
var vars := {}
var n := Roller.roll(b, "a", _rng(1), 0, {}, Roller.new_context(b, _rng(1), vars, {}))
_eq(_texts(Roller.flatten(n, [])), ["Step 1", "Step 2", "Step 3", "Step 4", "Step 5"], "a cycle ends on its condition")
_check(Roller.endless_cycles(b).is_empty(), "an expression-count cycle isn't flagged as endless")
# An endless cycle stops at exactly 10,000 actions.
var loop := _table("loop", ["Again"])
loop.entries[0].add_pipe("loop")
var b2 := _board([loop])
var ctx := Roller.new_context(b2, _rng(2), {}, {})
var t0 := Time.get_ticks_msec()
n = Roller.roll(b2, "loop", ctx.rng, 0, {}, ctx)
var ms := Time.get_ticks_msec() - t0
var steps := Roller.flatten(n, [])
_eq(steps.size(), 10001, "10,000 tables plus the marker")
_eq(ctx.actions, 10000, "exactly 10,000 actions")
_eq(str(steps.back()["text"]), "Stopped after 10,000 actions", "the limit marker")
_check(steps.back().get("stop", false) and steps.back().get("limit", false), "the marker is a stop step")
_eq(ctx.halted, "Stopped after 10,000 actions", "ctx.halted")
_check(ms < 15000, "the endless cycle stops in reasonable time (%d ms)" % ms)
_eq(Roller.endless_cycles(b2), ["loop"] as Array[String], "a plain self-thread is still flagged")
# Mixed with inline references.
var r := _table("r", ["[[Loop]] and on"])
b2.tables.append(r)
ctx = Roller.new_context(b2, _rng(3), {}, {})
n = Roller.roll(b2, "r", ctx.rng, 0, {}, ctx)
_check(ctx.actions == 10000 and ctx.halted != "", "the limit holds inside a reference")
func _test_long_chain() -> void:
var a := _table("a", ["Link {@k}"])
a.entries[0].effects = "@k += 1"
a.entries[0].add_pipe("a", "@k < 5000")
var b := _board([a])
var ctx := Roller.new_context(b, _rng(1), {}, {})
var n := Roller.roll(b, "a", ctx.rng, 0, {}, ctx)
var steps := Roller.flatten(n, [])
_eq(steps.size(), 5000, "a 5,000-step chain")
_eq(int(steps.back()["depth"]), 4999, "it nests 5,000 deep")
var le := {}
var lp := {}
var lt := {}
Roller.collect_lit(n, le, lp, lt)
_check(le.size() == 1 and lp.size() == 1, "collect_lit walks it")
_check(Roller.reaches(n, "a") and not Roller.reaches(n, "zzz"), "reaches walks it")
_check(JSON.stringify(steps).length() > 0, "its steps serialize")
# ---------------------------------------------------------------- dice
func _ranged(dice: String, ranges: Array) -> RollTable:
var t := RollTable.new("check", "Check")
t.dice = dice
for i in ranges.size():
var e := TableEntry.new("e%d" % (i + 1), ranges[i][2])
e.has_range = true
e.range_lo = ranges[i][0]
e.range_hi = ranges[i][1]
t.entries.append(e)
return t
func _test_expression_dice() -> void:
var t := _ranged("2d6 + dm(@end)", [[2, 6, "Fail"], [7, 12, "Pass"]])
var b := _board([t])
_check(t.is_expr_dice() and not t.has_chances(), "an expression dice table")
_eq(t.num_label(t.entries[0], 0), "≤6", "low end label")
_eq(t.num_label(t.entries[1], 1), "7+", "high end label")
_check(t.chance(t.entries[0]) == 0.0, "no chances for expression dice")
_eq(t.range_problems(), "", "no gap warnings past the ends")
_check(t.min_value() == 2 and t.die_size() == 12, "span is the ranges' span")
_eq(t.dice_label(), "2d6 + dm(@end)", "the label is the expression")
var high := 0
for k in 200:
var n := Roller.roll(b, "check", _rng(k), 0, {}, Roller.new_context(b, _rng(k), _vars({"end": 15}), {}))
_check(not n.has("stop"), "high values clamp to the top range")
if int(n.get("value", 0)) > 12:
high += 1
_eq((n["entry"] as TableEntry).text, "Pass", "a 13+ lands on 7+")
_check(high > 0, "values past 12 happened (%d)" % high)
for k in 50:
var n := Roller.roll(b, "check", _rng(k), 0, {}, Roller.new_context(b, _rng(k), _vars({"end": 0}), {}))
if int(n.get("value", 99)) < 2:
_eq((n["entry"] as TableEntry).text, "Fail", "values under 2 clamp to ≤6")
t.dice = "@terms"
var n2 := Roller.roll(b, "check", _rng(1), 0, {}, Roller.new_context(b, _rng(1), _vars({"terms": 20}), {}))
_check(n2.get("value") == 20 and (n2["entry"] as TableEntry).text == "Pass", "a plain variable as dice")
var gap := _ranged("1d6 + @x", [[2, 5, "Low"], [7, 12, "High"]])
_eq(gap.range_problems(), "No result for 6.", "a gap between ranges is still reported")
var plain := _ranged("2d6", [[2, 6, "Fail"], [7, 12, "Pass"]])
_check(not plain.is_expr_dice() and plain.num_label(plain.entries[0], 0) == "2–6" and plain.has_chances(), "plain dice are unchanged")
t.dice = "2d6 +"
var bad := Roller.roll(b, "check", _rng(1))
_check(bad.has("stop"), "a broken dice expression stops with a message: %s" % str(bad.get("stop")))
# ---------------------------------------------------------------- sheet
func _test_sheet() -> void:
var sheet := RollTable.create(RollTable.KIND_SHEET, "sheet", "Sheet")
sheet.entries[0].text = "STR {@str} ({= dm(@str)})\nSkills: {@skill_*}\n{= 1 +}"
var start := _table("start", ["Go"])
start.entries[0].add_pipe("sheet")
var b := _board([sheet, start])
var vars := _vars({"str": 9, "skill_gun_combat": 1, "skill_pilot": 0})
var live := Roller.render_sheet(b, vars, sheet)
var lines := Formatter.strip_tags(live).split("\n")
_eq(lines[0], "STR 9 (1)", "sheet: {@str} and {= dm(@str)}")
_eq(lines[1], "Skills: Gun Combat 1, Pilot 0", "sheet: {@skill_*}")
_check(live.contains("[url=error:expr]"), "a bad {= } shows an error marker")
_eq(Formatter.to_export_bbcode(live).contains("url="), false, "the error marker is internal")
var n := Roller.roll(b, "start", _rng(1), 0, {}, Roller.new_context(b, _rng(1), vars, {}))
var s := Roller.last_sheet(n)
_check(s.get("kind") == "sheet" and Formatter.strip_tags(str(s.get("summary"))).begins_with("STR 9 (1)"), "the chain's sheet node is its rendered template")
_eq(Roller.flatten(n, [])[1].get("kind"), "sheet", "sheet steps are marked")
var ctx := _ctx(_vars({"n": 3.0, "t": "x"}))
_eq(Formatter.strip_tags(TextExpander.expand("{@n} {@t} {@none} {= @n * 2}", ctx)["text"]), "3 x {@none?} 6", "{@n} shows numbers without .0")
_eq(Formatter.strip_tags(TextExpander.expand("{@zz_*}.", ctx)["text"]), ".", "an empty list shows nothing")
# ---------------------------------------------------------------- JSON
func _test_json() -> void:
var roll := RollTable.create(RollTable.KIND_ROLL, "roll", "Roll")
roll.entries[0].effects = "@a = 2d6\nreset @skill_*"
roll.entries[0].add_pipe("loop", "@terms")
roll.entries[1].add_pipe("choice", 2, "@picked")
var pick := RollTable.create(RollTable.KIND_CHOICE, "choice", "Choice", "pick")
pick.save_as = "@career"
var num := RollTable.create(RollTable.KIND_CHOICE, "num", "Num", "number")
num.min_expr = "1"
num.max_expr = "@max"
var txt := RollTable.create(RollTable.KIND_CHOICE, "txt", "Txt", "text")
var loop := RollTable.create(RollTable.KIND_LOOP, "loop", "Repeat", "until")
var vcard := RollTable.create(RollTable.KIND_VARIABLE, "var", "STR", "list")
vcard.initial = "\"a, b\""
var sheet := RollTable.create(RollTable.KIND_SHEET, "sheet", "Sheet")
var ranged := _ranged("2d6 + dm(@end)", [[2, 6, "Fail"], [7, 12, "Pass"]])
var b := _board([roll, pick, num, txt, loop, vcard, sheet, ranged])
b.name = "Logic"
# Factory shapes.
_check(num.entries.size() == 1 and num.entries[0].text == "Answer", "a number choice has one Answer entry")
_check(txt.entries.size() == 1 and txt.entries[0].text == "Answer", "a text choice has one Answer entry")
_check(pick.entries.size() >= 2, "a pick choice has options")
_check(loop.entries.size() == 2 and loop.entries[0].text == "Each time" and loop.entries[1].text == "Afterwards", "a loop has Each time and Afterwards")
_check(vcard.entries.is_empty() and vcard.var_name == "str" and vcard.var_type == "list", "a variable card")
_check(sheet.entries.size() == 1 and sheet.kind == "sheet", "a sheet card has one template entry")
# Defaults are left out.
var plain := _table("p", ["x"]).to_dict()
for k in ["kind", "choice", "prompt", "save_as", "min", "max", "loop", "loop_expr", "var_name", "var_type", "initial"]:
_check(not plain.has(k), "a plain table has no %s key" % k)
_check(not plain["entries"][0].has("effects"), "an entry without effects has no effects key")
var d := num.to_dict()
_check(d["kind"] == "choice" and d["choice"] == "number" and d["min"] == "1" and d["max"] == "@max" and not d.has("save_as"), "choice keys: %s" % str(d))
_eq(roll.to_dict()["entries"][0]["pipes"], [{"table": "loop", "count": "@terms"}], "an expression thread count")
# RollTable round trip through JSON text.
var text := b.to_json()
var b2 := TowerBoard.new()
_check(b2.load_json(text), "spread JSON loads")
_eq(b2.to_json(), text, "spread JSON round-trips unchanged")
_eq(b2.get_table("roll").entries[0].count_expr("loop"), "@terms", "expression count survives")
# JsonIO canonical/import keep every new key.
var exported := JsonIO.export_json(b.to_dict())
var imp := JsonIO.import_json(exported)
_check(imp["ok"], "import ok: %s" % str(imp["errors"]))
var b3 := TowerBoard.new()
b3.load_dict(imp["collection"])
for t in b.tables:
var t3 := b3.get_table(t.id)
_check(t3 != null and t3.to_dict() == t.to_dict(), "%s survives export and import\n got: %s\n want: %s" % [t.id, str(t3.to_dict() if t3 else {}), str(t.to_dict())])
var canon := JsonIO.canonical({"tables": [{"id": "x", "kind": "choice", "choice": "number", "min": 2.0, "max": 99,
"entries": [{"id": "e1", "text": "Answer", "effects": "@a += 1", "pipes": [{"table": "y", "count": "@n"}, {"table": "z", "count": 3.0}]}]}]})
var ct: Dictionary = canon["tables"][0]
_check(ct["kind"] == "choice" and ct["min"] == "2" and not ct.has("max"), "canonical keeps kind keys, numbers as text, drops defaults: %s" % str(ct))
_check(ct["entries"][0]["effects"] == "@a += 1" and ct["entries"][0]["pipes"] == [{"table": "y", "count": "@n"}, {"table": "z", "count": 3}], "canonical keeps effects and counts: %s" % str(ct["entries"][0]))
_eq(JsonIO.pipe_label(JsonIO.pipe_info({"table": "y", "count": "@n"})), "×@n", "thread label for an expression count")
# ---------------------------------------------------------------- scenario
func _character_board() -> TowerBoard:
var chargen := _table("chargen", ["Create a Traveller"])
chargen.entries[0].effects = "reset @skill_*; @str = 2d6; @dex = 2d6; @end = 2d6\n@edu = 2d6; @terms = 0; @age = 18; @injuries = 0"
chargen.entries[0].add_pipe("career")
var str_card := RollTable.create(RollTable.KIND_VARIABLE, "v_str", "STR")
str_card.var_name = "str"
var career := RollTable.create(RollTable.KIND_CHOICE, "career", "Career", "pick")
career.prompt = "EDU {@edu}. Which career?"
career.save_as = "@career"
var names := ["Navy", "Army", "Scouts"]
for i in 3:
career.entries[i].text = names[i]
career.entries[i].add_pipe("terms_q")
career.entries[0].effects = "@skill_pilot = max(@skill_pilot, 0)"
var terms_q := RollTable.create(RollTable.KIND_CHOICE, "terms_q", "Terms", "number")
terms_q.min_expr = "1"
terms_q.max_expr = "7"
terms_q.save_as = "@want"
terms_q.entries[0].add_pipe("terms")
var terms := RollTable.create(RollTable.KIND_LOOP, "terms", "Terms", "times")
terms.loop_expr = "@want"
terms.entries[0].text = "Term {i}"
terms.entries[0].effects = "@terms += 1; @age += 4"
terms.entries[0].add_pipe("survival")
terms.entries[1].add_pipe("sheet")
var survival := _ranged("2d6 + dm(@end)", [[2, 5, "Injured"], [6, 12, "Survived"]])
survival.id = "survival"
survival.name = "Survival"
survival.entries[0].effects = "@injuries += 1"
survival.entries[1].effects = "@skill_pilot += 1"
var sheet := RollTable.create(RollTable.KIND_SHEET, "sheet", "Traveller")
sheet.entries[0].text = "[b]{@career}[/b], age {@age}\nSTR {@str} ({= dm(@str)}) END {@end}\nTerms {@terms}, injuries {@injuries}\nSkills: {@skill_*}"
return _board([chargen, str_card, career, terms_q, terms, survival, sheet])
func _test_character() -> void:
var b := _character_board()
var vars := _vars({"skill_old": 5})
var ctx := Roller.new_context(b, _rng(42), vars, {})
var reqs: Array = []
ctx.prompt = _scripted({"pick": 0, "number": 3}, reqs)
var n: Dictionary = await Roller.roll_async(b, "chargen", ctx)
var steps := Roller.flatten(n, [])
_eq(reqs.size(), 2, "two questions: career and terms")
_check(not vars.has("skill_old"), "reset @skill_* cleared old skills")
var log := Effects.log_text(steps[0].get("effects", []))
_check(log.size() == 8 and log[1].begins_with("STR = "), "characteristics rolled by effects: %s" % str(log))
var s: int = _var(vars, "str")
_check(s >= 2 and s <= 12, "STR is 2d6")
_eq(_var(vars, "career"), "Navy", "career picked")
_check(_var(vars, "terms") == 3 and _var(vars, "age") == 30, "three terms age the Traveller to 30")
var surv := 0
var survived := 0
for st: Dictionary in steps:
if st["table_id"] == "survival":
surv += 1
if Formatter.strip_tags(str(st["text"])) == "Survived":
survived += 1
_eq(surv, 3, "a survival check each term")
_eq(_var(vars, "skill_pilot"), survived, "each survival raised Pilot (Navy starts it at 0)")
_eq(_var(vars, "injuries"), 3 - survived, "each failure is an injury")
var sheet := Roller.last_sheet(n)
var text := Formatter.strip_tags(str(sheet.get("summary", "")))
_check(text.begins_with("Navy, age 30\nSTR %d (%d) END " % [s, Expr.dm(s)]), "the sheet shows the character:\n%s" % text)
_check(text.contains("Skills: Pilot %d" % survived), "the sheet lists skills:\n%s" % text)
_check(steps.back()["table_id"] == "sheet", "the sheet is the last step")
_check(ctx.actions < 30, "a few dozen actions (%d)" % ctx.actions)
_check(JSON.parse_string(JSON.stringify(steps)) is Array, "steps are plain data")
# ---------------------------------------------------------------- checks