From 6f583ea4f56355db41df2f63af53b0c83955f399 Mon Sep 17 00:00:00 2001 From: RobinFiredrake Date: Sun, 8 Nov 2026 21:01:24 -0600 Subject: [PATCH] Plain Build engine: Describe, Builder, checks, inputs, collections, why trace Implements docs/PLAIN.md sections 1-5 (the engine half of the usability pass): - core/describe.gd (Describe): rules in plain words, labelled from variable cards, collections and card inputs, falling back to the original text. - core/builder.gd (Builder): effect and condition models that round-trip with the rule text, a rule tokenizer, and known_values(board). - Collections: variable cards with var_type "collection" label their members and don't declare their stem. - Check cards (kind "check"): dice + modifier vs target, Success/Failure, chain values nat/total/effect, node "check" info, lint and static checks. - Card inputs and pipe "with" values, scoped over the pipe's subtree on the explicit work stack (OP_RESTORE frames), with defaults and snapshot evaluation. - nat on every roll-table roll; dice faces recorded through ctx.faces. - Why trace: facts on nodes and steps (input, roll, check, case, show_if, options_where, effect, when, otherwise). - StateStore rules_view setting; JSON for the new keys; LOGIC.md and PLAIN.md updated (deviations in PLAIN.md 5a). Co-Authored-By: Claude Opus 5.5 --- core/board_tester.gd | 14 +- core/builder.gd | 487 ++++++++++++++++++++++++ core/builder.gd.uid | 1 + core/describe.gd | 674 +++++++++++++++++++++++++++++++++ core/describe.gd.uid | 1 + core/effects.gd | 23 +- core/expr.gd | 28 ++ core/roll_context.gd | 6 +- core/roll_table.gd | 119 +++++- core/roller.gd | 370 +++++++++++++++++- core/state_store.gd | 22 ++ core/table_entry.gd | 35 +- core/template_kit.gd | 4 +- docs/LOGIC.md | 109 +++++- docs/PLAIN.md | 32 ++ io/json_io.gd | 59 ++- tests/test_builder.gd | 220 +++++++++++ tests/test_builder.gd.uid | 1 + tests/test_check_inputs.gd | 665 ++++++++++++++++++++++++++++++++ tests/test_check_inputs.gd.uid | 1 + tests/test_describe.gd | 356 +++++++++++++++++ tests/test_describe.gd.uid | 1 + ui/table_settings_dialog.gd | 2 +- 23 files changed, 3180 insertions(+), 50 deletions(-) create mode 100644 core/builder.gd create mode 100644 core/builder.gd.uid create mode 100644 core/describe.gd create mode 100644 core/describe.gd.uid create mode 100644 tests/test_builder.gd create mode 100644 tests/test_builder.gd.uid create mode 100644 tests/test_check_inputs.gd create mode 100644 tests/test_check_inputs.gd.uid create mode 100644 tests/test_describe.gd create mode 100644 tests/test_describe.gd.uid diff --git a/core/board_tester.gd b/core/board_tester.gd index 2193a2c..0ff8f49 100644 --- a/core/board_tester.gd +++ b/core/board_tester.gd @@ -252,7 +252,11 @@ func report() -> Dictionary: ## Problems found without rolling anything. Array of {kind, table_id, ## entry_id ("" for the card), table (display name), text}, in board order. -## kinds: expression, effect, range, cycle, missing_pipe, empty_choice, pipes. +## kinds: expression, effect, range, cycle, missing_pipe, empty_choice, pipes, +## check (check cards: bad dice, modifier or target, missing results) and +## inputs (card inputs and pipe "with" values; see Roller.lint_inputs()). +## Items from Roller.lint_pipes() also carry its "level" when it has one +## ("error" or "hint"). static func static_checks(b: TowerBoard) -> Array[Dictionary]: var out: Array[Dictionary] = [] var add := func(kind: String, t: RollTable, eid: String, text: String) -> void: @@ -309,14 +313,20 @@ static func static_checks(b: TowerBoard) -> Array[Dictionary]: var t: RollTable = null var eid := "" var text := str(item) + var lkind := "pipes" + var level := "" if item is Dictionary: var d: Dictionary = item t = b.get_table(str(d.get("table_id", d.get("table", "")))) eid = str(d.get("entry_id", d.get("entry", ""))) text = str(d.get("text", d.get("message", d.get("problem", text)))) + lkind = str(d.get("kind", "pipes")) + level = str(d.get("level", "")) if t == null: t = RollTable.new("", "") - add.call("pipes", t, eid, text) + add.call(lkind, t, eid, text) + if level != "": + out.back()["level"] = level return out diff --git a/core/builder.gd b/core/builder.gd new file mode 100644 index 0000000..8fcae62 --- /dev/null +++ b/core/builder.gd @@ -0,0 +1,487 @@ +class_name Builder +extends RefCounted +## Structured models for effect statements and conditions that round-trip +## with the stored rule text (docs/PLAIN.md §2), plus the list of values a +## board uses (for value pickers). +## +## The stored format stays the text (docs/LOGIC.md). A model is only a view of +## it: parse_*() give {"ok": false} for anything a row-based builder can't +## show, and the UI then shows that rule as text. +## +## Effect model: {"ok": true, "op", "var", "amount"} +## op "set" (=), "add" (+=), "subtract" (-=), "multiply" (*=), +## "divide" (/=), "reset", "append" (+= "text"), "remove" (-= "text") +## var "@name", a chain name ("name"), "@prefix_*" (reset only) or +## "@[expr]" (indirect, e.g. "@[option]") +## amount String: the expression as written ("1", "2d6", "\"Aslan\"", +## "max(@x, 0)"); for append/remove the item text without quotes +## ("Psionic"); "" for reset +## Condition model: {"ok": true, "join": "and" | "or", "clauses": [{"var", +## "cmp", "value"}]} +## var "@name", "@[expr]" or a chain name ("option_value", "tier") +## cmp "eq" "ne" "ge" "le" "gt" "lt" "has" (list contains) "set" +## (truthy) "unset" (not truthy) +## value String token as written: a number ("8", "-2", "2.5"), quoted +## text ("\"Aslan\""), "@name", a chain name, "true"/"false"; +## "" for set/unset +## An empty condition is {"ok": true, "join": "and", "clauses": []}. +## Round trips are exact on models: parse_x(x_text(m)) == m for any model a +## parse gave. Text -> model -> text may normalize spacing and "==" to "=". + +const EFFECT_OPS := {"set": "=", "add": "+=", "subtract": "-=", "multiply": "*=", "divide": "/="} +const CMPS := {"eq": "=", "ne": "!=", "ge": ">=", "le": "<=", "gt": ">", "lt": "<"} +const _CMP_OF := {"=": "eq", "==": "eq", "!=": "ne", ">=": "ge", "<=": "le", ">": "gt", "<": "lt"} +## Chain values the engine sets, with what sets them. +const CHAIN_NAMES := ["answer", "option", "i", "total", "nat", "effect"] + +static var _dice_re: RegEx = null +static var _num_re: RegEx = null + + +# ---------------------------------------------------------------- effects + +## Parses one effect statement into a model, or {"ok": false, "error"} when +## it doesn't fit (a parse error, or an amount that isn't an expression). +static func parse_effect(stmt: String) -> Dictionary: + var src := stmt.strip_edges() + if src == "": + return {"ok": false, "error": "Empty statement"} + var st := Effects.parse_statement(src) + if st.has("error"): + return {"ok": false, "error": str(st["error"])} + var target := str(st["target"]) + if st.has("target_expr"): + target = "@[%s]" % str(st["target_expr"]).strip_edges() + if Expr.check(str(st["target_expr"])) != "": + return {"ok": false, "error": Expr.check(str(st["target_expr"]))} + var op := str(st["op"]) + if op == "reset": + return {"ok": true, "op": "reset", "var": target, "amount": ""} + var amount := str(st["expr"]).strip_edges() + var err := Expr.check(amount) + if err != "": + return {"ok": false, "error": err} + var name := "" + match op: + "=": + name = "set" + "+=": + name = "add" + "-=": + name = "subtract" + "*=": + name = "multiply" + "/=": + name = "divide" + if (op == "+=" or op == "-=") and is_text_literal(amount): + return {"ok": true, "op": "append" if op == "+=" else "remove", "var": target, "amount": unquote(amount)} + return {"ok": true, "op": name, "var": target, "amount": amount} + + +## The statement for a model ("" when the model isn't valid). +static func effect_text(m: Dictionary) -> String: + var op := str(m.get("op", "")) + var v := str(m.get("var", "")).strip_edges() + var amount := str(m.get("amount", "")).strip_edges() if m.get("amount") != null else "" + if v == "": + return "" + match op: + "reset": + return "reset " + v + "append": + return "%s += %s" % [v, quote(str(m.get("amount", "")))] + "remove": + return "%s -= %s" % [v, quote(str(m.get("amount", "")))] + if not EFFECT_OPS.has(op) or amount == "": + return "" + return "%s %s %s" % [v, EFFECT_OPS[op], amount] + + +## Every statement of an effects field as a model (ok or not), in order. +static func parse_effects(text: String) -> Array[Dictionary]: + var out: Array[Dictionary] = [] + for s in Effects.split(text): + var m := parse_effect(s) + m["src"] = s + out.append(m) + return out + + +# ---------------------------------------------------------------- conditions + +## Parses a condition into a model, or {"ok": false, "error"} for mixed +## and/or, parentheses, dice, function calls other than has(), or anything +## else that isn't a list of simple comparisons. +static func parse_condition(expr: String) -> Dictionary: + var src := expr.strip_edges() + if src == "": + return {"ok": true, "join": "and", "clauses": []} + var toks := tokens(src) + if toks.is_empty(): + return {"ok": false, "error": "Can't read this as simple comparisons"} + var groups: Array = [[]] + var join := "" + for tk: Dictionary in toks: + if tk["t"] == "kw" and (tk["s"] == "and" or tk["s"] == "or"): + if join != "" and join != tk["s"]: + return {"ok": false, "error": "Mixes and with or"} + join = tk["s"] + groups.append([]) + else: + (groups.back() as Array).append(tk) + var clauses: Array = [] + for g: Array in groups: + var c := _clause(g) + if c.is_empty(): + return {"ok": false, "error": "Can't read this as simple comparisons"} + clauses.append(c) + return {"ok": true, "join": join if join != "" else "and", "clauses": clauses} + + +## The condition text for a model ("" for no clauses or an invalid model). +static func condition_text(m: Dictionary) -> String: + var parts := PackedStringArray() + for c: Variant in m.get("clauses", []): + if not (c is Dictionary): + return "" + var t := clause_text(c) + if t == "": + return "" + parts.append(t) + var join := str(m.get("join", "and")) + if join != "and" and join != "or": + join = "and" + return (" %s " % join).join(parts) + + +## One clause as text: "@str >= 8", "has(@traits, \"Psionic\")", "@x", +## "not @x". "" when it isn't valid. +static func clause_text(c: Dictionary) -> String: + var v := str(c.get("var", "")).strip_edges() + var cmp := str(c.get("cmp", "")) + var value := str(c.get("value", "")).strip_edges() if c.get("value") != null else "" + if v == "": + return "" + match cmp: + "set": + return v + "unset": + return "not " + v + "has": + return "has(%s, %s)" % [v, value] if value != "" else "" + if not CMPS.has(cmp) or value == "": + return "" + return "%s %s %s" % [v, CMPS[cmp], value] + + +static func _clause(g: Array) -> Dictionary: + var n := g.size() + if n == 1 and _is_subject(g[0]): + return {"var": g[0]["s"], "cmp": "set", "value": ""} + if n == 2 and g[0]["t"] == "kw" and g[0]["s"] == "not" and _is_subject(g[1]): + return {"var": g[1]["s"], "cmp": "unset", "value": ""} + if n == 3 and _is_subject(g[0]) and g[1]["t"] == "op" and _CMP_OF.has(g[1]["s"]): + var val := _value(g, 2) + if val != "": + return {"var": g[0]["s"], "cmp": _CMP_OF[g[1]["s"]], "value": val} + if n == 4 and _is_subject(g[0]) and g[1]["t"] == "op" and _CMP_OF.has(g[1]["s"]) and g[2]["s"] == "-" and g[3]["t"] == "num": + return {"var": g[0]["s"], "cmp": _CMP_OF[g[1]["s"]], "value": "-" + str(g[3]["s"])} + # has(@list, value) + if (n == 6 or n == 7) and g[0]["t"] == "name" and g[0]["s"] == "has" and g[1]["s"] == "(" and _is_subject(g[2]) \ + and g[3]["s"] == "," and g[n - 1]["s"] == ")": + var hv := "" + if n == 6: + hv = _value(g, 4) + elif g[4]["s"] == "-" and g[5]["t"] == "num": + hv = "-" + str(g[5]["s"]) + if hv != "": + return {"var": g[2]["s"], "cmp": "has", "value": hv} + return {} + + +static func _is_subject(tk: Dictionary) -> bool: + return tk["t"] == "var" or (tk["t"] == "name" and not ["has", "true", "false"].has(tk["s"])) + + +static func _value(g: Array, k: int) -> String: + var tk: Dictionary = g[k] + match str(tk["t"]): + "num", "str", "var": + return tk["s"] + "name": + return tk["s"] + return "" + + +# ---------------------------------------------------------------- tokens + +## Splits a rule into tokens: Array of {"t": type, "s": text}, or [] when it +## can't (an unclosed quote or bracket, a stray character, "2x"). Types: +## "var" (@name, lowercased, or @[expr] as written), "prefix" (@name_*), +## "name" (a chain name or function), "num", "dice" (2d6, D3, 2D), "str" (a +## quoted text, quotes included), "op" (+ - * / % ( ) , = == != < <= > >=), +## "kw" (and, or, not; && || ! are read as these). +static func tokens(src: String) -> Array: + var out: Array = [] + var i := 0 + var n := src.length() + while i < n: + var c := src[i] + if c == " " or c == "\t" or c == "\n": + i += 1 + continue + if c == "\"" or c == "'": + var j := i + 1 + while j < n and src[j] != c: + if src[j] == "\\": + j += 1 + j += 1 + if j >= n: + return [] + out.append({"t": "str", "s": src.substr(i, j - i + 1)}) + i = j + 1 + continue + if c == "@": + if i + 1 < n and src[i + 1] == "[": + var close := Expr.bracket_end(src, i + 1) + if close < 0: + return [] + out.append({"t": "var", "s": "@[%s]" % src.substr(i + 2, close - i - 2).strip_edges()}) + i = close + 1 + continue + var j2 := i + 1 + while j2 < n and _is_word(src[j2]): + j2 += 1 + var nm := src.substr(i + 1, j2 - i - 1).to_lower() + if nm == "" or nm[0].is_valid_int(): + return [] + if j2 < n and src[j2] == "*": + out.append({"t": "prefix", "s": "@%s*" % nm}) + i = j2 + 1 + else: + out.append({"t": "var", "s": "@" + nm}) + i = j2 + continue + if _is_word(c): + var j3 := i + while j3 < n and (_is_word(src[j3]) or (src[j3] == "." and j3 + 1 < n and src[j3 + 1].is_valid_int())): + j3 += 1 + var w := src.substr(i, j3 - i) + i = j3 + if _num().search(w) != null: + out.append({"t": "num", "s": w}) + elif _dice().search(w) != null and w.length() > 1: + out.append({"t": "dice", "s": w}) + elif w[0].is_valid_int(): + return [] + elif ["and", "or", "not"].has(w.to_lower()) and w == w.to_lower(): + out.append({"t": "kw", "s": w}) + else: + out.append({"t": "name", "s": w}) + continue + var two := src.substr(i, 2) + if two in [">=", "<=", "!=", "=="]: + out.append({"t": "op", "s": two}) + i += 2 + continue + if two == "&&" or two == "||": + out.append({"t": "kw", "s": "and" if two == "&&" else "or"}) + i += 2 + continue + if c == "!": + out.append({"t": "kw", "s": "not"}) + i += 1 + continue + if c in ["+", "-", "*", "/", "%", "(", ")", ",", "=", "<", ">"]: + out.append({"t": "op", "s": c}) + i += 1 + continue + return [] + return out + + +static func _is_word(c: String) -> bool: + return c == "_" or c.is_valid_int() or (c.to_lower() != c.to_upper()) + + +static func _dice() -> RegEx: + if _dice_re == null: + _dice_re = RegEx.create_from_string("^(\\d*)[dD](\\d*)$") + return _dice_re + + +static func _num() -> RegEx: + if _num_re == null: + _num_re = RegEx.create_from_string("^\\d+(\\.\\d+)?$") + return _num_re + + +## [count, sides] of a dice token ("2d6" -> [2, 6], "D3" -> [1, 3], "2D" -> +## [2, 6]), or []. +static func dice_parts(word: String) -> Array: + var m := _dice().search(word) + if m == null or word.length() < 2: + return [] + var a := m.get_string(1) + var b := m.get_string(2) + return [int(a) if a != "" else 1, int(b) if b != "" else 6] + + +## True when `s` is one quoted text literal ("Aslan" or 'Aslan'). +static func is_text_literal(s: String) -> bool: + var t := tokens(s.strip_edges()) + return t.size() == 1 and t[0]["t"] == "str" + + +## A quoted literal's text: "\"Aslan\"" -> "Aslan" (\" and \\ unescaped). +## Anything else comes back as it is. +static func unquote(s: String) -> String: + s = s.strip_edges() + if s.length() < 2 or not ((s.begins_with("\"") and s.ends_with("\"")) or (s.begins_with("'") and s.ends_with("'"))): + return s + var inner := s.substr(1, s.length() - 2) + var out := "" + var k := 0 + while k < inner.length(): + var ch := inner[k] + if ch == "\\" and k + 1 < inner.length(): + k += 1 + ch = inner[k] + out += ch + k += 1 + return out + + +## Text as a double-quoted literal, escaping \ and ". +static func quote(s: String) -> String: + return "\"%s\"" % s.replace("\\", "\\\\").replace("\"", "\\\"") + + +# ---------------------------------------------------------------- values + +## Every value the board uses, for value pickers: Array of {"name", "label", +## "kind", "source"} with optional extras, variable cards first, then +## collections, then the rest in board order, then chain names. One item per +## name (the first source wins). +## name "@luck" (board value), "@skill_*" (a collection), "tier" (chain) +## label Describe.label(name, board) +## kind "number", "text", "list" or "collection" +## source "variable" (a variable card), "collection", "effect" (an effect +## target), "save_as" (a pipe's or choice's save_as, or +## [[Table -> name]]), "input" (a card input), "read" (only read by +## a rule), "chain" (answer, option, i, total, nat, effect) +## table_id the card that declares, sets or reads it first +## collection on members of a collection: its pattern ("@skill_*") +## Chain names are listed only when the board has a card that sets them +## (answer: number/text choices; option: options from variables; i: loops; +## nat: roll tables and checks; total/effect: checks). +static func known_values(board: TowerBoard) -> Array[Dictionary]: + var out: Array[Dictionary] = [] + if board == null: + return out + var seen := {} + var stems: Array = [] # [stem, pattern] + var add := func(name: String, kind: String, source: String, tid: String) -> void: + if name == "" or seen.has(name): + return + seen[name] = true + var item := {"name": name, "label": Describe.label(name, board), "kind": kind, "source": source, "table_id": tid} + if name.begins_with("@") and not name.ends_with("*"): + for sp: Array in stems: + if name.begins_with("@" + str(sp[0]) + "_") and name.length() > str(sp[0]).length() + 2: + item["collection"] = sp[1] + break + out.append(item) + for t in board.tables: + if t.kind == RollTable.KIND_VARIABLE and t.var_name != "" and not t.is_collection(): + add.call("@" + t.var_name, t.var_type, "variable", t.id) + for t in board.tables: + if t.is_collection() and t.var_name != "": + stems.append([t.var_name, "@%s_*" % t.var_name]) + stems.sort_custom(func(a: Array, b: Array) -> bool: return str(a[0]).length() > str(b[0]).length()) + for t in board.tables: + if t.is_collection() and t.var_name != "": + add.call("@%s_*" % t.var_name, "collection", "collection", t.id) + var reads: Array = [] + var chain := {} + for t in board.tables: + match t.kind: + RollTable.KIND_CHOICE: + if t.choice != "pick": + chain["answer"] = true + if t.save_as != "": + add.call(_value_name(t.save_as), "number" if t.choice == "number" else "text", "save_as", t.id) + else: + if t.is_dynamic(): + chain["option"] = true + if t.save_as != "": + add.call(_value_name(t.save_as), "text", "save_as", t.id) + reads.append([t.options_where, t.id]) + reads.append([t.min_expr, t.id]) + reads.append([t.max_expr, t.id]) + RollTable.KIND_LOOP: + chain["i"] = true + reads.append([t.loop_expr, t.id]) + RollTable.KIND_CHECK: + chain["nat"] = true + chain["total"] = true + chain["effect"] = true + reads.append([t.check_dice, t.id]) + reads.append([t.check_mod, t.id]) + reads.append([t.check_target, t.id]) + RollTable.KIND_ROLL: + chain["nat"] = true + if t.is_expr_dice(): + reads.append([t.dice, t.id]) + for inp: Dictionary in t.inputs: + add.call(str(inp.get("name", "")), _kind_of_expr(str(inp.get("default", ""))), "input", t.id) + for e in t.entries: + for m in parse_effects(e.effects): + if not m["ok"]: + continue + var v := str(m["var"]) + if v.begins_with("@[") or v.ends_with("*"): + continue + var k := "number" + match str(m["op"]): + "append", "remove": + k = "list" + "set": + k = "text" if is_text_literal(str(m["amount"])) else "number" + add.call(v, k, "effect", t.id) + if m["op"] != "reset": + reads.append([str(m["amount"]), t.id]) + for p in e.pipes: + var sv := e.save_for(p) + if sv != "": + add.call(_value_name(sv), "text", "save_as", t.id) + reads.append([e.when_for(p), t.id]) + reads.append([e.count_expr(p), t.id]) + var w := e.with_for(p) + for nm: String in w: + reads.append([str(w[nm]), t.id]) + for ref in JsonIO.find_refs(e.text): + if str(ref["var"]) != "": + add.call(_value_name(str(ref["var"])), "text", "save_as", t.id) + reads.append([e.when, t.id]) + reads.append([e.show_if, t.id]) + for r: Array in reads: + var src := str(r[0]).strip_edges() + if src == "" or not src.contains("@"): + continue + for tk: Dictionary in tokens(src): + if tk["t"] == "var" and not str(tk["s"]).begins_with("@["): + add.call(str(tk["s"]), "number", "read", str(r[1])) + for nm: String in CHAIN_NAMES: + if chain.has(nm): + add.call(nm, "text" if nm == "option" else "number", "chain", "") + return out + + +static func _value_name(s: String) -> String: + var t := s.strip_edges() + return "@" + t.substr(1).to_lower() if t.begins_with("@") else t + + +static func _kind_of_expr(src: String) -> String: + return "text" if is_text_literal(src) else "number" diff --git a/core/builder.gd.uid b/core/builder.gd.uid new file mode 100644 index 0000000..726955f --- /dev/null +++ b/core/builder.gd.uid @@ -0,0 +1 @@ +uid://bsyjk1ayxdxej diff --git a/core/describe.gd b/core/describe.gd new file mode 100644 index 0000000..42e8f5a --- /dev/null +++ b/core/describe.gd @@ -0,0 +1,674 @@ +class_name Describe +extends RefCounted +## Rules in plain words (docs/PLAIN.md §1): pure functions that turn stored +## rule text into short phrases, using value labels (§3). Anything they can't +## read comes back as the original text; they never fail and keep phrases +## short (MAX_LEN characters, else the original text or a cut with "…"). +## +## Labels: a value's label is its variable card's name, else the collection +## it belongs to names it by the rest of its name ("@skill_gun_combat" in the +## Skills collection -> "Gun Combat"), else a pretty form of its name ("soc" +## -> "Soc"). Card inputs are labelled by their declared label. `board` may be +## null everywhere (pretty names only). + +## Longest phrase before falling back to the original text (or a cut). +const MAX_LEN := 90 +const MINUS := "−" +const _CHAIN_LABELS := {"answer": "Answer", "i": "Pass", "nat": "Natural roll", "total": "Total", + "effect": "Effect", "option": "Chosen option", "option_label": "Chosen option", + "option_value": "Chosen value"} +const _OPS := {"*": "×", "/": "÷", "-": MINUS, "==": "=", "!=": "≠", ">=": "≥", "<=": "≤"} + + +# ---------------------------------------------------------------- labels + +## The label of a value: "@luck", "@skill_pilot", "@skill_*" (a collection +## or prefix: "Skills", or "Skill values" without a collection card), "@[…]" +## ("Chosen value"), or a chain name ("answer" -> "Answer", an input's label). +static func label(name: String, board: TowerBoard) -> String: + return _label(name, _labels(board)) + + +## Label table for a board: {"vars": {name: label}, "stems": [[stem, label]] +## longest first, "inputs": {name: label}}. +static func _labels(board: TowerBoard) -> Dictionary: + var vars := {} + var stems: Array = [] + var inputs := {} + if board != null: + for t in board.tables: + if t.kind == RollTable.KIND_VARIABLE and t.var_name != "": + var lab := Formatter.strip_tags(t.name).strip_edges() + if t.var_type == RollTable.VAR_COLLECTION: + stems.append([t.var_name, lab if lab != "" else RollContext.pretty_name(t.var_name)]) + elif lab != "" and not vars.has(t.var_name): + vars[t.var_name] = lab + for inp: Dictionary in t.inputs: + var il := str(inp.get("label", "")).strip_edges() + if il != "" and not inputs.has(str(inp.get("name", ""))): + inputs[str(inp.get("name", ""))] = il + stems.sort_custom(func(a: Array, b: Array) -> bool: return str(a[0]).length() > str(b[0]).length()) + return {"vars": vars, "stems": stems, "inputs": inputs} + + +static func _label(name: String, L: Dictionary) -> String: + var n := name.strip_edges() + if n.begins_with("@["): + return "Chosen value" + if n.begins_with("@"): + n = n.substr(1).to_lower() + if n.ends_with("*"): + var stem := n.trim_suffix("*").trim_suffix("_") + for sp: Array in L["stems"]: + if sp[0] == stem: + return sp[1] + return "%s values" % RollContext.pretty_name(stem) + if L["vars"].has(n): + return L["vars"][n] + for sp: Array in L["stems"]: + var pre := str(sp[0]) + "_" + if n.begins_with(pre) and n.length() > pre.length(): + return RollContext.pretty_name(n.substr(pre.length())) + return RollContext.pretty_name(n) + if L["inputs"].has(n): + return L["inputs"][n] + if _CHAIN_LABELS.has(n): + return _CHAIN_LABELS[n] + return RollContext.pretty_name(n) + + +## The collection a value belongs to ({"stem", "label"}) or {}. +static func _collection_of(name: String, L: Dictionary) -> Dictionary: + var n := name.strip_edges().trim_prefix("@").to_lower() + for sp: Array in L["stems"]: + var pre := str(sp[0]) + "_" + if n.begins_with(pre): + return {"stem": sp[0], "label": sp[1]} + return {} + + +# ---------------------------------------------------------------- effects + +## One effect statement in plain words: "@luck -= 1" -> "Luck −1", +## "@town = \"Millbrook\"" -> "Town = Millbrook", "reset @skill_*" -> "Clear +## all Skills", "@traits += \"Psionic\"" -> "Add Psionic to Traits", +## "@[option] += 1" -> "Chosen skill +1" when `table` is a pick card taking +## options from a collection (else "Chosen value +1"). +static func effect(stmt: String, board: TowerBoard, table: RollTable = null) -> String: + return _effect(stmt, _labels(board), table) + + +## One phrase per statement of an effects field. +static func effects(text: String, board: TowerBoard, table: RollTable = null) -> Array[String]: + var L := _labels(board) + var out: Array[String] = [] + for s in Effects.split(text): + out.append(_effect(s, L, table)) + return out + + +static func _effect(stmt: String, L: Dictionary, table: RollTable) -> String: + var src := stmt.strip_edges() + var m := Builder.parse_effect(src) + if not m["ok"]: + return src + var v := str(m["var"]) + var subj := _chosen(table, L) if v.begins_with("@[") else _label(v, L) + var amount := str(m["amount"]) + var out := "" + match str(m["op"]): + "reset": + if v.ends_with("*"): + out = "Clear all " + _label(v, L) + elif L["vars"].has(v.trim_prefix("@")): + out = "Reset " + subj + else: + out = "Clear " + subj + "set": + out = "%s = %s" % [subj, _expr(amount, L)] + "add", "subtract": + var sub: bool = m["op"] == "subtract" + if amount.is_valid_float() and not amount.to_lower().contains("e") and not amount.to_lower().contains("n"): + var x: Variant = Expr.to_value(amount) + if x < 0: + sub = not sub + x = -x + out = "%s %s%s" % [subj, MINUS if sub else "+", Expr.format_value(x)] + else: + out = "%s %s %s" % [subj, MINUS if sub else "+", _expr(amount, L)] + "multiply": + out = "%s ×%s" % [subj, _compact(amount, L)] + "divide": + out = "%s ÷%s" % [subj, _compact(amount, L)] + "append": + out = "Add %s to %s" % [amount, subj] + "remove": + out = "Remove %s from %s" % [amount, subj] + return _short(out, src) + + +static func _compact(amount: String, L: Dictionary) -> String: + var t := Builder.tokens(amount) + var e := _expr(amount, L) + return e if t.size() == 1 else " " + e + + +## "Chosen skill" on a pick card whose options come from a collection, else +## "Chosen value". +static func _chosen(table: RollTable, L: Dictionary) -> String: + if table != null and table.is_dynamic(): + var p := RollTable.parse_options_from(table.options_from) + if str(p["kind"]) == "prefix": + var stem := str(p["name"]).trim_suffix("_") + for sp: Array in L["stems"]: + if sp[0] == stem: + return "Chosen " + _singular(str(sp[1]).to_lower()) + return "Chosen value" + + +static func _singular(s: String) -> String: + if s.length() > 3 and s.ends_with("s") and not s.ends_with("ss"): + return s.substr(0, s.length() - 1) + return s + + +# ---------------------------------------------------------------- conditions + +## A condition in plain words: "@str >= 8" -> "Strength is 8 or more", +## "@x = 0 and @soc >= 9" -> "X is 0 and Social Standing is 9 or more", +## "has(@traits, \"Psionic\")" -> "Traits include Psionic". "" for an empty +## condition; the original text for anything Builder.parse_condition() can't +## read. +static func condition(expr: String, board: TowerBoard) -> String: + return _condition(expr, _labels(board)) + + +static func _condition(expr: String, L: Dictionary) -> String: + var src := expr.strip_edges() + var m := Builder.parse_condition(src) + if not m["ok"]: + return src + var parts := PackedStringArray() + for c: Dictionary in m["clauses"]: + parts.append(_clause(c, L)) + return _short((" %s " % m["join"]).join(parts), src) + + +static func _clause(c: Dictionary, L: Dictionary) -> String: + var subj := _label(str(c["var"]), L) + var cmp := str(c["cmp"]) + match cmp: + "set": + return subj + " is set" + "unset": + return subj + " is not set" + "has": + return "%s include %s" % [subj, _value(str(c["value"]), L)] + return "%s %s" % [subj, _tail(cmp, str(c["value"]), L)] + + +## The comparison after a value name: "is 8 or more", "is at most 3", "is +## Aslan", "is not 0", "is more than 2", "is less than 2". +static func _tail(cmp: String, value: String, L: Dictionary) -> String: + var v := _value(value, L) + var num := Expr.is_number(value) or (value.begins_with("-") and Expr.is_number(value.substr(1))) + match cmp: + "eq": + return "is " + v + "ne": + return "is not " + v + "ge": + return ("is %s or more" % v) if num else "is at least " + v + "le": + return "is at most " + v + "gt": + return "is more than " + v + "lt": + return "is less than " + v + "has": + return "includes " + v + "set": + return "is set" + "unset": + return "is not set" + return "%s %s" % [cmp, v] + + +## A value token in words: numbers as they are, quoted text without quotes, +## @names and chain names by label, true/false as yes/no. +static func _value(tok: String, L: Dictionary) -> String: + var s := tok.strip_edges() + if s == "true": + return "yes" + if s == "false": + return "no" + if Builder.is_text_literal(s): + return Builder.unquote(s) + if s.begins_with("-") and Expr.is_number(s.substr(1)): + return MINUS + s.substr(1) + if Expr.is_number(s): + return s + if s.begins_with("@") or Builder._is_word(s.substr(0, 1)): + return _label(s, L) + return s + + +# ---------------------------------------------------------------- dice + +## A dice or count expression in plain words: "2d6 + dm(@str)" -> "2D + +## Strength modifier", "1d6 + tier" -> "1D + Tier", "@terms" -> "Terms". +## d6 dice read as "ND"; other dice as "dN" / "NdM". Text that can't be read +## comes back as it is. +static func dice(expr: String, board: TowerBoard) -> String: + return _expr(expr, _labels(board)) + + +static func _expr(expr: String, L: Dictionary) -> String: + var src := expr.strip_edges() + if src == "": + return "" + var toks := Builder.tokens(src) + if toks.is_empty(): + return src + var pieces: Array = [] # [kind, text]; kinds: val fn op neg ( ) , + var k := 0 + while k < toks.size(): + var tk: Dictionary = toks[k] + var t := str(tk["t"]) + var s := str(tk["s"]) + var prevk := str(pieces.back()[0]) if not pieces.is_empty() else "" + # dm(x) with one value inside: "X modifier". + if t == "name" and s == "dm" and k + 3 < toks.size() and toks[k + 1]["s"] == "(" and toks[k + 3]["s"] == ")" \ + and ["var", "name", "num"].has(str(toks[k + 2]["t"])): + pieces.append(["val", _value(str(toks[k + 2]["s"]), L) + " modifier"]) + k += 4 + continue + k += 1 + match t: + "dice": + var dp := Builder.dice_parts(s) + if int(dp[1]) == 6: + pieces.append(["val", "%dD" % int(dp[0])]) + elif int(dp[0]) == 1: + pieces.append(["val", "d%d" % int(dp[1])]) + else: + pieces.append(["val", "%dd%d" % [int(dp[0]), int(dp[1])]]) + "var", "prefix": + pieces.append(["val", _label(s, L)]) + "name": + if k < toks.size() and toks[k]["s"] == "(": + pieces.append(["fn", s]) + else: + pieces.append(["val", _value(s, L)]) + "num": + pieces.append(["val", s]) + "str": + pieces.append(["val", Builder.unquote(s)]) + "kw": + pieces.append(["op", s]) + _: + if s == "(" or s == ")" or s == ",": + pieces.append([s, s]) + elif s == "-" and (prevk == "" or prevk == "op" or prevk == "(" or prevk == "," or prevk == "neg"): + pieces.append(["neg", MINUS]) + else: + pieces.append(["op", _OPS.get(s, s)]) + var out := "" + var prev := "" + for pc: Array in pieces: + var kind := str(pc[0]) + var space := false + match kind: + "op": + space = out != "" + "val", "fn": + space = prev in ["op", ",", "val", ")"] + "(", "neg": + space = prev in ["op", ","] + if space: + out += " " + out += str(pc[1]) + prev = kind + return _short(out, src) + + +# ---------------------------------------------------------------- cards and pipes + +## A pick card's dynamic options source: "your Skills, level 1 or more", +## "your Contacts", "your Skill values, where Chosen option is not Pilot". +## "" for a card without options_from; the pattern as written when it's bad. +static func options(table: RollTable, board: TowerBoard) -> String: + if table == null or table.options_from.strip_edges() == "": + return "" + var L := _labels(board) + var p := RollTable.parse_options_from(table.options_from) + var s := "" + match str(p["kind"]): + "prefix": + s = "your " + _label("@%s*" % p["name"], L) + "list": + s = "your " + _label("@" + str(p["name"]), L) + _: + return table.options_from.strip_edges() + var w := _where(table.options_where, L) + if w != "": + s += ", " + w + return _short(s, table.options_description()) + + +## The options_where filter as a short tail: "level 1 or more" for one +## comparison on option_value, else "where "; "" when empty. +static func _where(where: String, L: Dictionary) -> String: + var src := where.strip_edges() + if src == "": + return "" + var m := Builder.parse_condition(src) + if m["ok"] and (m["clauses"] as Array).size() == 1: + var c: Dictionary = m["clauses"][0] + if str(c["var"]) == "option_value" and ["eq", "ge", "le", "gt", "lt"].has(str(c["cmp"])): + var tail := _tail(str(c["cmp"]), str(c["value"]), L).trim_prefix("is ") + return "level " + tail + return "where " + _condition(src, L) + + +## A pipe's label in plain words, parts joined with " · ": its inputs ("Tier +## 3"), "only if " or "otherwise", the count ("×2", "×Terms") and +## "saves ". "" for a plain pipe. +static func pipe(entry: TableEntry, target_id: String, board: TowerBoard) -> String: + if entry == null: + return "" + var L := _labels(board) + var parts := PackedStringArray() + var w := entry.with_for(target_id) + for nm: String in w: + parts.append("%s %s" % [_label(nm, L), _expr(str(w[nm]), L)]) + var cond := entry.when_for(target_id) + if cond != "": + parts.append("only if " + _condition(cond, L)) + elif entry.is_otherwise(target_id): + parts.append("otherwise") + var ce := entry.count_expr(target_id) + if ce != "": + parts.append("×" + _expr(ce, L)) + elif entry.count_for(target_id) != 1: + parts.append("×%d" % entry.count_for(target_id)) + var sv := entry.save_for(target_id) + if sv != "": + parts.append("saves " + _label(sv, L)) + return " · ".join(parts) + + +## A check card: "Roll 2D + Strength modifier, need 8 or more" ("need 5 or +## less" for a roll-under check). "" for other kinds. +static func check(table: RollTable, board: TowerBoard) -> String: + if table == null or table.kind != RollTable.KIND_CHECK: + return "" + var L := _labels(board) + var roll := _expr(table.check_dice, L) + var mod := table.check_mod.strip_edges() + if mod != "": + var mt := Builder.tokens(mod) + if not mt.is_empty() and mt[0]["s"] == "-": + roll += " %s %s" % [MINUS, _expr(mod.substr(1), L)] + else: + roll += " + " + _expr(mod, L) + var target := _expr(table.check_target, L) + var num := Expr.is_number(table.check_target.strip_edges()) + var need := "" + if table.check_cmp == "le": + need = ("%s or less" % target) if num else "at most " + target + else: + need = ("%s or more" % target) if num else "at least " + target + return _short("Roll %s, need %s" % [roll, need], "Roll %s %s vs %s" % [table.check_dice, mod, table.check_target]) + + +# ---------------------------------------------------------------- why + +## One trace fact (Roller node/step "why") as a sentence. Plain mode uses +## labels and words ("Skipped Tier 3 because Luck was 1 (needs 2 or more)"); +## text mode (plain = false) shows the rules as written ("Skipped tier3: when +## @luck >= 2 was false (@luck = 1)"). Unknown facts give a short dump. +static func why(fact: Dictionary, board: TowerBoard, plain: bool = true) -> String: + if fact == null: + return "" + var L := _labels(board) + var s := "" + match str(fact.get("type", "")): + "roll": + s = _why_roll(fact, plain) + "check": + s = _why_check(fact, L, plain) + "when": + s = _why_when(fact, board, L, plain) + "otherwise": + var to := _table(str(fact.get("to", "")), board, plain) + if bool(fact.get("result", false)): + s = "Took %s because no condition was true" % to if plain else "%s: otherwise, ran (no condition was true)" % to + else: + s = "Skipped %s because a condition was true" % to if plain else "%s: otherwise, skipped" % to + "case": + s = _why_case(fact, L, plain) + "show_if": + var h := int(fact.get("hidden", 0)) + var parts := PackedStringArray() + if h > 0: + parts.append(("%d option hidden by its condition" if h == 1 else "%d options hidden by their conditions") % h) + if bool(fact.get("chosen_hidden", false)): + parts.append("the options from values were hidden") + s = ", and ".join(parts) + if s != "": + s = s.substr(0, 1).to_upper() + s.substr(1) + if not plain: + s = "show_if hid %d option(s)%s" % [h, ", and the Chosen entry" if bool(fact.get("chosen_hidden", false)) else ""] + "options_where": + var kept := int(fact.get("kept", 0)) + var total := int(fact.get("total", 0)) + if plain: + var from := str(fact.get("from", "")) + var p := RollTable.parse_options_from(from) + var what := _label("@%s*" % p["name"], L) if str(p["kind"]) == "prefix" else (_label("@" + str(p["name"]), L) if str(p["kind"]) == "list" else "options") + s = "Offered %d of %d %s (%s)" % [kept, total, what, _where(str(fact.get("expr", "")), L)] + else: + s = "options_where %s kept %d of %d" % [fact.get("expr", ""), kept, total] + "effect": + s = _why_effect(fact, L, plain) + "input": + var nm := str(fact.get("name", "")) + var val := Expr.format_value(fact.get("value")) + var from_pipe := str(fact.get("from", "")) == "pipe" + if plain: + s = "%s was %s (%s)" % [_label(nm, L), val, "from the pipe" if from_pipe else "default"] + else: + s = "input %s = %s (%s)" % [nm, val, "with" if from_pipe else "default"] + _: + s = JSON.stringify(fact) + if s.length() > MAX_LEN * 2: + s = s.substr(0, MAX_LEN * 2 - 1) + "…" + return s + + +static func _table(id: String, board: TowerBoard, plain: bool) -> String: + if not plain or board == null: + return id + var t := board.get_table(id) + if t == null: + return id + var n := Formatter.strip_tags(t.name).strip_edges() + return n if n != "" else id + + +## "3 + 4 = 7" (or "5" for one die). +static func _faces(faces: Variant) -> String: + if not (faces is Array) or (faces as Array).is_empty(): + return "" + var parts := PackedStringArray() + var sum := 0.0 + for f: Variant in faces: + parts.append(Expr.format_value(f)) + sum += float(Expr.to_value(f)) if Expr.is_number(f) else 0.0 + if parts.size() == 1: + return parts[0] + return "%s = %s" % [" + ".join(parts), Expr.format_value(sum)] + + +static func _nonzero(v: Variant) -> bool: + var n: Variant = Expr.to_value(v) + return Expr.is_number(n) and n != 0 + + +static func _signed(v: Variant) -> String: + var n: Variant = Expr.to_value(v) + if not Expr.is_number(n): + return str(v) + return ("+" + Expr.format_value(n)) if n >= 0 else (MINUS + Expr.format_value(-n)) + + +static func _why_roll(f: Dictionary, plain: bool) -> String: + var total := Expr.format_value(f.get("total")) + match str(f.get("pick", "dice")): + "weighted": + return "Rolled %s on %s" % [total, f.get("dice", "")] if plain else "roll %s: %s" % [f.get("dice", ""), total] + "card": + return "Drew card %s" % total if plain else "draw: card %s" % total + var faces := _faces(f.get("faces")) + if not plain: + var t := "roll %s: %s" % [f.get("dice", ""), faces if faces != "" else total] + if f.has("mod") and _nonzero(f["mod"]): + t += " %s = %s" % [_signed(f["mod"]).replace(MINUS, "-"), total] + return t + if faces == "": + return "Worked out %s" % total + var s := "Rolled " + faces + if f.has("mod") and _nonzero(f["mod"]): + s += ", %s = %s" % [_signed(f["mod"]), total] + return s + + +static func _why_check(f: Dictionary, L: Dictionary, plain: bool) -> String: + var faces := _faces(f.get("faces")) + var nat := Expr.format_value(f.get("nat")) + var total := Expr.format_value(f.get("total")) + var target := Expr.format_value(f.get("target")) + var le := str(f.get("cmp", "ge")) == "le" + var ok := bool(f.get("success", false)) + if not plain: + return "check %s%s vs %s (%s): %s %s = %s → %s" % [f.get("dice", ""), + (" + " + str(f.get("mod_expr", ""))) if str(f.get("mod_expr", "")) != "" else "", f.get("target_expr", target), + f.get("cmp", "ge"), nat, _signed(f.get("mod", 0)).replace(MINUS, "-"), total, "success" if ok else "failure"] + var s := "Rolled " + (faces if faces != "" else nat) + if _nonzero(f.get("mod", 0)): + s += ", %s = %s" % [_signed(f.get("mod", 0)), total] + s += ": needed %s or %s, %s" % [target, "less" if le else "more", "success" if ok else "failure"] + return s + + +## "Luck was 1 and Social Standing was 9" from a fact's values. +static func _values(values: Variant, L: Dictionary, plain: bool) -> String: + if not (values is Dictionary) or (values as Dictionary).is_empty(): + return "" + var parts := PackedStringArray() + for key: Variant in values: + var nm := str(key) + var v: Variant = values[key] + if plain: + parts.append(("%s wasn't set" % _label(nm, L)) if v == null else "%s was %s" % [_label(nm, L), _shown(v)]) + else: + parts.append("%s = %s" % [nm, "unset" if v == null else Expr.format_value(v)]) + if not plain: + return ", ".join(parts) + if parts.size() == 1: + return parts[0] + return ", ".join(parts.slice(0, parts.size() - 1)) + " and " + parts[parts.size() - 1] + + +static func _shown(v: Variant) -> String: + var s := Expr.format_value(v) + return s if s != "" else "empty" + + +## "(needs 2 or more)" for one comparison on a value that was read, else +## "(rule: )". +static func _needs(expr: String, values: Variant, L: Dictionary) -> String: + var m := Builder.parse_condition(expr) + if m["ok"] and (m["clauses"] as Array).size() == 1: + var c: Dictionary = m["clauses"][0] + if values is Dictionary and (values as Dictionary).has(str(c["var"])): + var tail := _tail(str(c["cmp"]), str(c["value"]), L) + if tail.begins_with("is "): + tail = tail.substr(3) + elif tail.begins_with("includes "): + tail = "to include " + tail.substr(9) + return "(needs %s)" % tail + return "(rule: %s)" % _condition(expr, L) + + +static func _why_when(f: Dictionary, board: TowerBoard, L: Dictionary, plain: bool) -> String: + var to := _table(str(f.get("to", "")), board, plain) + var expr := str(f.get("expr", "")) + var ok := bool(f.get("result", false)) + if not plain: + var t := "%s %s: when %s was %s" % ["Took" if ok else "Skipped", to, expr, "true" if ok else "false"] + if f.has("error"): + t = "Skipped %s: when %s failed: %s" % [to, expr, f["error"]] + var vals := _values(f.get("values"), L, false) + return t + (" (%s)" % vals if vals != "" else "") + if f.has("error"): + return "Skipped %s: its condition couldn't be worked out (%s)" % [to, f["error"]] + var vals2 := _values(f.get("values"), L, true) + var verb := "Took" if ok else "Skipped" + if vals2 == "": + return "%s %s: %s was %s" % [verb, to, _condition(expr, L), "true" if ok else "false"] + return "%s %s because %s %s" % [verb, to, vals2, _needs(expr, f.get("values"), L)] + + +static func _why_case(f: Dictionary, L: Dictionary, plain: bool) -> String: + var n := int(f.get("index", 0)) + 1 + var expr := str(f.get("expr", "")) + var ok := bool(f.get("result", false)) + if expr == "": + return "Otherwise (case %d): no case before it matched" % n if plain else "case %d: otherwise" % n + if not plain: + var t := "case %d: %s → %s" % [n, expr, "error: " + str(f["error"]) if f.has("error") else ("true" if ok else "false")] + var vals := _values(f.get("values"), L, false) + return t + (" (%s)" % vals if vals != "" else "") + if f.has("error"): + return "Case %d couldn't be worked out (%s)" % [n, f["error"]] + var vals2 := _values(f.get("values"), L, true) + var verb := "matched" if ok else "didn't match" + if vals2 == "": + return "Case %d %s: %s was %s" % [n, verb, _condition(expr, L), "true" if ok else "false"] + return "Case %d %s because %s %s" % [n, verb, vals2, _needs(expr, f.get("values"), L)] + + +static func _why_effect(f: Dictionary, L: Dictionary, plain: bool) -> String: + var v := str(f.get("var", "")) + var op := str(f.get("op", "")) + if not plain: + if f.has("count"): + return "reset %s (%s)" % [v, Expr.format_value(f["count"])] + return "%s %s: %s → %s" % [v, op, _raw(f.get("before")), _raw(f.get("after"))] + var lab := _label(v, L) + if f.has("count"): + return "Cleared all %s (%s)" % [lab, Expr.format_value(f["count"])] + var before: Variant = f.get("before") + var after: Variant = f.get("after") + if op == "reset" and after == null: + return "%s was cleared" % lab + if before == null: + return "%s became %s" % [lab, _shown(after)] + return "%s went from %s to %s" % [lab, _shown(before), _shown(after)] + + +static func _raw(v: Variant) -> String: + return "unset" if v == null else Expr.format_value(v) + + +# ---------------------------------------------------------------- helpers + +## `s`, or when it's too long the original text (if that's shorter) or a cut. +static func _short(s: String, original: String) -> String: + if s.length() <= MAX_LEN: + return s + if original.length() <= MAX_LEN: + return original + return s.substr(0, MAX_LEN - 1) + "…" diff --git a/core/describe.gd.uid b/core/describe.gd.uid new file mode 100644 index 0000000..1277d1d --- /dev/null +++ b/core/describe.gd.uid @@ -0,0 +1 @@ +uid://gqkj2l7wn7kh diff --git a/core/effects.gd b/core/effects.gd index 9cc2681..914db46 100644 --- a/core/effects.gd +++ b/core/effects.gd @@ -142,8 +142,12 @@ static func validate(text: String) -> Array[Dictionary]: ## Runs every statement against the context. Returns the log, one line per ## statement: Array of {"text": String, "error": bool (only when true)}. -## `source_id` is stored as the variables' source table. -static func run(text: String, ctx: RollContext, source_id: String = "") -> Array[Dictionary]: +## `source_id` is stored as the variables' source table. `facts`, when given, +## gets one why-trace fact per statement that changed something: +## {"type": "effect", "var": "@name" (or "@prefix_*" / a chain name), "op": +## "=" | "+=" | "-=" | "*=" | "/=" | "reset", "before": value or null, +## "after": value or null} ("count" instead of before/after for a prefix reset). +static func run(text: String, ctx: RollContext, source_id: String = "", facts: Variant = null) -> Array[Dictionary]: var log: Array[Dictionary] = [] if text.strip_edges() == "": return log @@ -159,9 +163,9 @@ static func run(text: String, ctx: RollContext, source_id: String = "") -> Array continue st["target"] = rt["target"] if st["op"] == "reset": - log.append(_reset(st["target"], ctx)) + log.append(_reset(st["target"], ctx, facts)) else: - log.append(_assign(st, ctx, source_id)) + log.append(_assign(st, ctx, source_id, facts)) return log @@ -173,7 +177,7 @@ static func log_text(log: Array) -> PackedStringArray: return out -static func _assign(st: Dictionary, ctx: RollContext, source_id: String) -> Dictionary: +static func _assign(st: Dictionary, ctx: RollContext, source_id: String, facts: Variant = null) -> Dictionary: var target: String = st["target"] var op: String = st["op"] var r := Expr.evaluate(st["expr"], ctx) @@ -240,10 +244,12 @@ static func _assign(st: Dictionary, ctx: RollContext, source_id: String) -> Dict value = floori(float(a2) / float(b2)) line = "%s ÷%s → %s" % [label, Expr.format_value(b2), _shown(value)] ctx.save(target, value, source_id) + if facts != null: + (facts as Array).append({"type": "effect", "var": target, "op": op, "before": cur, "after": ctx.get_value(target)}) return {"text": line} -static func _reset(target: String, ctx: RollContext) -> Dictionary: +static func _reset(target: String, ctx: RollContext, facts: Variant = null) -> Dictionary: if target.ends_with("*"): var prefix := target.trim_prefix("@").trim_suffix("*") var names := {} @@ -260,12 +266,17 @@ static func _reset(target: String, ctx: RollContext) -> Dictionary: errors.append(r) if not errors.is_empty(): return {"text": "reset %s: %s" % [target, "; ".join(errors)], "error": true} + if facts != null: + (facts as Array).append({"type": "effect", "var": target, "op": "reset", "count": names.size()}) return {"text": "Reset %s (%d)" % [target, names.size()]} var name := target.trim_prefix("@") + var before: Variant = ctx.get_value("@" + name) var err := reset_one(name, ctx) if err != "": return {"text": "reset %s: %s" % [target, err], "error": true} var v: Variant = ctx.get_value("@" + name) + if facts != null: + (facts as Array).append({"type": "effect", "var": "@" + name, "op": "reset", "before": before, "after": v}) if v == null: return {"text": "Reset %s (cleared)" % ctx.display_name(name)} return {"text": "Reset %s → %s" % [ctx.display_name(name), _shown(v)]} diff --git a/core/expr.gd b/core/expr.gd index f744d83..80ea402 100644 --- a/core/expr.gd +++ b/core/expr.gd @@ -112,6 +112,27 @@ static func check(src: String) -> String: return str(_parsed(src)["error"]) +## The variables an expression reads, in order of first use: "@name" for +## board variables, "name" for chain variables (indirect @[…] names aren't +## known until it runs, so they're left out). [] when it doesn't parse. +static func names_in(src: String) -> Array: + var p := _parsed(src) + if p["error"] != "": + return [] + var out: Array = [] + for pair: Array in p["vars"]: + out.append(("@" if pair[0] == "@" else "") + str(pair[1])) + return out + + +## {name: value} for names_in(src), read from `ctx` now (null when unset). +static func values_read(src: String, ctx: RollContext) -> Dictionary: + var out := {} + for nm: String in names_in(src): + out[nm] = ctx.get_value(nm) if ctx != null else null + return out + + ## Number-like text becomes a number ("12" -> 12, "2.5" -> 2.5); whole floats ## become ints; anything else is unchanged. static func to_value(v: Variant) -> Variant: @@ -482,6 +503,13 @@ class _Base: var error: String = "" func _d(n: int, sides: int) -> int: + if ctx != null and ctx.faces != null: + var total := 0 + for k in n: + var f := ctx.rng.randi_range(1, sides) + (ctx.faces as Array).append(f) + total += f + return total return Expr.roll_dice(n, sides, ctx.rng if ctx != null else null) func dm(x: Variant) -> int: diff --git a/core/roll_context.gd b/core/roll_context.gd index a1ad957..f701c46 100644 --- a/core/roll_context.gd +++ b/core/roll_context.gd @@ -79,6 +79,10 @@ var root: Dictionary = {} var running: int = 0 ## While true the roller never awaits the prompt hook (sync Roller.roll()). var no_prompt: bool = false +## While an Array, every die Expr or a ranged table rolls appends its face +## here (the roller sets it around a roll to record "nat" and the why trace). +## null (the default) records nothing. +var faces: Variant = null var _decl: Dictionary = {} var _decl_built := false @@ -212,7 +216,7 @@ func declared(name: String) -> RollTable: _decl.clear() if board != null: for t in board.tables: - if t.kind == RollTable.KIND_VARIABLE and t.var_name != "" and not _decl.has(t.var_name): + if t.kind == RollTable.KIND_VARIABLE and t.var_name != "" and t.var_type != RollTable.VAR_COLLECTION and not _decl.has(t.var_name): _decl[t.var_name] = t return _decl.get(name.strip_edges().trim_prefix("@")) diff --git a/core/roll_table.gd b/core/roll_table.gd index f80ef0b..df67e3e 100644 --- a/core/roll_table.gd +++ b/core/roll_table.gd @@ -24,12 +24,21 @@ const KIND_LOOP := "loop" const KIND_VARIABLE := "variable" const KIND_SHEET := "sheet" const KIND_ROUTER := "router" -const KINDS: Array[String] = [KIND_ROLL, KIND_CHOICE, KIND_LOOP, KIND_VARIABLE, KIND_SHEET, KIND_ROUTER] +const KIND_CHECK := "check" +const KINDS: Array[String] = [KIND_ROLL, KIND_CHOICE, KIND_LOOP, KIND_VARIABLE, KIND_SHEET, KIND_ROUTER, KIND_CHECK] ## A new router's first case condition (an even chance, so both cases can come up). const ROUTER_DEFAULT_WHEN := "1d6 >= 4" const CHOICES: Array[String] = ["pick", "number", "text"] const LOOPS: Array[String] = ["times", "while", "until"] -const VAR_TYPES: Array[String] = ["number", "text", "list"] +## A variable card with var_type "collection" declares a group of board +## values @_ (docs/PLAIN.md §3); its name labels the group. +const VAR_COLLECTION := "collection" +const VAR_TYPES: Array[String] = ["number", "text", "list", VAR_COLLECTION] +## Check cards (docs/PLAIN.md §4.1): success when the total is >= ("ge") or +## <= ("le") the target. +const CHECK_CMPS: Array[String] = ["ge", "le"] +const CHECK_DEFAULT_DICE := "2d6" +const CHECK_DEFAULT_TARGET := "8" var id: String = "" var name: String = "" @@ -75,6 +84,17 @@ var loop_expr: String = "" var var_name: String = "" var var_type: String = "number" var initial: String = "" +## Check cards: the dice, the modifier and the target (expressions) and the +## comparison ("ge" or "le"). entries[0] is Success, entries[1] Failure. +var check_dice: String = CHECK_DEFAULT_DICE +var check_mod: String = "" +var check_cmp: String = "ge" +var check_target: String = CHECK_DEFAULT_TARGET +## Card inputs (any kind but variable): Array of {"name": String, "label": +## String, "default": String (an expression; "" reads as 0)}. While a pipe's +## subtree runs, each input is a chain value (the pipe's "with" value, or the +## default). +var inputs: Array = [] var _dice_cache: Dice = null var _dice_cache_text: String = "" @@ -88,11 +108,13 @@ func _init(p_id: String = "", p_name: String = "") -> void: ## A well-formed card of any kind. `sub` picks the variant: the choice ## ("pick", "number", "text"), the loop mode ("times", "while", "until") or -## the variable type ("number", "text", "list"). +## the variable type ("number", "text", "list", "collection"). ## roll: four "Result N" entries · choice pick: three options · ## choice number/text: one "Answer" entry · loop: "Each time" and ## "Afterwards" · variable: no entries · sheet: one template entry · -## router: an "if …" case (when ROUTER_DEFAULT_WHEN) and an "Otherwise" case. +## router: an "if …" case (when ROUTER_DEFAULT_WHEN) and an "Otherwise" case · +## check: "Success" and "Failure" (2d6 vs 8) · variable "collection": the +## stem is the name's slug without a final "s" ("Skills" -> "skill"). static func create(p_kind: String, p_id: String, p_name: String, sub: String = "") -> RollTable: var t := RollTable.new(p_id, p_name) t.kind = p_kind if KINDS.has(p_kind) else KIND_ROLL @@ -121,6 +143,8 @@ static func create(p_kind: String, p_id: String, p_name: String, sub: String = " KIND_VARIABLE: t.var_type = sub if VAR_TYPES.has(sub) else "number" t.var_name = JsonIO.slug(Formatter.strip_tags(p_name), "var") if p_name != "" else "var" + if t.var_type == VAR_COLLECTION and t.var_name.length() > 3 and t.var_name.ends_with("s") and not t.var_name.ends_with("ss"): + t.var_name = t.var_name.substr(0, t.var_name.length() - 1) t.initial = "0" if t.var_type == "number" else "" KIND_SHEET: t.entries.append(TableEntry.new("e1", "[b]%s[/b]" % p_name)) @@ -129,9 +153,57 @@ static func create(p_kind: String, p_id: String, p_name: String, sub: String = " first.when = ROUTER_DEFAULT_WHEN t.entries.append(first) t.entries.append(TableEntry.new("e2", "Otherwise")) + KIND_CHECK: + t.entries.append(TableEntry.new("e1", "Success")) + t.entries.append(TableEntry.new("e2", "Failure")) return t +## True for a collection variable card. +func is_collection() -> bool: + return kind == KIND_VARIABLE and var_type == VAR_COLLECTION + + +## Names of the declared inputs, in order. +func input_names() -> Array[String]: + var out: Array[String] = [] + for inp: Dictionary in inputs: + out.append(str(inp.get("name", ""))) + return out + + +## The declared input called `name`, or {}. +func find_input(input_name: String) -> Dictionary: + for inp: Dictionary in inputs: + if str(inp.get("name", "")) == input_name: + return inp + return {} + + +## Cleans an "inputs" value from JSON or the UI: Array of {name, label, +## default} with names trimmed (a leading "@" dropped) and empty names left +## out. Numbers become expression text. +static func clean_inputs(v: Variant) -> Array: + var out: Array = [] + if not (v is Array): + return out + for item: Variant in v: + var nm := "" + var label := "" + var def := "" + if item is Dictionary: + nm = str(item.get("name", "")) if item.get("name") != null else "" + label = str(item.get("label", "")) if item.get("label") != null else "" + def = expr_text(item.get("default", ""), "") + elif item is String: + nm = item + nm = nm.strip_edges().trim_prefix("@") + if nm == "": + continue + out.append({"name": nm, "label": label.strip_edges(), "default": def.strip_edges()}) + return out + + ## True for a pick choice whose options come from variables (options_from). func is_dynamic() -> bool: return kind == KIND_CHOICE and choice == "pick" and options_from.strip_edges() != "" @@ -217,6 +289,14 @@ func dice_obj() -> Dice: ## Rolls the ranged table's dice. Returns {"value": int, "error": String}. func roll_value(ctx: RollContext) -> Dictionary: if not is_expr_dice(): + if ctx.faces != null: + var d := dice_obj() + var total := d.bonus + for k in d.count: + var face := ctx.rng.randi_range(1, d.sides) + (ctx.faces as Array).append(face) + total += face + return {"value": total if d.valid else 0, "error": ""} return {"value": dice_obj().roll(ctx.rng), "error": ""} var r := Expr.evaluate(dice, ctx) if r["error"] != "": @@ -227,6 +307,8 @@ func roll_value(ctx: RollContext) -> Dictionary: ## Label for the dice: "d100", "2d6", "1d8+2". Plain tables label by entry ## count; expression dice show the expression. func dice_label() -> String: + if kind == KIND_CHECK: + return check_dice.strip_edges() if is_ranged(): return dice.strip_edges() if is_expr_dice() else dice_obj().label() return "d%d" % die_size() @@ -462,6 +544,25 @@ func to_dict() -> Dictionary: d["var_type"] = var_type if initial != "": d["initial"] = initial + elif kind == KIND_CHECK: + if check_dice != CHECK_DEFAULT_DICE: + d["check_dice"] = check_dice + if check_mod != "": + d["check_mod"] = check_mod + if check_cmp != "ge": + d["check_cmp"] = check_cmp + if check_target != CHECK_DEFAULT_TARGET: + d["check_target"] = check_target + if not inputs.is_empty(): + var list2: Array = [] + for inp: Dictionary in inputs: + var o := {"name": str(inp.get("name", ""))} + if str(inp.get("label", "")) != "": + o["label"] = str(inp["label"]) + if str(inp.get("default", "")) != "": + o["default"] = str(inp["default"]) + list2.append(o) + d["inputs"] = list2 return d @@ -495,6 +596,16 @@ static func from_dict(d: Dictionary) -> RollTable: var vt := str(d.get("var_type", "number")) t.var_type = vt if VAR_TYPES.has(vt) else "number" t.initial = expr_text(d.get("initial", ""), "") + t.check_dice = expr_text(d.get("check_dice", CHECK_DEFAULT_DICE), CHECK_DEFAULT_DICE).strip_edges() + if t.check_dice == "": + t.check_dice = CHECK_DEFAULT_DICE + t.check_mod = expr_text(d.get("check_mod", ""), "").strip_edges() + var cc := str(d.get("check_cmp", "ge")) + t.check_cmp = cc if CHECK_CMPS.has(cc) else "ge" + t.check_target = expr_text(d.get("check_target", CHECK_DEFAULT_TARGET), CHECK_DEFAULT_TARGET).strip_edges() + if t.check_target == "": + t.check_target = CHECK_DEFAULT_TARGET + t.inputs = clean_inputs(d.get("inputs", [])) for ed: Variant in d.get("entries", []): if ed is Dictionary: t.entries.append(TableEntry.from_dict(ed)) diff --git a/core/roller.gd b/core/roller.gd index ca6bb80..57f1e9f 100644 --- a/core/roller.gd +++ b/core/roller.gd @@ -23,6 +23,12 @@ extends RefCounted ## node ("after": true) ## limit: true on the "Stopped after 10,000 actions" stop node ## cancelled: true on the "Cancelled" stop node +## check: on a check card's node, {nat, mod, total, target, success} +## (its "value" is the total; "index" 0 is Success, 1 Failure) +## inputs: {name: value}, the card inputs bound while this node's subtree +## ran (docs/PLAIN.md §4.2) +## why: Array of trace facts (plain Dictionaries with a "type"; see +## docs/LOGIC.md §10 and Describe.why()), present when there are any ## ## The roller is a coroutine with an explicit work stack: pipes and loop passes ## never recurse in GDScript, so chains of thousands of steps are fine. Only @@ -40,7 +46,7 @@ const CANCELLED := "Cancelled" const NO_CASE := "No case matched" const NO_OPTIONS := "No options available" -enum { OP_ROLL, OP_PIPE, OP_LOOP } +enum { OP_ROLL, OP_PIPE, OP_LOOP, OP_RESTORE } ## A RollContext wired to this board: it resolves [[names]] against the board's @@ -163,6 +169,13 @@ static func _chain(board: TowerBoard, table_id: String, depth: int, ctx: RollCon _do_pipe(board, f, ctx, stack) OP_LOOP: await _do_loop(f, ctx, stack) + OP_RESTORE: + _restore(f, ctx) + # A halted roll leaves frames behind: put back any card inputs they hid. + while not stack.is_empty(): + var rest: Dictionary = stack.pop_back() + if int(rest["op"]) == OP_RESTORE: + _restore(rest, ctx) ctx.running -= 1 var kids: Array = holder["children"] return kids[0] if not kids.is_empty() else {} @@ -177,6 +190,13 @@ static func _stop(t: RollTable, why: String, extra: Dictionary = {}) -> Dictiona static func _attach(f: Dictionary, node: Dictionary, ctx: RollContext) -> void: if str(f.get("save", "")) != "": node["save_as"] = f["save"] + if f.has("inputs"): + node["inputs"] = f["inputs"] + var facts: Array = f["pre_why"] + if node.has("why"): + facts.append_array(node["why"]) + node["why"] = facts + _log(node, f["pre_log"]) (f["parent"]["children"] as Array).append(node) if f.get("top", false): ctx.root = node @@ -200,6 +220,7 @@ static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: return if not _take_action(f, t, ctx): return + _bind_inputs(t, f, ctx, stack) if t.entries.is_empty(): _attach(f, _stop(t, "This table has no results"), ctx) return @@ -210,6 +231,8 @@ static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: _start_loop(t, f, ctx, stack) RollTable.KIND_ROUTER: await _do_router(t, f, ctx, stack) + RollTable.KIND_CHECK: + await _do_check(t, f, ctx, stack) RollTable.KIND_SHEET: var sheet := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "", "kind": RollTable.KIND_SHEET} @@ -217,6 +240,9 @@ static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: await _enter(sheet, f, ctx, stack, true, true) _: var node := _pick_node(t, ctx) + if node.has("nat"): + ctx.chain_vars["nat"] = node["nat"] + node.erase("nat") _attach(f, node, ctx) if not node.has("stop"): await _enter(node, f, ctx, stack) @@ -229,6 +255,7 @@ static func _pick_node(t: RollTable, ctx: RollContext) -> Dictionary: var index: int var value: int var reshuffled := false + var fact: Dictionary if t.card_mode: var decks: Dictionary = ctx.get_meta("decks", {}) if not decks.has(t.id): @@ -244,11 +271,25 @@ static func _pick_node(t: RollTable, ctx: RollContext) -> Dictionary: var card := deck.draw(t, rng) index = int(card["index"]) value = int(card["value"]) + fact = {"type": "roll", "pick": "card", "dice": t.dice_label(), "total": value} elif t.is_ranged(): + var was: Variant = ctx.faces + ctx.faces = [] var rv := t.roll_value(ctx) + var faces: Array = ctx.faces + ctx.faces = was + if was != null: + (was as Array).append_array(faces) if rv["error"] != "": return _stop(t, "Can't roll %s: %s" % [t.dice, rv["error"]]) value = int(rv["value"]) + fact = {"type": "roll", "pick": "dice", "dice": t.dice.strip_edges(), "faces": faces, "total": value} + if not faces.is_empty(): + var nat := 0 + for x: int in faces: + nat += x + fact["nat"] = nat + fact["mod"] = value - nat index = t.entry_index_clamped(value) if t.is_expr_dice() else t.entry_index_for(value) if index < 0: return _stop(t, "No result for %s" % t.fmt(value), {"value": value}) @@ -257,10 +298,18 @@ static func _pick_node(t: RollTable, ctx: RollContext) -> Dictionary: if index < 0: return _stop(t, "No result can come up") value = index + 1 + fact = {"type": "roll", "pick": "weighted", "dice": t.dice_label(), "total": value} var node := {"table": t, "index": index, "value": value, "entry": t.entries[index], "children": [], - "summary": ""} + "summary": "", "why": [fact]} if reshuffled: node["reshuffled"] = true + # "nat" for the caller (_do_roll sets the chain value and drops the key): + # the dice alone, or a plain table's die value. An expression without + # dice ("@terms") has none. + if fact.has("nat"): + node["nat"] = fact["nat"] + elif str(fact["pick"]) != "dice": + node["nat"] = value return node @@ -276,7 +325,9 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr var e: TableEntry = node["entry"] var depth := int(f.get("depth", 0)) if e.effects.strip_edges() != "": - _log(node, Effects.run(e.effects, ctx, t.id)) + var facts: Array = [] + _log(node, Effects.run(e.effects, ctx, t.id, facts)) + _why(node, facts) if expand: ctx.depth = depth + 1 var ex: Dictionary = await TextExpander.expand_async(e.text, ctx, live) @@ -308,14 +359,29 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr if e.pipes.is_empty(): return var log: Array = [] - var plan := pipe_plan(e, ctx, log) + var why: Array = [] + var plan := pipe_plan(e, ctx, log, why) _log(node, log) + _why(node, why) for k in range(plan.size() - 1, -1, -1): var item: Dictionary = plan[k] if not item["run"]: continue var p: String = item["to"] - stack.append({"op": OP_PIPE, "node": node, "entry": e, "to": p, "left": int(item["count"]), "save": e.save_for(p), "depth": depth}) + var fr := {"op": OP_PIPE, "node": node, "entry": e, "to": p, "left": int(item["count"]), "save": e.save_for(p), "depth": depth} + if item.has("with"): + fr["with"] = item["with"] + stack.append(fr) + + +## Appends why-trace facts to a node's "why". +static func _why(node: Dictionary, facts: Array) -> void: + if facts.is_empty(): + return + if not node.has("why"): + node["why"] = facts + else: + (node["why"] as Array).append_array(facts) ## Appends effect-log lines to a node's "effects". @@ -329,14 +395,19 @@ static func _log(node: Dictionary, lines: Array) -> void: ## The snapshot of an entry's pipes, taken once after the entry's effects ran ## and its text expanded: one item per pipe, in pipe order, -## {"to": table id, "run": bool, "count": int}. +## {"to": table id, "run": bool, "count": int, "with": {name: value}} ("with" +## only on a pipe that runs and passes input values; a value whose expression +## fails is left out, so the target's default applies, with an error line). ## - A pipe with a condition ("when") runs only if it's true. An error ## counts as false and adds an error line to `log`. ## - An "otherwise" pipe runs only if none of the entry's conditions was true. ## - Any other pipe always runs. ## Counts are worked out only for pipes that run (0 for the others); an -## expression count's error gives 0 and an error line. -static func pipe_plan(e: TableEntry, ctx: RollContext, log: Array = []) -> Array: +## expression count's error gives 0 and an error line. `why` gets the trace +## facts: {"type": "when", "to", "expr", "values": {name: value}, "result": +## bool, "error"?} per conditional pipe and {"type": "otherwise", "to", +## "result"} per otherwise pipe. +static func pipe_plan(e: TableEntry, ctx: RollContext, log: Array = [], why: Array = []) -> Array: var plan: Array = [] var any_true := false for p in e.pipes: @@ -344,22 +415,104 @@ static func pipe_plan(e: TableEntry, ctx: RollContext, log: Array = []) -> Array var run := true if w != "": var r := Expr.evaluate(w, ctx) + var fact := {"type": "when", "to": p, "expr": w, "values": Expr.values_read(w, ctx), "result": false} if r["error"] != "": log.append({"text": "Pipe condition %s: %s" % [w, r["error"]], "error": true}) run = false + fact["error"] = str(r["error"]) else: run = Expr.truthy(r["value"]) + fact["result"] = run + why.append(fact) any_true = any_true or run plan.append({"to": p, "run": run, "count": 0, "otherwise": w == "" and e.is_otherwise(p)}) for item: Dictionary in plan: if item["otherwise"]: item["run"] = not any_true + why.append({"type": "otherwise", "to": item["to"], "result": item["run"]}) item.erase("otherwise") if item["run"]: item["count"] = e.count_value(str(item["to"]), ctx, log) + if not e.pipe_with.is_empty() and e.pipe_with.has(item["to"]): + item["with"] = with_values(e, str(item["to"]), ctx, log) return plan +## The input values a pipe passes, worked out now: {name: value}. A value +## whose expression fails is left out (the target's default applies) and adds +## an error line to `log`. +static func with_values(e: TableEntry, target: String, ctx: RollContext, log: Array = []) -> Dictionary: + var out := {} + var w: Variant = e.pipe_with.get(target) + if not (w is Dictionary): + return out + for nm: String in w: + var src := str(w[nm]) + var r := Expr.evaluate(src, ctx) + if r["error"] != "": + log.append({"text": "Pipe input %s = %s: %s" % [nm, src, r["error"]], "error": true}) + else: + out[nm] = Expr.normalize(r["value"]) + return out + + +# ---------- Card inputs ---------- + +## Binds a card's inputs as chain values for the subtree about to run: the +## pipe's "with" values (f["with"]), and each declared input's default for the +## rest. Pushes an OP_RESTORE frame first, so the previous values come back +## when the subtree ends. The trace facts and error lines go on the node via +## _attach(). +static func _bind_inputs(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void: + var given: Dictionary = f.get("with", {}) + if t.inputs.is_empty() and given.is_empty(): + return + var values := {} + var facts: Array = [] + var log: Array = [] + for inp: Dictionary in t.inputs: + var nm := str(inp.get("name", "")) + if nm == "" or values.has(nm): + continue + if given.has(nm): + values[nm] = given[nm] + facts.append({"type": "input", "name": nm, "value": given[nm], "from": "pipe"}) + continue + var def := str(inp.get("default", "")).strip_edges() + var v: Variant = 0 + if def != "": + var r := Expr.evaluate(def, ctx) + if r["error"] != "": + log.append({"text": "Input %s default %s: %s" % [nm, def, r["error"]], "error": true}) + else: + v = Expr.normalize(r["value"]) + values[nm] = v + facts.append({"type": "input", "name": nm, "value": v, "from": "default"}) + for nm: String in given: + if not values.has(nm): + values[nm] = given[nm] + facts.append({"type": "input", "name": nm, "value": given[nm], "from": "pipe"}) + var saved := {} + for nm: String in values: + saved[nm] = [ctx.chain_vars.has(nm), ctx.chain_vars.get(nm)] + ctx.chain_vars[nm] = values[nm] + stack.append({"op": OP_RESTORE, "saved": saved}) + f["inputs"] = values + f["pre_why"] = facts + f["pre_log"] = log + + +## Puts back the chain values a card's inputs hid. +static func _restore(f: Dictionary, ctx: RollContext) -> void: + var saved: Dictionary = f["saved"] + for nm: String in saved: + var pair: Array = saved[nm] + if pair[0]: + ctx.chain_vars[nm] = pair[1] + else: + ctx.chain_vars.erase(nm) + + static func _do_pipe(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: Array) -> void: if int(f["left"]) <= 0: return @@ -368,38 +521,121 @@ static func _do_pipe(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: return f["left"] = int(f["left"]) - 1 stack.append(f) - stack.append({"op": OP_ROLL, "id": f["to"], "parent": f["node"], "save": f["save"], "depth": f["depth"]}) + var fr := {"op": OP_ROLL, "id": f["to"], "parent": f["node"], "save": f["save"], "depth": f["depth"]} + if f.has("with"): + fr["with"] = f["with"] + stack.append(fr) # ---------- Routers ---------- ## The index of the first router case whose condition is true (an empty ## condition, the Otherwise case, always matches), or -1. Errors count as -## false and add a line to `log`. -static func route(t: RollTable, ctx: RollContext, log: Array = []) -> int: +## false and add a line to `log`. `why` gets one fact per case tried: +## {"type": "case", "index", "expr" ("" for Otherwise), "values", "result", +## "error"?}. +static func route(t: RollTable, ctx: RollContext, log: Array = [], why: Array = []) -> int: for k in t.entries.size(): var w := t.entries[k].when.strip_edges() if w == "": + why.append({"type": "case", "index": k, "expr": "", "values": {}, "result": true}) return k var r := Expr.evaluate(w, ctx) + var fact := {"type": "case", "index": k, "expr": w, "values": Expr.values_read(w, ctx), "result": false} + why.append(fact) if r["error"] != "": log.append({"text": "Case %s: %s" % [w, r["error"]], "error": true}) + fact["error"] = str(r["error"]) elif Expr.truthy(r["value"]): + fact["result"] = true return k return -1 static func _do_router(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void: var log: Array = [] - var k := route(t, ctx, log) + var why: Array = [] + var k := route(t, ctx, log, why) if k < 0: var stop := _stop(t, NO_CASE, {"kind": RollTable.KIND_ROUTER}) _log(stop, log) + _why(stop, why) _attach(f, stop, ctx) return var node := {"table": t, "index": k, "entry": t.entries[k], "children": [], "summary": "", "kind": RollTable.KIND_ROUTER, "case": k} _log(node, log) + _why(node, why) + _attach(f, node, ctx) + await _enter(node, f, ctx, stack) + + +# ---------- Checks ---------- + +## Rolls a check card's dice, modifier and target (docs/PLAIN.md §4.1): +## {"nat", "mod", "total", "target", "success", "faces" (the dice faces), +## "error" ("" when fine)}. An empty modifier is 0. Numbers are whole +## (floored). +static func check_roll(t: RollTable, ctx: RollContext) -> Dictionary: + var out := {"nat": 0, "mod": 0, "total": 0, "target": 0, "success": false, "faces": [], "error": ""} + var was: Variant = ctx.faces + ctx.faces = [] + var r := Expr.evaluate(t.check_dice, ctx) + var faces: Array = ctx.faces + ctx.faces = was + if was != null: + (was as Array).append_array(faces) + out["faces"] = faces + if r["error"] != "": + out["error"] = "Check dice %s: %s" % [t.check_dice, r["error"]] + return out + if not Expr.is_number(r["value"]): + out["error"] = "Check dice %s gave \"%s\", not a number" % [t.check_dice, Expr.format_value(r["value"])] + return out + var nat := Expr.as_int(r, 0) + var mod := 0 + if t.check_mod.strip_edges() != "": + var m := Expr.evaluate(t.check_mod, ctx) + if m["error"] != "" or not Expr.is_number(m["value"]): + out["error"] = "Check modifier %s: %s" % [t.check_mod, m["error"] if m["error"] != "" else "not a number"] + return out + mod = Expr.as_int(m, 0) + var g := Expr.evaluate(t.check_target, ctx) + if g["error"] != "" or not Expr.is_number(g["value"]): + out["error"] = "Check target %s: %s" % [t.check_target, g["error"] if g["error"] != "" else "not a number"] + return out + var target := Expr.as_int(g, 0) + var total := nat + mod + out["nat"] = nat + out["mod"] = mod + out["total"] = total + out["target"] = target + out["success"] = total <= target if t.check_cmp == "le" else total >= target + return out + + +static func _do_check(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void: + var c := check_roll(t, ctx) + if str(c["error"]) != "": + var stop := _stop(t, "Can't roll the check: %s" % c["error"], {"kind": RollTable.KIND_CHECK}) + stop["effects"] = [{"text": str(c["error"]), "error": true}] + _attach(f, stop, ctx) + return + ctx.chain_vars["nat"] = c["nat"] + ctx.chain_vars["total"] = c["total"] + ctx.chain_vars["effect"] = int(c["total"]) - int(c["target"]) + var k := 0 if c["success"] else 1 + var info := {"nat": c["nat"], "mod": c["mod"], "total": c["total"], "target": c["target"], "success": c["success"]} + var fact := {"type": "check", "dice": t.check_dice.strip_edges(), "mod_expr": t.check_mod.strip_edges(), + "target_expr": t.check_target.strip_edges(), "faces": c["faces"], "nat": c["nat"], "mod": c["mod"], + "total": c["total"], "target": c["target"], "cmp": t.check_cmp, "success": c["success"]} + if k >= t.entries.size(): + var none := _stop(t, "This check has no Failure result", {"kind": RollTable.KIND_CHECK, "check": info, "value": c["total"]}) + _why(none, [fact]) + _attach(f, none, ctx) + return + var node := {"table": t, "index": k, "entry": t.entries[k], "value": c["total"], "children": [], "summary": "", + "kind": RollTable.KIND_CHECK, "check": info, "why": [fact]} _attach(f, node, ctx) await _enter(node, f, ctx, stack) @@ -490,7 +726,9 @@ static func _do_loop(f: Dictionary, ctx: RollContext, stack: Array) -> void: static func request_for(t: RollTable, ctx: RollContext) -> Dictionary: var options: Array = [] var log: Array = [] + var why: Array = [] var hidden := 0 + var chosen_hidden := false if t.choice == "pick": var ranged := t.is_ranged() for k in range(t.fixed_start(), t.entries.size()): @@ -500,9 +738,11 @@ static func request_for(t: RollTable, ctx: RollContext) -> Dictionary: continue options.append({"index": k, "entry": k, "text": TextExpander.render(e.text, ctx), "details": e.details, "weight": e.span() if ranged else maxi(0, e.weight)}) - if t.is_dynamic() and not t.entries.is_empty() and option_shown(t.entries[0], ctx, log): + if t.is_dynamic() and not t.entries.is_empty() and not option_shown(t.entries[0], ctx, log): + chosen_hidden = true + elif t.is_dynamic() and not t.entries.is_empty(): var chosen := t.entries[0] - var cands := dynamic_options(t, ctx, log) + var cands := dynamic_options(t, ctx, log, why) for j in cands.size(): var c: Dictionary = cands[j] var vt := Expr.format_value(c["value"]) if str(c["kind"]) == "prefix" else "" @@ -518,8 +758,10 @@ static func request_for(t: RollTable, ctx: RollContext) -> Dictionary: def = lo elif t.choice == "text": def = "" + if hidden > 0 or chosen_hidden: + why.push_front({"type": "show_if", "hidden": hidden, "chosen_hidden": chosen_hidden}) return {"table_id": t.id, "kind": t.choice, "title": t.name, "prompt": TextExpander.render(t.prompt, ctx), - "options": options, "min": lo, "max": hi, "default": def, "log": log, "hidden": hidden} + "options": options, "min": lo, "max": hi, "default": def, "log": log, "hidden": hidden, "why": why} ## Whether a pick option is offered now: its show_if is empty or true. An @@ -540,8 +782,9 @@ static func option_shown(e: TableEntry, ctx: RollContext, log: Array = []) -> bo ## variable name without "@", or the list item), label, value}. A prefix ## gives one per set variable, sorted by label ("Pilot"); a list gives one ## per item, in list order (label and value are the item). A filter error -## counts as false and adds one line to `log`. -static func dynamic_options(t: RollTable, ctx: RollContext, log: Array = []) -> Array: +## counts as false and adds one line to `log`. With a filter, `why` gets +## {"type": "options_where", "from", "expr", "kept", "total"}. +static func dynamic_options(t: RollTable, ctx: RollContext, log: Array = [], why: Array = []) -> Array: var out: Array = [] var src := RollTable.parse_options_from(t.options_from) if str(src["error"]) != "": @@ -579,6 +822,7 @@ static func dynamic_options(t: RollTable, ctx: RollContext, log: Array = []) -> ctx.chain_vars[k] = saved[k] else: ctx.chain_vars.erase(k) + why.append({"type": "options_where", "from": t.options_from.strip_edges(), "expr": where, "kept": out.size(), "total": cands.size()}) return out @@ -625,6 +869,7 @@ static func _do_choice(t: RollTable, f: Dictionary, ctx: RollContext, stack: Arr if t.choice == "pick" and opts.is_empty(): var none := _stop(t, NO_OPTIONS, {"kind": RollTable.KIND_CHOICE}) _log(none, req["log"]) + _why(none, req["why"]) _attach(f, none, ctx) return var reply: Variant = await ask(ctx, req) @@ -659,6 +904,7 @@ static func _do_choice(t: RollTable, f: Dictionary, ctx: RollContext, stack: Arr # A plain fixed list: Random rolls the card the usual way # (weights, ranges, card mode). node = _pick_node(t, ctx) + node.erase("nat") node["random"] = true else: var k := _pick_option(opts, ctx.rng) @@ -669,6 +915,7 @@ static func _do_choice(t: RollTable, f: Dictionary, ctx: RollContext, stack: Arr node["random"] = true node["kind"] = RollTable.KIND_CHOICE _log(node, req["log"]) + _why(node, req["why"]) _attach(f, node, ctx) if node.has("stop"): return @@ -793,7 +1040,9 @@ static func _can_finish(t: RollTable, board: TowerBoard, done: Dictionary) -> bo ## is saved in the roll history. "text" is BBCode with internal markers. ## Logic-card keys (only when they apply): kind, effects (Array of {text, ## error?}), answer, passes, pass, after, picked, random, limit, cancelled, -## case (router nodes: the matched case's index). +## case (router nodes: the matched case's index), option, check ({nat, mod, +## total, target, success}), inputs ({name: value}) and why (the trace facts, +## a copy of the array; the facts themselves are shared, don't change them). static func step_of(n: Dictionary, depth: int = 0) -> Dictionary: var t: RollTable = n["table"] var step := { @@ -819,9 +1068,11 @@ static func step_of(n: Dictionary, depth: int = 0) -> Dictionary: step["kind"] = n["kind"] if n.has("effects"): step["effects"] = (n["effects"] as Array).duplicate(true) - for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled", "case", "option"]: + for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled", "case", "option", "check", "inputs"]: if n.has(k): step[k] = n[k] + if n.has("why"): + step["why"] = (n["why"] as Array).duplicate() return step @@ -940,10 +1191,14 @@ static func live_context(board: TowerBoard, persistent: Dictionary) -> RollConte ## Live display of a variable card: its current value as text, or its -## starting value (marked) when it isn't set yet. +## starting value (marked) when it isn't set yet. A collection shows its set +## members ("Gun Combat 1, Pilot 0"; set is false when there are none). ## Returns {"text": String, "set": bool, "error": String}. static func variable_display(board: TowerBoard, persistent: Dictionary, t: RollTable) -> Dictionary: var ctx := live_context(board, persistent) + if t.is_collection(): + var listed := ctx.list_text(t.var_name + "_") + return {"text": listed, "set": listed != "", "error": ""} var v: Variant = ctx.get_value("@" + t.var_name) if v != null: return {"text": Expr.format_value(v), "set": true, "error": ""} @@ -974,6 +1229,8 @@ static func lint_pipes(board: TowerBoard) -> Array[Dictionary]: for t in board.tables: out.append_array(lint_router(t)) out.append_array(lint_options(t)) + out.append_array(lint_check(t)) + out.append_array(lint_inputs(board, t)) for i in t.entries.size(): var e := t.entries[i] var first_other := "" @@ -1053,6 +1310,79 @@ static func lint_options(t: RollTable) -> Array[Dictionary]: return out +## Problems with a check card (empty for other kinds): dice, modifier or +## target expressions that don't parse or are empty, and a missing Success or +## Failure result. Items also carry "kind": "check" and "level": "error". +static func lint_check(t: RollTable) -> Array[Dictionary]: + var out: Array[Dictionary] = [] + if t.kind != RollTable.KIND_CHECK: + return out + for pair: Array in [["Check dice", t.check_dice], ["Check modifier", t.check_mod], ["Check target", t.check_target]]: + var src := str(pair[1]).strip_edges() + var msg := "" + if src == "": + if pair[0] != "Check modifier": + msg = "%s is empty" % pair[0] + elif Expr.check(src) != "": + msg = "%s %s: %s" % [pair[0], src, Expr.check(src)] + if msg != "": + out.append({"table_id": t.id, "entry_id": "", "message": msg, "kind": "check", "level": "error"}) + if t.entries.size() < 2: + out.append({"table_id": t.id, "entry_id": "", "kind": "check", "level": "error", + "message": "A check needs a Success result and a Failure result"}) + return out + + +## Problems with card inputs and the pipes that pass them (docs/PLAIN.md +## §4.2): declared inputs with a bad or repeated name or a default that +## doesn't parse ("level": "error"), pipe "with" expressions that don't parse +## (error), and a "with" naming an input the target doesn't declare +## ("level": "hint": it still works, as a chain value). Items carry "kind": +## "inputs". +static func lint_inputs(board: TowerBoard, t: RollTable) -> Array[Dictionary]: + var out: Array[Dictionary] = [] + var seen := {} + for inp: Dictionary in t.inputs: + var nm := str(inp.get("name", "")) + if not _is_name(nm): + out.append({"table_id": t.id, "entry_id": "", "kind": "inputs", "level": "error", + "message": "Input \"%s\" isn't a name (lowercase letters, digits and _)" % nm}) + elif seen.has(nm): + out.append({"table_id": t.id, "entry_id": "", "kind": "inputs", "level": "error", + "message": "Input %s is declared twice" % nm}) + seen[nm] = true + var def := str(inp.get("default", "")).strip_edges() + if def != "" and Expr.check(def) != "": + out.append({"table_id": t.id, "entry_id": "", "kind": "inputs", "level": "error", + "message": "Input %s default %s: %s" % [nm, def, Expr.check(def)]}) + for e in t.entries: + if e.pipe_with.is_empty(): + continue + for p in e.pipes: + var w := e.with_for(p) + if w.is_empty(): + continue + var target := board.get_table(p) + for nm: String in w: + var src := str(w[nm]) + if Expr.check(src) != "": + out.append({"table_id": t.id, "entry_id": e.id, "kind": "inputs", "level": "error", + "message": "Pipe input %s = %s: %s" % [nm, src, Expr.check(src)]}) + if target != null and target.find_input(nm).is_empty(): + out.append({"table_id": t.id, "entry_id": e.id, "kind": "inputs", "level": "hint", + "message": "The pipe to %s passes %s, but that card has no input called %s" % [_table_name(board, p), nm, nm]}) + return out + + +static var _name_re: RegEx = null + + +static func _is_name(s: String) -> bool: + if _name_re == null: + _name_re = RegEx.create_from_string("^[a-z_][a-z0-9_]*$") + return _name_re.search(s) != null + + static func _table_name(board: TowerBoard, id: String) -> String: var t := board.get_table(id) return Formatter.strip_tags(t.name) if t else id diff --git a/core/state_store.gd b/core/state_store.gd index a93be2a..99b51bd 100644 --- a/core/state_store.gd +++ b/core/state_store.gd @@ -127,6 +127,28 @@ func set_setting(key: String, value: Variant) -> void: _dirty = true +## How rules are shown (docs/PLAIN.md §5): "plain" (the default; Describe's +## phrases) or "text" (the stored rule text). +const RULES_VIEW := "rules_view" +const RULES_VIEWS: Array[String] = ["plain", "text"] + + +func rules_view() -> String: + var v := str(get_setting(RULES_VIEW, "plain")) + return v if RULES_VIEWS.has(v) else "plain" + + +## True when rules show in plain words. +func rules_plain() -> bool: + return rules_view() == "plain" + + +## Sets "plain" or "text" (anything else is ignored). +func set_rules_view(v: String) -> void: + if RULES_VIEWS.has(v): + set_setting(RULES_VIEW, v) + + # ---------- Forgetting ---------- ## Drops everything stored for a collection (decks, variables, its history). diff --git a/core/table_entry.gd b/core/table_entry.gd index f8860b3..d0d0a95 100644 --- a/core/table_entry.gd +++ b/core/table_entry.gd @@ -30,6 +30,10 @@ var pipe_when: Dictionary = {} ## target table id -> true: the pipe runs only when none of this entry's ## conditional pipes did. Ignored while the pipe has a condition. var pipe_otherwise: Dictionary = {} +## target table id -> {input name: expression}: values passed to the target +## card's inputs (docs/PLAIN.md §4.2), worked out in the entry's snapshot. +## Missing = none. +var pipe_with: Dictionary = {} ## Router cards: this case's condition. "" is the Otherwise case (always ## matches). Ignored on other kinds. var when: String = "" @@ -150,6 +154,29 @@ func has_conditional_pipes() -> bool: return false +## The pipe's input values: {input name: expression}, or {} (a copy). +func with_for(target: String) -> Dictionary: + var w: Variant = pipe_with.get(target) + return (w as Dictionary).duplicate() if w is Dictionary else {} + + +## Sets the pipe's input values ({} for none). Names are trimmed (a leading +## "@" dropped); empty names and empty expressions are left out; numbers +## become expression text. +func set_pipe_with(target: String, values: Variant) -> void: + var clean := {} + if values is Dictionary: + for k: Variant in values: + var nm := str(k).strip_edges().trim_prefix("@") + var ex := RollTable.expr_text(values[k], "").strip_edges() + if nm != "" and ex != "": + clean[nm] = ex + if clean.is_empty(): + pipe_with.erase(target) + else: + pipe_with[target] = clean + + func set_pipe_save(target: String, name: String) -> void: name = name.strip_edges() if name == "": @@ -173,6 +200,7 @@ func remove_pipe(target: String) -> void: pipe_save.erase(target) pipe_when.erase(target) pipe_otherwise.erase(target) + pipe_with.erase(target) func to_dict() -> Dictionary: @@ -195,7 +223,8 @@ func to_dict() -> Dictionary: var s := save_for(p) var w := when_for(p) var other := is_otherwise(p) - if expr == "" and n == 1 and s == "" and w == "" and not other: + var wv: Variant = pipe_with.get(p) + if expr == "" and n == 1 and s == "" and w == "" and not other and wv == null: list.append(p) else: var po := {"table": p} @@ -209,6 +238,8 @@ func to_dict() -> Dictionary: po["when"] = w elif other: po["otherwise"] = true + if wv is Dictionary and not (wv as Dictionary).is_empty(): + po["with"] = (wv as Dictionary).duplicate() list.append(po) d["pipes"] = list if has_range: @@ -231,6 +262,8 @@ static func from_dict(d: Dictionary) -> TableEntry: e.add_pipe(target, c if c is String else int(c), str(p.get("save_as", ""))) e.set_pipe_when(target, str(p.get("when", "")) if p.get("when") != null else "") e.set_pipe_otherwise(target, bool(p.get("otherwise", false))) + if p.get("with") is Dictionary: + e.set_pipe_with(target, p["with"]) elif str(p) != "": e.add_pipe(str(p)) var r: Variant = d.get("range") diff --git a/core/template_kit.gd b/core/template_kit.gd index a7099b5..35b3375 100644 --- a/core/template_kit.gd +++ b/core/template_kit.gd @@ -72,7 +72,7 @@ static func make(board: TowerBoard, table_ids: Array, kind: String, tname: Strin continue var np := {"table": other.name, "outside": true} if p is Dictionary: - for k in ["count", "save_as"]: + for k in ["count", "save_as", "with"]: if (p as Dictionary).has(k): np[k] = p[k] pipes.append(np) @@ -259,7 +259,7 @@ static func instantiate(tpl: Dictionary, values: Dictionary, board: TowerBoard, continue var np := {"table": to} if p is Dictionary: - for k in ["count", "save_as"]: + for k in ["count", "save_as", "with"]: if (p as Dictionary).has(k): np[k] = p[k] pipes.append(np) diff --git a/docs/LOGIC.md b/docs/LOGIC.md index efdf92e..a1110cc 100644 --- a/docs/LOGIC.md +++ b/docs/LOGIC.md @@ -18,8 +18,10 @@ Every table has a `kind`. Existing tables are `roll`. | `variable` | Never rolled. Declares a variable with a type, a starting value and a description (§5) | The variable's live value | | `sheet` | Prints its template with current values (§6) | The template, rendered live | | `router` | Chooses the first of its cases whose condition is true (§3b) | A fork icon, one row per case with its condition | +| `check` | Rolls dice plus a modifier against a target and takes its Success or Failure result (§3c) | The roll and target, Success and Failure rows | -Every kind except `variable` can be the start of a roll and can be the target of a pipe. +Every kind except `variable` can be the start of a roll and can be the target of a pipe, and +can declare **inputs** that pipes pass values to (§3d). Every entry, of any kind, can carry **effects** (§5.2) and pipes. Pipes keep their count and "save as" options, and a pipe count may now be an expression (`@terms`, `1d3`). A pipe may also have a condition, or be an "otherwise" pipe (§3a). @@ -185,11 +187,67 @@ has no dice. Its entries are **cases**, each with an entry-level `when` expressi be reordered and removed on the card, and their conditions edited there or in the settings dialog. -`Roller.lint_pipes(board)` lists problems for a board check: `when` or case conditions that +`Roller.lint_pipes(board)` lists problems for a board check (it also includes +`lint_check()` and `lint_inputs()`, §3c and §3d): `when` or case conditions that don't parse, bad `options_from` patterns, `options_where` and `show_if` expressions that don't parse, `options_from`/`show_if` on cards where they do nothing (§2a), an otherwise pipe listed before a `when` pipe on the same entry (a hint: it still works), an otherwise pipe on an entry with no `when` pipe (it always runs), and routers with -no cases or whose Otherwise case isn't last. Each item is `{table_id, entry_id, message}`. +no cases or whose Otherwise case isn't last. Each item is `{table_id, entry_id, message}`; items +from the check and input lint also carry `kind` (`"check"` or `"inputs"`) and `level` +(`"error"` or `"hint"`), which `BoardTester.static_checks()` passes on. + +## 3c. Check cards + +A check (`kind: "check"`) rolls `check_dice` (default `2d6`), adds `check_mod` (an expression, +default empty, e.g. `dm(@str)`) and compares the total with `check_target` (an expression, +default `8`): with `check_cmp` `ge` (the default) it succeeds when the total is the target or +more, with `le` (roll-under) when it is the target or less. It has two fixed entries, +**Success** (index 0) and **Failure** (index 1); the matching one happens like a rolled entry +(effects, text, pipes with the §3a snapshot). + +- Before that entry runs, three chain variables are set: `nat` (the dice alone), `total` + (dice plus modifier) and `effect` (total minus target; negative on a roll-under success). +- The node and step have `kind: "check"`, `value` (the total) and + `check: {nat, mod, total, target, success}`. It counts as one action. +- A dice, modifier or target expression that fails, or gives text, stops the node with + "Can't roll the check: …" (a dead end in the board test). A check with no Failure entry + stops with "This check has no Failure result" when it fails. +- `Roller.check_roll(table, ctx)` does the roll alone; `Roller.lint_check(table)` reports + expressions that don't parse, an empty dice or target, and a missing Success or Failure entry. + +### `nat` on roll tables + +Every roll of a `roll` table sets the chain variable `nat` too: for a ranged table, the sum of +the dice faces without any modifier (`2d6 + dm(@str)` and `2d6+3` both give the 2d6 alone), so a +"natural 2" rule can test `nat = 2`; for a weighted or card-mode table, the die value. An +expression with no dice at all (`@terms`) leaves `nat` as it was. A pick card's Random never +sets it. + +## 3d. Card inputs (pipe parameters) + +Any card (not a variable card) may declare `inputs: [{name, label, default}]`, and a pipe object +may pass values with `"with": {"": ""}`. + +- The `with` expressions are worked out in the entry's snapshot (§3a), together with the pipe's + condition and count, so an earlier pipe's subtree can't change them; a pipe with a count + passes the same values on every roll. +- When the chain reaches the card, each input becomes a chain variable (`tier`, `{tier}` in + text) for the card's whole subtree: its entry's effects, text, inline references and pipes, + loop passes, router cases and choice options. When that subtree ends, the previous values + (or their absence) come back. Two pipes into the same card can pass different values. +- An input the pipe doesn't pass gets its `default`, an expression worked out when the card is + reached (quote text: `"High"`; empty means 0). A roll that starts on the card, an inline + `[[reference]]` to it, and a pipe without `with` all use the defaults. +- A `with` value whose expression fails is left out (so the default applies) and adds a red + line "Pipe input tier = …: …"; a default that fails gives 0 and a red line. A `with` name + the target doesn't declare is still passed, as a chain variable. +- The node and step carry `inputs: {name: value}`. +- `Roller.lint_inputs(board, table)` reports input names that aren't names or are declared + twice and defaults or `with` expressions that don't parse (errors), and a `with` naming an + input the target doesn't declare (a hint). +- This works on the roller's explicit work stack (an `OP_RESTORE` frame under the subtree), so + it needs no recursion and respects the 10,000-action limit; a halted roll still puts the + values back. ## 4. Expressions @@ -234,6 +292,14 @@ when the expression has modifiers. declaration is needed. A **variable card** (`kind: variable`) is optional and gives a variable a label, a type (`number`, `text` or `list`), a starting value (an expression) and details. +- A **collection** is a variable card with `var_type: "collection"`. Its `var_name` is a stem + (`skill`), its name the group's label ("Skills"), and its members are the board variables + `@_` (`@skill_gun_combat`). It declares no variable of its own: members are + ordinary variables, `reset @skill_*`, `count("skill_")`, `{@skill_*}` and + `options_from: "@skill_*"` work as before, and plain descriptions (`Describe`, docs/PLAIN.md) + label members by the rest of their name ("Gun Combat") and the group by the card's name. + `RollTable.create("variable", id, "Skills", "collection")` gives the stem `skill` (the name's + slug without a final "s"). Its live display lists the set members. - `reset @name` sets a declared variable back to its starting value, or deletes an undeclared one. `reset @skill_*` resets every variable with that prefix. - Chain variables (no `@`, e.g. `answer`, `i`, `-> hero`) last for one top-level roll, as @@ -311,16 +377,45 @@ step's result. ## 9. File format additions Table keys: -- `kind` (`roll` is the default and is omitted) +- `kind` (`roll` is the default and is omitted; `check` is a check card) - `choice`, `prompt`, `save_as`, `min`, `max` (choice cards) - `options_from`, `options_where` (pick choices with options from variables, §2a) - `loop`, `loop_expr` (loop cards) -- `var_name`, `var_type`, `initial` (variable cards) +- `var_name`, `var_type` (`number`, `text`, `list` or `collection`), `initial` (variable cards) +- `check_dice`, `check_mod`, `check_cmp` (`ge` or `le`), `check_target` (check cards; Strings, + left out at their defaults `2d6`, `""`, `ge`, `8`) +- `inputs`: `[{"name": "tier", "label": "Tier", "default": "1"}]` (any card; `label` and + `default` left out when empty) Entry keys: - `effects` (String) - `when` (String, router cases; empty or missing is Otherwise) - `show_if` (String, pick options; empty or missing is always shown) -Pipe objects may have `"count": ""`, `"when": ""` and -`"otherwise": true` (left out when the pipe has a `when`). +Pipe objects may have `"count": ""`, `"when": ""`, +`"otherwise": true` (left out when the pipe has a `when`) and +`"with": {"": ""}` (§3d). + +## 10. Why trace + +Every node may carry `why`: an Array of facts, plain Dictionaries recorded by the roller, so a +UI can say why a roll went the way it did (`Describe.why(fact, board, plain)` turns one into a +sentence). Steps from `Roller.flatten()` carry them (a copy of the array) and they survive JSON, +so history keeps them. The key is left out when a node has no facts. Each fact has a `type`: + +| `type` | On | Keys | +|---|---|---| +| `input` | the card's node, first | `name`, `value`, `from` (`"pipe"` or `"default"`) | +| `roll` | rolled nodes (roll tables, a pick's plain Random) | `pick` (`"dice"`, `"weighted"`, `"card"`), `dice`, `total`; dice rolls also `faces` (Array), and when there were dice `nat` and `mod` | +| `check` | check nodes | `dice`, `mod_expr`, `target_expr`, `faces`, `nat`, `mod`, `total`, `target`, `cmp`, `success` | +| `case` | router nodes, one per case tried | `index`, `expr` (`""` for Otherwise), `values`, `result`, `error`? | +| `show_if` | pick nodes when options were hidden | `hidden` (fixed options hidden), `chosen_hidden` | +| `options_where` | dynamic pick nodes with a filter | `from`, `expr`, `kept`, `total` | +| `effect` | any node whose entry has effects, one per statement that ran | `var` (the real target, `@[…]` resolved), `op` (`=`, `+=`, `-=`, `*=`, `/=`, `reset`), `before`, `after` (null when unset); a prefix reset has `count` instead | +| `when` | the node whose entry has the pipe, one per conditional pipe | `to` (table id), `expr`, `values`, `result`, `error`? | +| `otherwise` | likewise, one per otherwise pipe | `to`, `result` | + +`values` maps each variable the expression reads (`"@luck"`, or a chain name such as `"tier"`) to +its value when it was evaluated (null when unset); indirect `@[…]` names aren't listed. The +order on a node is: input facts, then roll/check/case/options facts, then effects, then +when/otherwise facts. diff --git a/docs/PLAIN.md b/docs/PLAIN.md index 02fe9f1..a9a3f38 100644 --- a/docs/PLAIN.md +++ b/docs/PLAIN.md @@ -93,6 +93,38 @@ than". `>= N` reads "is N or more" when it sits after a value name. `state` setting `rules_view`: `"plain"` (default) or `"text"`. Everywhere a rule is shown, the UI uses `Describe` in plain mode and the stored text in text mode. +## 5a. Engine notes and deviations (phase 1) +The engine half (§1–§5) is built; LOGIC.md §3c, §3d, §5.1 (collections), §9 and §10 have the +details. Where it settles something the spec left open, or differs: +- **Builder models.** `amount` is the expression text as written (`"2d6"`, `"\"Millbrook\""`), + except for `append`/`remove`, where it is the item text without quotes (`"Psionic"`); + `append`/`remove` are `+=`/`-=` with one quoted text. Condition `value`s are the token as + written (a String: `"8"`, `"-2"`, `"\"Aslan\""`, `"@soc"`, a chain name, `true`/`false`). + Both models also accept chain names as `var` (`option_value >= 1`, `tier = 3`), which dynamic + options and inputs need. An empty condition parses to `{ok: true, join: "and", clauses: []}`. +- **`known_values`** items also have `table_id`, and members of a collection `collection` + (`"@skill_*"`); a value that is only read by some rule has source `read`. Chain names are + listed only when the board has a card that sets them. +- **Labels.** `le` reads "is at most N" and `ge` "is N or more" (as specified); a check card + reads "need N or more" / "need N or less". `Describe.effect()`/`effects()` take an optional + card, so `@[option] += 1` on a pick card taking options from a collection reads "Chosen + skill +1". `Describe.label(name, board)` is public. +- **Check cards.** `effect` is total minus target for both comparisons (negative on a roll-under + success). A dice, modifier or target expression that fails stops the node ("Can't roll the + check: …") rather than counting as a failure. +- **`nat`** on weighted and card-mode tables is the die value; an expression with no dice leaves + `nat` alone. +- **Inputs.** Defaults are expressions (quote text; empty means 0). Inputs are bound however the + card is reached (pipe, inline reference, start of the roll), and a `with` name the card + doesn't declare is still passed (and linted as a hint). +- **Why facts** are described in LOGIC.md §10. `show_if` and `options_where` are one summary + fact each; a node without facts has no `why` key. +- **Collections.** `RollTable.create("variable", …, "collection")` takes the stem from the name + without a final "s" ("Skills" → `skill`). A collection card doesn't declare `@skill` itself. + The settings dialog's Type switch gained a "Collection" choice so such cards stay editable. +- **Display preference.** `StateStore.rules_view()` / `rules_plain()` / `set_rules_view()` read + and write the `rules_view` setting. + ## 6. UI (phase 2) - **Inspector** (Build mode): a panel docked right that edits the selected card, result or pipe. - **Results:** text, details, and a **When this comes up** effects builder (rows of diff --git a/io/json_io.gd b/io/json_io.gd index 65e1685..9936fe9 100644 --- a/io/json_io.gd +++ b/io/json_io.gd @@ -10,11 +10,14 @@ extends RefCounted ## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode], ## [deck_empty], [kind], [choice], [prompt], [save_as], [options_from], ## [options_where], [min], [max], -## [loop], [loop_expr], [var_name], [var_type], [initial], entries +## [loop], [loop_expr], [var_name], [var_type], [initial], +## [check_dice], [check_mod], [check_cmp], [check_target], +## [inputs: [{name, [label], [default]}, ...]], entries ## entry: id, text, [details], [weight], [range], [effects], [when], [show_if], ## [pipes] ## pipe: a table id String, or {"table": id, "count": n or "", -## "save_as": name, "when": "", "otherwise": true} +## "save_as": name, "when": "", "otherwise": true, +## "with": {input name: ""}} ## ("otherwise" is dropped when the pipe has a "when") ## The logic-card keys (docs/LOGIC.md §9) are Strings, and are left out when ## they have their default value. @@ -129,6 +132,11 @@ static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Di for key in ["prompt", "initial"]: if t5.has(key): t5[key] = clean.call(str(t5[key])) + if t5.has("inputs"): + for inp: Dictionary in t5["inputs"]: + for key in ["name", "label", "default"]: + if inp.has(key): + inp[key] = clean.call(str(inp[key])) if t5.has("tags"): var tags: Array = [] for tag in t5["tags"]: @@ -184,6 +192,11 @@ static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Di np["save_as"] = clean.call(str(np["save_as"])) if np.has("when"): np["when"] = clean.call(str(np["when"])) + if np.get("with") is Dictionary: + var wd := {} + for k: String in np["with"]: + wd[clean.call(k)] = clean.call(str(np["with"][k])) + np["with"] = wd pipes.append(np) else: pipes.append(target) @@ -313,13 +326,25 @@ static func _canon_table(td: Dictionary) -> Dictionary: if RollTable.KINDS.has(kind) and kind != "roll": t["kind"] = kind var defaults := {"choice": "pick", "prompt": "", "save_as": "", "options_from": "", "options_where": "", "min": "0", "max": "99", - "loop": "times", "loop_expr": "", "var_name": "", "var_type": "number", "initial": ""} + "loop": "times", "loop_expr": "", "var_name": "", "var_type": "number", "initial": "", + "check_dice": RollTable.CHECK_DEFAULT_DICE, "check_mod": "", "check_cmp": "ge", "check_target": RollTable.CHECK_DEFAULT_TARGET} for key: String in defaults: if not td.has(key) or td[key] == null: continue var s := RollTable.expr_text(td[key], str(defaults[key])) if s != str(defaults[key]): t[key] = s + var inputs := RollTable.clean_inputs(td.get("inputs", [])) + if not inputs.is_empty(): + var list: Array = [] + for inp: Dictionary in inputs: + var o := {"name": inp["name"]} + if str(inp["label"]) != "": + o["label"] = inp["label"] + if str(inp["default"]) != "": + o["default"] = inp["default"] + list.append(o) + t["inputs"] = list var entries: Array = [] var src_entries: Variant = td.get("entries", []) if src_entries is Array: @@ -373,12 +398,29 @@ static func _canon_entry(ev: Variant) -> Dictionary: np["when"] = pw elif p.get("otherwise", false) is bool and bool(p.get("otherwise", false)): np["otherwise"] = true + var wv := _canon_with(p.get("with")) + if not wv.is_empty(): + np["with"] = wv pipes.append(np) if not pipes.is_empty(): e["pipes"] = pipes return e +## A pipe's "with" object: {input name: expression text}, names trimmed (a +## leading "@" dropped), numbers as text, empty names and values left out. +static func _canon_with(v: Variant) -> Dictionary: + var out := {} + if not (v is Dictionary): + return out + for k: Variant in v: + var nm := str(k).strip_edges().trim_prefix("@") + var ex := RollTable.expr_text(v[k], "").strip_edges() + if nm != "" and ex != "": + out[nm] = ex + return out + + # -------------------------------------------------------------- helpers ## Turns whole floats (as JSON parsing gives) into ints; returns `fallback` @@ -413,7 +455,8 @@ static func unique_id(base: String, used: Dictionary) -> String: ## Normalizes a pipe (String or Dictionary) to {"table", "count", "save_as", -## "count_expr", "when", "otherwise"}. An expression count ("@terms") reads as +## "count_expr", "when", "otherwise", "with"} ("with": {name: expression}, +## {} for none). An expression count ("@terms") reads as ## count 1, with the expression in "count_expr" ("" otherwise). "when" is the ## pipe's condition ("" for none); "otherwise" is true only without one. static func pipe_info(p: Variant) -> Dictionary: @@ -424,8 +467,9 @@ static func pipe_info(p: Variant) -> Dictionary: expr = (c as String).strip_edges() var w := str(p.get("when", "")).strip_edges() if p.get("when") != null else "" return {"table": str(p.get("table", "")), "count": int(_num(c, 1)), "save_as": str(p.get("save_as", "")), "count_expr": expr, - "when": w, "otherwise": w == "" and p.get("otherwise", false) is bool and bool(p.get("otherwise", false))} - return {"table": str(p), "count": 1, "save_as": "", "count_expr": "", "when": "", "otherwise": false} + "when": w, "otherwise": w == "" and p.get("otherwise", false) is bool and bool(p.get("otherwise", false)), + "with": _canon_with(p.get("with"))} + return {"table": str(p), "count": 1, "save_as": "", "count_expr": "", "when": "", "otherwise": false, "with": {}} ## Edge label for a pipe: "" (plain), "×2", "→ weapon" or "×2 → weapon" @@ -443,6 +487,9 @@ static func pipe_label(info: Dictionary) -> String: parts.append("×%d" % int(info["count"])) if str(info["save_as"]) != "": parts.append("→ " + str(info["save_as"])) + var wv: Dictionary = info.get("with", {}) + for k: String in wv: + parts.append("%s=%s" % [k, wv[k]]) return " ".join(parts) diff --git a/tests/test_builder.gd b/tests/test_builder.gd new file mode 100644 index 0000000..08f204e --- /dev/null +++ b/tests/test_builder.gd @@ -0,0 +1,220 @@ +extends SceneTree +## Headless checks for Builder (docs/PLAIN.md §2): effect and condition models +## that round-trip exactly with the stored text, the cases that don't fit a +## builder (ok: false), and known_values(). +## Run: godot --headless --path . -s res://tests/test_builder.gd + +var _failures := 0 + + +func _init() -> void: + _test_parse_effect() + _test_effect_round_trips() + _test_effect_not_ok() + _test_parse_condition() + _test_condition_round_trips() + _test_condition_not_ok() + _test_known_values() + print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures]) + quit(1 if _failures else 0) + + +func _eq(got: Variant, want: Variant, what: String) -> void: + if typeof(got) != typeof(want) or got != want: + _failures += 1 + print(" ✗ %s: got %s, want %s" % [what, JSON.stringify(got), JSON.stringify(want)]) + + +func _check(ok: bool, what: String) -> void: + if not ok: + _failures += 1 + print(" ✗ ", what) + + +# ---------------------------------------------------------------- effects + +func _test_parse_effect() -> void: + _eq(Builder.parse_effect("@luck -= 1"), {"ok": true, "op": "subtract", "var": "@luck", "amount": "1"}, "subtract") + _eq(Builder.parse_effect("@Luck+=1"), {"ok": true, "op": "add", "var": "@luck", "amount": "1"}, "add, tight, lowercased") + _eq(Builder.parse_effect("@str = 2d6"), {"ok": true, "op": "set", "var": "@str", "amount": "2d6"}, "set dice") + _eq(Builder.parse_effect("@town = \"Millbrook\""), {"ok": true, "op": "set", "var": "@town", "amount": "\"Millbrook\""}, "set text") + _eq(Builder.parse_effect("@age *= 2"), {"ok": true, "op": "multiply", "var": "@age", "amount": "2"}, "multiply") + _eq(Builder.parse_effect("@age /= 2"), {"ok": true, "op": "divide", "var": "@age", "amount": "2"}, "divide") + _eq(Builder.parse_effect("reset @skill_*"), {"ok": true, "op": "reset", "var": "@skill_*", "amount": ""}, "reset prefix") + _eq(Builder.parse_effect("reset @luck"), {"ok": true, "op": "reset", "var": "@luck", "amount": ""}, "reset") + _eq(Builder.parse_effect("@traits += \"Psionic\""), {"ok": true, "op": "append", "var": "@traits", "amount": "Psionic"}, "append") + _eq(Builder.parse_effect("@traits -= 'Psionic'"), {"ok": true, "op": "remove", "var": "@traits", "amount": "Psionic"}, "remove") + _eq(Builder.parse_effect("@contacts += option_label"), {"ok": true, "op": "add", "var": "@contacts", "amount": "option_label"}, "add a chain value") + _eq(Builder.parse_effect("@[option] += 1"), {"ok": true, "op": "add", "var": "@[option]", "amount": "1"}, "indirect") + _eq(Builder.parse_effect("reset @[ option ]"), {"ok": true, "op": "reset", "var": "@[option]", "amount": ""}, "indirect reset") + _eq(Builder.parse_effect("@skill_vacc = max(@skill_vacc, 0)"), + {"ok": true, "op": "set", "var": "@skill_vacc", "amount": "max(@skill_vacc, 0)"}, "set expression") + _eq(Builder.parse_effect("hero = \"Bob\""), {"ok": true, "op": "set", "var": "hero", "amount": "\"Bob\""}, "chain target") + _eq(Builder.effect_text({"op": "add", "var": "@luck", "amount": "1"}), "@luck += 1", "effect_text add") + _eq(Builder.effect_text({"op": "append", "var": "@traits", "amount": "Psionic"}), "@traits += \"Psionic\"", "effect_text append") + _eq(Builder.effect_text({"op": "reset", "var": "@skill_*"}), "reset @skill_*", "effect_text reset") + _eq(Builder.effect_text({"op": "bogus", "var": "@x", "amount": "1"}), "", "effect_text bad op") + _eq(Builder.effect_text({"op": "set", "var": "@x", "amount": ""}), "", "effect_text no amount") + var list := Builder.parse_effects("@a += 1; @b = \"x;y\"\nnonsense") + _eq(list.size(), 3, "parse_effects splits") + _eq(str(list[1]["amount"]), "\"x;y\"", "a ; inside quotes stays") + _check(not list[2]["ok"] and list[2]["src"] == "nonsense", "bad statement kept with src") + + +func _test_effect_round_trips() -> void: + var models := [ + {"ok": true, "op": "set", "var": "@str", "amount": "2d6"}, + {"ok": true, "op": "set", "var": "@town", "amount": "\"Millbrook\""}, + {"ok": true, "op": "set", "var": "@x", "amount": "-1"}, + {"ok": true, "op": "set", "var": "@x", "amount": "if(@a > 1, 2, 3)"}, + {"ok": true, "op": "add", "var": "@luck", "amount": "1"}, + {"ok": true, "op": "add", "var": "@credits", "amount": "1d6 * 1000"}, + {"ok": true, "op": "subtract", "var": "@luck", "amount": "1"}, + {"ok": true, "op": "multiply", "var": "@age", "amount": "2"}, + {"ok": true, "op": "divide", "var": "@age", "amount": "3"}, + {"ok": true, "op": "reset", "var": "@luck", "amount": ""}, + {"ok": true, "op": "reset", "var": "@skill_*", "amount": ""}, + {"ok": true, "op": "reset", "var": "@[option]", "amount": ""}, + {"ok": true, "op": "append", "var": "@traits", "amount": "Psionic"}, + {"ok": true, "op": "append", "var": "@traits", "amount": "Said \"hi\""}, + {"ok": true, "op": "append", "var": "@traits", "amount": "a\\b"}, + {"ok": true, "op": "remove", "var": "@traits", "amount": "Old Bill"}, + {"ok": true, "op": "add", "var": "@[option]", "amount": "1"}, + {"ok": true, "op": "set", "var": "@[\"skill_\" + option]", "amount": "max(@[\"skill_\" + option], 0)"}, + {"ok": true, "op": "add", "var": "count", "amount": "1"}, + {"ok": true, "op": "add", "var": "@contacts", "amount": "option_label"}, + ] + for m: Dictionary in models: + var text := Builder.effect_text(m) + _eq(Builder.parse_effect(text), m, "round trip %s" % text) + # Text -> model -> text normalizes spacing only. + for src: String in ["@luck-=1", "@str=2d6", "reset @skill_*", "@traits+=\"X\""]: + var m := Builder.parse_effect(src) + var again := Builder.parse_effect(Builder.effect_text(m)) + _eq(again, m, "text round trip %s" % src) + var r1 := Effects.run(src, RollContext.new({}), "") + _check(r1.size() == 1, "runs: %s" % src) + + +func _test_effect_not_ok() -> void: + for src: String in ["", "hello", "@x += (", "@x ==", "reset luck", "reset @x @y", "@[option += 1", "@x += ", "3 = @x", "@[ ] = 1"]: + var m := Builder.parse_effect(src) + _check(not m["ok"], "not ok: \"%s\" gave %s" % [src, m]) + _check(str(m.get("error", "")) != "", "error text for \"%s\"" % src) + + +# ---------------------------------------------------------------- conditions + +func _test_parse_condition() -> void: + _eq(Builder.parse_condition("@str >= 8"), {"ok": true, "join": "and", "clauses": [{"var": "@str", "cmp": "ge", "value": "8"}]}, "ge") + _eq(Builder.parse_condition("@x = 0 and @soc >= 9"), {"ok": true, "join": "and", "clauses": [ + {"var": "@x", "cmp": "eq", "value": "0"}, {"var": "@soc", "cmp": "ge", "value": "9"}]}, "and") + _eq(Builder.parse_condition("@a == 1 || @b != @c"), {"ok": true, "join": "or", "clauses": [ + {"var": "@a", "cmp": "eq", "value": "1"}, {"var": "@b", "cmp": "ne", "value": "@c"}]}, "|| and ==") + _eq(Builder.parse_condition("has(@traits, \"Psionic\")"), {"ok": true, "join": "and", "clauses": [ + {"var": "@traits", "cmp": "has", "value": "\"Psionic\""}]}, "has") + _eq(Builder.parse_condition("@commissioned"), {"ok": true, "join": "and", "clauses": [{"var": "@commissioned", "cmp": "set", "value": ""}]}, "set") + _eq(Builder.parse_condition("not @x"), {"ok": true, "join": "and", "clauses": [{"var": "@x", "cmp": "unset", "value": ""}]}, "unset") + _eq(Builder.parse_condition("!@x"), {"ok": true, "join": "and", "clauses": [{"var": "@x", "cmp": "unset", "value": ""}]}, "! unset") + _eq(Builder.parse_condition("@luck < -1"), {"ok": true, "join": "and", "clauses": [{"var": "@luck", "cmp": "lt", "value": "-1"}]}, "negative") + _eq(Builder.parse_condition("option_value > 2.5"), {"ok": true, "join": "and", "clauses": [{"var": "option_value", "cmp": "gt", "value": "2.5"}]}, "chain var") + _eq(Builder.parse_condition("@[option] <= tier"), {"ok": true, "join": "and", "clauses": [{"var": "@[option]", "cmp": "le", "value": "tier"}]}, "indirect and chain value") + _eq(Builder.parse_condition(" "), {"ok": true, "join": "and", "clauses": []}, "empty") + _eq(Builder.condition_text({"join": "or", "clauses": [{"var": "@a", "cmp": "eq", "value": "1"}, {"var": "@b", "cmp": "set", "value": ""}]}), + "@a = 1 or @b", "condition_text") + _eq(Builder.condition_text({"join": "and", "clauses": []}), "", "condition_text empty") + _eq(Builder.condition_text({"join": "and", "clauses": [{"var": "@a", "cmp": "zz", "value": "1"}]}), "", "condition_text bad cmp") + + +func _test_condition_round_trips() -> void: + var models := [ + {"ok": true, "join": "and", "clauses": []}, + {"ok": true, "join": "and", "clauses": [{"var": "@str", "cmp": "ge", "value": "8"}]}, + {"ok": true, "join": "and", "clauses": [{"var": "@str", "cmp": "le", "value": "-3"}]}, + {"ok": true, "join": "and", "clauses": [{"var": "@str", "cmp": "gt", "value": "@dex"}]}, + {"ok": true, "join": "and", "clauses": [{"var": "@str", "cmp": "lt", "value": "2.5"}]}, + {"ok": true, "join": "and", "clauses": [{"var": "@species", "cmp": "eq", "value": "\"Aslan\""}]}, + {"ok": true, "join": "and", "clauses": [{"var": "@species", "cmp": "ne", "value": "'Vargr'"}]}, + {"ok": true, "join": "and", "clauses": [{"var": "@traits", "cmp": "has", "value": "\"Psionic\""}]}, + {"ok": true, "join": "and", "clauses": [{"var": "@traits", "cmp": "has", "value": "option"}]}, + {"ok": true, "join": "and", "clauses": [{"var": "@commissioned", "cmp": "set", "value": ""}]}, + {"ok": true, "join": "and", "clauses": [{"var": "@commissioned", "cmp": "unset", "value": ""}]}, + {"ok": true, "join": "and", "clauses": [{"var": "@x", "cmp": "eq", "value": "true"}]}, + {"ok": true, "join": "or", "clauses": [{"var": "@a", "cmp": "eq", "value": "1"}, {"var": "@b", "cmp": "ne", "value": "2"}, + {"var": "tier", "cmp": "ge", "value": "3"}]}, + {"ok": true, "join": "and", "clauses": [{"var": "@[option]", "cmp": "ge", "value": "1"}, {"var": "option_value", "cmp": "lt", "value": "@cap"}]}, + ] + for m: Dictionary in models: + var text := Builder.condition_text(m) + _eq(Builder.parse_condition(text), m, "round trip \"%s\"" % text) + if text != "": + _eq(Expr.check(text), "", "parses as an expression: %s" % text) + for src: String in ["@str>=8", "@a==1 and @b=2", "has( @t ,\"x\" )", "!@x", "@a = 1 && @b = 2"]: + var m := Builder.parse_condition(src) + _check(m["ok"], "ok: %s" % src) + _eq(Builder.parse_condition(Builder.condition_text(m)), m, "text round trip %s" % src) + + +func _test_condition_not_ok() -> void: + for src: String in ["@a = 1 and @b = 2 or @c = 3", "(@a = 1)", "count(@skill_*) > 0", "1d6 >= 4", "@a + 1 > 2", + "8 <= @str", "@x = \"open", "max(@a, 1) > 2", "@a >", "@a = 1 and", "not has(@t, \"x\")", "@a = 2d6", "has(@t)"]: + var m := Builder.parse_condition(src) + _check(not m["ok"], "not ok: \"%s\" gave %s" % [src, m]) + + +# ---------------------------------------------------------------- known_values + +func _test_known_values() -> void: + var b := TowerBoard.new() + var luck := RollTable.create(RollTable.KIND_VARIABLE, "v_luck", "Luck") + luck.var_name = "luck" + b.tables.append(luck) + var town := RollTable.create(RollTable.KIND_VARIABLE, "v_town", "Home Town", "text") + town.var_name = "town" + b.tables.append(town) + b.tables.append(RollTable.create(RollTable.KIND_VARIABLE, "v_skills", "Skills", "collection")) + var start := RollTable.new("start", "Start") + var e := TableEntry.new("e1", "[[Names -> hero]]") + e.effects = "@skill_pilot += 1; @traits += \"Psionic\"; @credits = 100; @luck -= 1; @[option] += 1; reset @x_*" + e.add_pipe("tier", 1, "@weapon") + e.set_pipe_when("tier", "@str >= 8") + e.set_pipe_with("tier", {"tier": "@level + 1"}) + start.entries.append(e) + b.tables.append(start) + var tier := RollTable.create(RollTable.KIND_CHECK, "tier", "Tier") + tier.inputs = [{"name": "tier", "label": "Tier", "default": "1"}] + b.tables.append(tier) + var ask := RollTable.create(RollTable.KIND_CHOICE, "ask", "How many", "number") + ask.save_as = "@terms" + b.tables.append(ask) + var vals := Builder.known_values(b) + var by := {} + var order: Array = [] + for v: Dictionary in vals: + by[v["name"]] = v + order.append(v["name"]) + for k in ["name", "label", "kind", "source"]: + _check(v.has(k), "%s has %s" % [v.get("name"), k]) + _eq(order.slice(0, 3), ["@luck", "@town", "@skill_*"], "variable cards first, then collections") + _eq(by["@luck"], {"name": "@luck", "label": "Luck", "kind": "number", "source": "variable", "table_id": "v_luck"}, "a variable card") + _eq(by["@town"]["kind"], "text", "text variable") + _eq(by["@town"]["label"], "Home Town", "label from the card") + _eq(by["@skill_*"]["kind"], "collection", "collection kind") + _eq(by["@skill_*"]["label"], "Skills", "collection label") + _eq(by["@skill_pilot"]["label"], "Pilot", "member label") + _eq(by["@skill_pilot"]["collection"], "@skill_*", "member knows its collection") + _eq(by["@skill_pilot"]["source"], "effect", "effect target") + _eq(by["@traits"]["kind"], "list", "append makes a list") + _eq(by["@credits"]["kind"], "number", "number effect") + _eq(by["@weapon"]["source"], "save_as", "pipe save_as") + _eq(by["hero"]["source"], "save_as", "[[ -> hero]] save") + _eq(by["@terms"]["kind"], "number", "number choice save_as") + _eq(by["tier"]["source"], "input", "card input") + _eq(by["tier"]["label"], "Tier", "input label") + _eq(by["@str"]["source"], "read", "value only read") + _eq(by["@level"]["source"], "read", "value read by a with") + _check(by.has("answer") and by["answer"]["source"] == "chain", "answer from a number choice") + _check(by.has("nat") and by.has("total") and by.has("effect"), "check chain names") + _check(not by.has("i") and not by.has("option"), "no loop, no dynamic pick") + _check(not by.has("@[option]") and not by.has("@x_*"), "no indirect or prefix targets") + _eq(Builder.known_values(null), [] as Array[Dictionary], "null board") diff --git a/tests/test_builder.gd.uid b/tests/test_builder.gd.uid new file mode 100644 index 0000000..541b13a --- /dev/null +++ b/tests/test_builder.gd.uid @@ -0,0 +1 @@ +uid://02r1wlwv3fsf diff --git a/tests/test_check_inputs.gd b/tests/test_check_inputs.gd new file mode 100644 index 0000000..2c226c3 --- /dev/null +++ b/tests/test_check_inputs.gd @@ -0,0 +1,665 @@ +extends SceneTree +## 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 + +var _failures := 0 + + +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() + print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures]) + quit(1 if _failures else 0) + + +# ---------------------------------------------------------------- helpers + +func _eq(got: Variant, want: Variant, what: String) -> void: + if typeof(got) != typeof(want) or got != want: + _failures += 1 + print(" ✗ %s: got %s, want %s" % [what, JSON.stringify(got), JSON.stringify(want)]) + + +func _check(ok: bool, what: String) -> void: + if not ok: + _failures += 1 + print(" ✗ ", what) + + +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 pipes, 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 pipes 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 pipe)", "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", "Loop") + 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"], "router 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"], "router 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"], "router 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("Pipe 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", "collection 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"], "collection 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 collection") + # 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", "collection 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"}}], "pipe 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("Pipe 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 pipe 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 pipe 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 board") diff --git a/tests/test_check_inputs.gd.uid b/tests/test_check_inputs.gd.uid new file mode 100644 index 0000000..baaaaa7 --- /dev/null +++ b/tests/test_check_inputs.gd.uid @@ -0,0 +1 @@ +uid://i7gun1udginh diff --git a/tests/test_describe.gd b/tests/test_describe.gd new file mode 100644 index 0000000..8e15190 --- /dev/null +++ b/tests/test_describe.gd @@ -0,0 +1,356 @@ +extends SceneTree +## Headless checks for Describe (docs/PLAIN.md §1 and §3): plain phrases for +## every effect op, the condition forms, dice, dynamic options, pipes, check +## cards and why facts, with labels from variable cards, collections and card +## inputs, and the fallbacks to the original text. +## Run: godot --headless --path . -s res://tests/test_describe.gd + +var _failures := 0 + + +func _init() -> void: + _test_labels() + _test_effects() + _test_conditions() + _test_dice() + _test_options() + _test_pipes() + _test_check() + _test_why_facts() + _test_why_from_rolls() + _test_fallbacks() + _test_rules_view() + print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures]) + quit(1 if _failures else 0) + + +# ---------------------------------------------------------------- helpers + +func _eq(got: Variant, want: Variant, what: String) -> void: + if typeof(got) != typeof(want) or got != want: + _failures += 1 + print(" ✗ %s: got %s, want %s" % [what, JSON.stringify(got), JSON.stringify(want)]) + + +func _check(ok: bool, what: String) -> void: + if not ok: + _failures += 1 + print(" ✗ ", what) + + +func _var_card(id: String, name: String, var_name: String, type: String = "number") -> RollTable: + var t := RollTable.create(RollTable.KIND_VARIABLE, id, name, type) + t.var_name = var_name + return t + + +func _one(id: String, name: String = "") -> RollTable: + var t := RollTable.new(id, name if name != "" else id.capitalize()) + t.entries.append(TableEntry.new("e1", "x")) + return t + + +## A board with labelled values: Strength (@str), Social Standing (@soc), Luck +## (@luck), Town (@town, text), Traits (@traits, list), the Skills collection +## (@skill_*), and Tier 3 / Weapons tables. Tier 3 declares the input tier +## ("Tier"). +func _board() -> TowerBoard: + var b := TowerBoard.new() + b.id = "describe" + b.tables.append(_var_card("v_str", "Strength", "str")) + b.tables.append(_var_card("v_soc", "Social Standing", "soc")) + b.tables.append(_var_card("v_luck", "Luck", "luck")) + b.tables.append(_var_card("v_town", "Town", "town", "text")) + b.tables.append(_var_card("v_traits", "Traits", "traits", "list")) + b.tables.append(RollTable.create(RollTable.KIND_VARIABLE, "v_skills", "Skills", "collection")) + var tier := _one("tier3", "Tier 3") + tier.inputs = [{"name": "tier", "label": "Tier", "default": "1"}] + b.tables.append(tier) + b.tables.append(_one("weapons", "[b]Weapons[/b]")) + return b + + +# ---------------------------------------------------------------- labels + +func _test_labels() -> void: + var b := _board() + _eq(b.get_table("v_skills").var_name, "skill", "a collection's stem drops the final s") + _eq(Describe.label("@str", b), "Strength", "variable card label") + _eq(Describe.label("@STR", b), "Strength", "labels ignore case") + _eq(Describe.label("@skill_gun_combat", b), "Gun Combat", "collection member label") + _eq(Describe.label("@skill_*", b), "Skills", "collection label") + _eq(Describe.label("@contact_*", b), "Contact values", "a prefix without a collection") + _eq(Describe.label("@soc_x", b), "Soc X", "no collection: pretty name") + _eq(Describe.label("@dex", b), "Dex", "unlabelled value") + _eq(Describe.label("tier", b), "Tier", "input label") + _eq(Describe.label("answer", b), "Answer", "chain label") + _eq(Describe.label("nat", b), "Natural roll", "nat label") + _eq(Describe.label("@[option]", b), "Chosen value", "indirect label") + _eq(Describe.label("@str", null), "Str", "no board") + # The variable card wins over a collection. + b.tables.append(_var_card("v_pilot", "Piloting", "skill_pilot")) + _eq(Describe.label("@skill_pilot", b), "Piloting", "card label before collection") + # A collection doesn't declare its stem as a variable. + var ctx := Roller.new_context(b, RandomNumberGenerator.new(), {}) + _check(ctx.declared("skill") == null, "a collection isn't a declared variable") + _check(ctx.declared("str") != null, "a number card is") + + +# ---------------------------------------------------------------- effects + +func _test_effects() -> void: + var b := _board() + _eq(Describe.effect("@luck -= 1", b), "Luck −1", "subtract") + _eq(Describe.effect("@skill_pilot += 1", b), "Pilot +1", "add to a collection member") + _eq(Describe.effect("@luck += -2", b), "Luck −2", "add a negative") + _eq(Describe.effect("@luck -= -2", b), "Luck +2", "subtract a negative") + _eq(Describe.effect("@town = \"Millbrook\"", b), "Town = Millbrook", "set text") + _eq(Describe.effect("@str = 2d6", b), "Strength = 2D", "set dice") + _eq(Describe.effect("@str = 2d6 + dm(@soc)", b), "Strength = 2D + Social Standing modifier", "set expression") + _eq(Describe.effect("@credits += 1d6 * 1000", b), "Credits + 1D × 1000", "add expression") + _eq(Describe.effect("@age *= 2", b), "Age ×2", "multiply") + _eq(Describe.effect("@age /= 2", b), "Age ÷2", "divide") + _eq(Describe.effect("@traits += \"Psionic\"", b), "Add Psionic to Traits", "append") + _eq(Describe.effect("@traits -= \"Psionic\"", b), "Remove Psionic from Traits", "remove") + _eq(Describe.effect("reset @skill_*", b), "Clear all Skills", "reset a collection") + _eq(Describe.effect("reset @contact_*", b), "Clear all Contact values", "reset a prefix") + _eq(Describe.effect("reset @luck", b), "Reset Luck", "reset a declared value") + _eq(Describe.effect("reset @dex", b), "Clear Dex", "reset an undeclared value") + _eq(Describe.effect("@[option] += 1", b), "Chosen value +1", "indirect, no card") + var pick := RollTable.create(RollTable.KIND_CHOICE, "raise", "Raise a skill", "pick") + pick.options_from = "@skill_*" + _eq(Describe.effect("@[option] += 1", b, pick), "Chosen skill +1", "indirect on a skills card") + pick.options_from = "@contacts" + _eq(Describe.effect("@[option] += 1", b, pick), "Chosen value +1", "indirect outside a collection") + _eq(Describe.effect("hero = \"Bob\"", b), "Hero = Bob", "chain target") + _eq(Describe.effects("@luck -= 1; @str = 7\nreset @skill_*", b), ["Luck −1", "Strength = 7", "Clear all Skills"] as Array[String], "effects field") + + +# ---------------------------------------------------------------- conditions + +func _test_conditions() -> void: + var b := _board() + _eq(Describe.condition("@str >= 8", b), "Strength is 8 or more", "ge number") + _eq(Describe.condition("@str >= @soc", b), "Strength is at least Social Standing", "ge value") + _eq(Describe.condition("@str <= 3", b), "Strength is at most 3", "le") + _eq(Describe.condition("@str > 3", b), "Strength is more than 3", "gt") + _eq(Describe.condition("@str < 3", b), "Strength is less than 3", "lt") + _eq(Describe.condition("@str != 0", b), "Strength is not 0", "ne") + _eq(Describe.condition("@town == \"Aslan\"", b), "Town is Aslan", "eq text") + _eq(Describe.condition("@x = 0 and @soc >= 9", b), "X is 0 and Social Standing is 9 or more", "and") + _eq(Describe.condition("@x = 0 or @luck < -1", b), "X is 0 or Luck is less than −1", "or, negative") + _eq(Describe.condition("has(@traits, \"Psionic\")", b), "Traits include Psionic", "has") + _eq(Describe.condition("@commissioned", b), "Commissioned is set", "set") + _eq(Describe.condition("not @commissioned", b), "Commissioned is not set", "unset") + _eq(Describe.condition("option_value >= 1", b), "Chosen value is 1 or more", "chain value") + _eq(Describe.condition("tier = 3", b), "Tier is 3", "input") + _eq(Describe.condition("@skill_pilot >= 1", b), "Pilot is 1 or more", "collection member") + _eq(Describe.condition("", b), "", "empty") + + +# ---------------------------------------------------------------- dice + +func _test_dice() -> void: + var b := _board() + _eq(Describe.dice("2d6 + dm(@str)", b), "2D + Strength modifier", "2D + modifier") + _eq(Describe.dice("1d6 + tier", b), "1D + Tier", "input in dice") + _eq(Describe.dice("d20", b), "d20", "d20") + _eq(Describe.dice("3d8 - 2", b), "3d8 − 2", "3d8 − 2") + _eq(Describe.dice("2D", b), "2D", "2D") + _eq(Describe.dice("@terms", b), "Terms", "a value") + _eq(Describe.dice("-1", b), "−1", "negative number") + _eq(Describe.dice("max(@str, 3)", b), "max(Strength, 3)", "function call") + _eq(Describe.dice("(1d6 + 1) * 10", b), "(1D + 1) × 10", "parentheses") + _eq(Describe.dice("count(@skill_*)", b), "count(Skills)", "prefix argument") + + +# ---------------------------------------------------------------- options + +func _test_options() -> void: + var b := _board() + var t := RollTable.create(RollTable.KIND_CHOICE, "raise", "Raise", "pick") + _eq(Describe.options(t, b), "", "fixed card") + t.options_from = "@skill_*" + _eq(Describe.options(t, b), "your Skills", "collection source") + t.options_where = "option_value >= 1" + _eq(Describe.options(t, b), "your Skills, level 1 or more", "level filter") + t.options_where = "option != @last" + _eq(Describe.options(t, b), "your Skills, where Chosen option is not Last", "other filter") + t.options_where = "" + t.options_from = "@contact_*" + _eq(Describe.options(t, b), "your Contact values", "prefix without collection") + t.options_from = "@traits" + _eq(Describe.options(t, b), "your Traits", "list source") + t.options_from = "skills" + _eq(Describe.options(t, b), "skills", "bad pattern falls back") + + +# ---------------------------------------------------------------- pipes + +func _test_pipes() -> void: + var b := _board() + var e := TableEntry.new("e1", "x") + e.add_pipe("tier3") + _eq(Describe.pipe(e, "tier3", b), "", "plain pipe") + e.set_pipe_with("tier3", {"tier": "3"}) + e.set_pipe_when("tier3", "@luck >= 2") + _eq(Describe.pipe(e, "tier3", b), "Tier 3 · only if Luck is 2 or more", "input and condition") + e.add_pipe("weapons", 2, "@weapon") + _eq(Describe.pipe(e, "weapons", b), "×2 · saves Weapon", "count and save") + e.set_pipe_otherwise("weapons", true) + _eq(Describe.pipe(e, "weapons", b), "otherwise · ×2 · saves Weapon", "otherwise") + e.set_pipe_count("weapons", "@terms") + _eq(Describe.pipe(e, "weapons", b), "otherwise · ×Terms · saves Weapon", "expression count") + + +# ---------------------------------------------------------------- check + +func _test_check() -> void: + var b := _board() + var t := RollTable.create(RollTable.KIND_CHECK, "c", "Check") + _eq(Describe.check(t, b), "Roll 2D, need 8 or more", "default check") + t.check_mod = "dm(@str)" + _eq(Describe.check(t, b), "Roll 2D + Strength modifier, need 8 or more", "with modifier") + t.check_cmp = "le" + t.check_target = "@soc" + t.check_mod = "-1" + _eq(Describe.check(t, b), "Roll 2D − 1, need at most Social Standing", "roll-under, value target") + _eq(Describe.check(_one("r"), b), "", "not a check") + + +# ---------------------------------------------------------------- why + +func _test_why_facts() -> void: + var b := _board() + var W := func(f: Dictionary, plain: bool = true) -> String: return Describe.why(f, b, plain) + _eq(W.call({"type": "when", "to": "tier3", "expr": "@luck >= 2", "values": {"@luck": 1}, "result": false}), + "Skipped Tier 3 because Luck was 1 (needs 2 or more)", "when false") + _eq(W.call({"type": "when", "to": "tier3", "expr": "@luck >= 2", "values": {"@luck": 3}, "result": true}), + "Took Tier 3 because Luck was 3 (needs 2 or more)", "when true") + _eq(W.call({"type": "when", "to": "tier3", "expr": "@luck >= 2", "values": {"@luck": null}, "result": false}), + "Skipped Tier 3 because Luck wasn't set (needs 2 or more)", "when unset") + _eq(W.call({"type": "when", "to": "tier3", "expr": "@x = 0 and @soc >= 9", "values": {"@x": 0, "@soc": 5}, "result": false}), + "Skipped Tier 3 because X was 0 and Social Standing was 5 (rule: X is 0 and Social Standing is 9 or more)", "when, two values") + _eq(W.call({"type": "when", "to": "tier3", "expr": "1d6 >= 4", "values": {}, "result": true}), + "Took Tier 3: 1d6 >= 4 was true", "when without values") + _eq(W.call({"type": "when", "to": "tier3", "expr": "@x >", "values": {}, "result": false, "error": "Expected value"}), + "Skipped Tier 3: its condition couldn't be worked out (Expected value)", "when error") + _eq(W.call({"type": "when", "to": "tier3", "expr": "@luck >= 2", "values": {"@luck": 1}, "result": false}, false), + "Skipped tier3: when @luck >= 2 was false (@luck = 1)", "when, text mode") + _eq(W.call({"type": "otherwise", "to": "weapons", "result": true}), "Took Weapons because no condition was true", "otherwise ran") + _eq(W.call({"type": "otherwise", "to": "weapons", "result": false}), "Skipped Weapons because a condition was true", "otherwise skipped") + _eq(W.call({"type": "case", "index": 0, "expr": "@str >= 10", "values": {"@str": 7}, "result": false}), + "Case 1 didn't match because Strength was 7 (needs 10 or more)", "case false") + _eq(W.call({"type": "case", "index": 1, "expr": "has(@traits, \"Psionic\")", "values": {"@traits": "Psionic"}, "result": true}), + "Case 2 matched because Traits was Psionic (needs to include Psionic)", "case true") + _eq(W.call({"type": "case", "index": 2, "expr": "", "values": {}, "result": true}), + "Otherwise (case 3): no case before it matched", "otherwise case") + _eq(W.call({"type": "roll", "pick": "dice", "dice": "2d6", "faces": [3, 4], "nat": 7, "mod": 0, "total": 7}), + "Rolled 3 + 4 = 7", "roll") + _eq(W.call({"type": "roll", "pick": "dice", "dice": "2d6 + 1", "faces": [3.0, 4.0], "nat": 7.0, "mod": 1.0, "total": 8.0}), + "Rolled 3 + 4 = 7, +1 = 8", "roll with modifier (JSON floats)") + _eq(W.call({"type": "roll", "pick": "dice", "dice": "@terms", "faces": [], "total": 3}), "Worked out 3", "expression roll") + _eq(W.call({"type": "roll", "pick": "weighted", "dice": "d6", "total": 4}), "Rolled 4 on d6", "weighted") + _eq(W.call({"type": "roll", "pick": "card", "dice": "d6", "total": 4}), "Drew card 4", "card") + _eq(W.call({"type": "check", "dice": "2d6", "mod_expr": "dm(@str)", "target_expr": "8", "faces": [5, 1], "nat": 6, "mod": 1, + "total": 7, "target": 8, "cmp": "ge", "success": false}), "Rolled 5 + 1 = 6, +1 = 7: needed 8 or more, failure", "check") + _eq(W.call({"type": "check", "dice": "2d6", "mod_expr": "", "target_expr": "8", "faces": [6, 6], "nat": 12, "mod": 0, + "total": 12, "target": 8, "cmp": "le", "success": false}, false), "check 2d6 vs 8 (le): 12 +0 = 12 → failure", "check text mode") + _eq(W.call({"type": "effect", "var": "@luck", "op": "-=", "before": 2, "after": 1}), "Luck went from 2 to 1", "effect") + _eq(W.call({"type": "effect", "var": "@skill_pilot", "op": "+=", "before": null, "after": 1}), "Pilot became 1", "effect from unset") + _eq(W.call({"type": "effect", "var": "@dex", "op": "reset", "before": 4, "after": null}), "Dex was cleared", "reset effect") + _eq(W.call({"type": "effect", "var": "@skill_*", "op": "reset", "count": 3}), "Cleared all Skills (3)", "prefix reset") + _eq(W.call({"type": "effect", "var": "@luck", "op": "-=", "before": 2, "after": 1}, false), "@luck -=: 2 → 1", "effect text mode") + _eq(W.call({"type": "input", "name": "tier", "value": 3, "from": "pipe"}), "Tier was 3 (from the pipe)", "input") + _eq(W.call({"type": "input", "name": "tier", "value": 1, "from": "default"}), "Tier was 1 (default)", "input default") + _eq(W.call({"type": "show_if", "hidden": 2, "chosen_hidden": false}), "2 options hidden by their conditions", "show_if") + _eq(W.call({"type": "options_where", "from": "@skill_*", "expr": "option_value >= 1", "kept": 3, "total": 5}), + "Offered 3 of 5 Skills (level 1 or more)", "options_where") + _check(W.call({"type": "mystery", "x": 1}).contains("mystery"), "unknown facts give a dump") + + +## Facts recorded by a real roll come out as sentences, and survive JSON. +func _test_why_from_rolls() -> void: + var b := _board() + var start := RollTable.new("start", "Start") + var e := TableEntry.new("e1", "go") + e.effects = "@luck -= 1" + e.add_pipe("tier3") + e.set_pipe_when("tier3", "@luck >= 2") + e.add_pipe("weapons") + e.set_pipe_otherwise("weapons", true) + start.entries.append(e) + b.tables.append(start) + var vars := {"luck": {"value": 2, "source": ""}} + var ctx := Roller.new_context(b, RandomNumberGenerator.new(), vars) + var tree := Roller.roll(b, "start", ctx.rng, 0, {}, ctx) + var steps := Roller.flatten(tree) + var why: Array = steps[0].get("why", []) + var sentences: Array = [] + for f: Dictionary in why: + sentences.append(Describe.why(f, b)) + _check(sentences.has("Luck went from 2 to 1"), "effect fact from a roll: %s" % [sentences]) + _check(sentences.has("Skipped Tier 3 because Luck was 1 (needs 2 or more)"), "when fact from a roll: %s" % [sentences]) + _check(sentences.has("Took Weapons because no condition was true"), "otherwise fact from a roll: %s" % [sentences]) + var back: Variant = JSON.parse_string(JSON.stringify(steps)) + var why2: Array = (back as Array)[0]["why"] + var again: Array = [] + for f: Dictionary in why2: + again.append(Describe.why(f, b)) + _eq(again, sentences, "facts survive JSON") + + +# ---------------------------------------------------------------- fallbacks + +func _test_fallbacks() -> void: + var b := _board() + _eq(Describe.effect("this is not a statement", b), "this is not a statement", "bad effect") + _eq(Describe.effect("@x += (", b), "@x += (", "bad amount") + _eq(Describe.condition("count(@skill_*) > 0", b), "count(@skill_*) > 0", "function condition") + _eq(Describe.condition("@a = 1 and @b = 2 or @c = 3", b), "@a = 1 and @b = 2 or @c = 3", "mixed and/or") + _eq(Describe.condition("(@a = 1)", b), "(@a = 1)", "parentheses") + _eq(Describe.condition("1d6 >= 4", b), "1d6 >= 4", "dice condition") + _eq(Describe.dice("2d6 +* \"", b), "2d6 +* \"", "unclosed quote") + _eq(Describe.dice("", b), "", "empty dice") + var long := "@a = 1 and @bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb = 2 and @cccccccccccccccccccccccccccccccccccccccc = 3" + _check(Describe.condition(long, b).length() <= Describe.MAX_LEN + 20, "long phrases stay short") + var huge := "" + for k in 30: + huge += "@v%d = %d and " % [k, k] + huge += "@z = 1" + _check(Describe.condition(huge, b).length() <= Describe.MAX_LEN, "very long phrases are cut") + _check(Describe.why({}, b) != null, "empty fact") + _eq(Describe.pipe(null, "x", b), "", "no entry") + _eq(Describe.options(null, b), "", "no table") + # Odd input never crashes and never comes back empty. + for junk: String in ["@", "@[", "@[]", "\"", "((((", "1d", "d", "2x", "@a +", "- - 1", "@a = = 1", "has(", "not", + "and", "@a and", "@[x] = 1 and @[", "€ = 1", "@skill_* += 1", "reset", "reset @", "@a /= 0", ",,,", "1..2", "]["]: + _check(Describe.effect(junk, b) != "", "effect junk: %s" % junk) + _check(Describe.condition(junk, b) != "", "condition junk: %s" % junk) + _check(Describe.dice(junk, b) != "", "dice junk: %s" % junk) + Builder.parse_effect(junk) + Builder.parse_condition(junk) + Describe.why({"type": "when", "to": junk, "expr": junk, "values": {junk: junk}, "result": true}, b) + Describe.why({"type": "case", "index": junk, "expr": junk, "values": junk}, b, false) + Describe.why({"type": "roll", "faces": junk, "total": junk, "mod": junk}, b) + Describe.why({"type": "check", "faces": [junk], "mod": junk}, b) + Describe.why({"type": "effect", "var": junk, "count": junk}, b) + + +# ---------------------------------------------------------------- display preference + +func _test_rules_view() -> void: + var dir := "user://test_describe_state" + var st := StateStore.new(dir) + st.reload() + st.set_setting(StateStore.RULES_VIEW, null) + _eq(st.rules_view(), "plain", "plain by default") + _check(st.rules_plain(), "rules_plain") + st.set_rules_view("text") + _eq(st.rules_view(), "text", "text") + st.set_rules_view("bogus") + _eq(st.rules_view(), "text", "bad values are ignored") + st.save() + _eq(StateStore.new(dir).rules_view(), "text", "kept in the state file") + st.set_rules_view("plain") + st.save() diff --git a/tests/test_describe.gd.uid b/tests/test_describe.gd.uid new file mode 100644 index 0000000..809d72a --- /dev/null +++ b/tests/test_describe.gd.uid @@ -0,0 +1 @@ +uid://bicuhdrq56on diff --git a/ui/table_settings_dialog.gd b/ui/table_settings_dialog.gd index 6a87191..a46b1fd 100644 --- a/ui/table_settings_dialog.gd +++ b/ui/table_settings_dialog.gd @@ -370,7 +370,7 @@ func _build_kind() -> void: _var_name.text_changed.connect(func(_t: String) -> void: _refresh()) box.add_child(field("Variable name (used as @name)", _var_name)) box.add_child(section("Type")) - box.add_child(segmented(["Number", "Text", "List"], RollTable.VAR_TYPES.find(_var_type), func(i: int) -> void: + box.add_child(segmented(["Number", "Text", "List", "Collection"], RollTable.VAR_TYPES.find(_var_type), func(i: int) -> void: _var_type = RollTable.VAR_TYPES[i] _refresh() ))