Compare commits

..

No commits in common. "adb93c545c9076346c64434a0be6253e0ed88305" and "6557998eee86cf8b08d36a006941618aa5b07861" have entirely different histories.

55 changed files with 417 additions and 8396 deletions

View file

@ -21,16 +21,9 @@ godot --path .
last few rolls. last few rolls.
- **Build mode** is for setting up tables. Edit names, results, weights and details in place, - **Build mode** is for setting up tables. Edit names, results, weights and details in place,
add or delete results and tables, and drag a card by its header. Drag from a result's ● add or delete results and tables, and drag a card by its header. Drag from a result's ●
onto another table to lay a pipe. The **inspector** docked on the right edits whatever is onto another table to lay a pipe. Click a pipe to set how many times it rolls, save its
selected: click a card's title (or its ⚙) for the card, a result's text for the result, or result as a variable, or remove it. The ⚙ on a card opens its settings: details, tags,
a pipe for the pipe. Results get fill-in rows for their changes ("Subtract [1] from plain or dice table (e.g. 2d6), and Card mode.
[Luck ▾]") and a box per pipe with its inputs, **Only if** conditions ("[Luck ▾] [is at
least ▾] [2]"), **Otherwise**, count and "saves as". Cards get their kind's fields (check
dice, modifier and target; choice options; loop rules; router cases; collection members;
inputs). Value dropdowns list the board's values with search and **+ New value…**. "Edit
as text" switches any builder to the rule text. **More settings…** opens the card's full
settings (Card mode and the rest). The top bar's **Plain / Text** switch shows rules in
plain words or as rule text. » hides the inspector.
- **Undo and redo:** every change to the board can be undone: typing, weights, effects, - **Undo and redo:** every change to the board can be undone: typing, weights, effects,
details and settings, adding and deleting results, cards and pipes, pipe options, moves, details and settings, adding and deleting results, cards and pipes, pipe options, moves,
groups, templates, Pack and Reset sample. **Ctrl+Z** undoes and **Ctrl+Shift+Z** or groups, templates, Pack and Reset sample. **Ctrl+Z** undoes and **Ctrl+Shift+Z** or
@ -47,8 +40,8 @@ godot --path .
`[[Names -> hero]]` (saves the result as `{hero}` for the rest of the roll). `{@town|Towns}` `[[Names -> hero]]` (saves the result as `{hero}` for the rest of the roll). `{@town|Towns}`
keeps a value across rolls until you clear it in the tray's Variables tab. BBCode such as keeps a value across rolls until you clear it in the tray's Variables tab. BBCode such as
`[b]bold[/b]` works anywhere you type. `[b]bold[/b]` works anywhere you type.
- **Logic cards** (see `docs/LOGIC.md`): Build mode's **+ Card ▾** also adds check cards, - **Logic cards** (see `docs/LOGIC.md`): Build mode's **+ Table ▾** also adds choice cards
choice cards (which option, how many, open ended), loops, variables, collections and sheets. A choice card pauses the (which option, how many, open ended), loops, variables and sheets. A choice card pauses the
roll with a pop-up (1–9 pick, R for Random, Enter confirms, Esc cancels); the steps so far roll with a pop-up (1–9 pick, R for Random, Enter confirms, Esc cancels); the steps so far
light up behind it. Loops show their rule (`× @rooms`, `while @hp > 0`); variable cards show light up behind it. Loops show their rule (`× @rooms`, `while @hp > 0`); variable cards show
their live value; sheet cards show their template filled in, and become the tray's their live value; sheet cards show their template filled in, and become the tray's
@ -58,7 +51,7 @@ godot --path .
- **Branching:** click a pipe in Build mode to give it an **Only if** condition - **Branching:** click a pipe in Build mode to give it an **Only if** condition
(`@str >= 8`), or mark it **Otherwise** so it runs only when none of that result's (`@str >= 8`), or mark it **Otherwise** so it runs only when none of that result's
conditions are true. All of a result's conditions and pipe counts are checked once, before conditions are true. All of a result's conditions and pipe counts are checked once, before
any pipe runs, and only the pipes taken light up. A **Router** card (+ Card ▾) lists cases any pipe runs, and only the pipes taken light up. A **Router** card (+ Table ▾) lists cases
("if @species = "Aslan"", "if @str >= 10", "Otherwise") and takes the first true one. ("if @species = "Aslan"", "if @str >= 10", "Otherwise") and takes the first true one.
- **Options from variables:** a pick card's settings can take its options from variables - **Options from variables:** a pick card's settings can take its options from variables
(`@skill_*` gives one option per set skill, `@contacts` one per list item), filtered with (`@skill_*` gives one option per set skill, `@contacts` one per list item), filtered with
@ -73,7 +66,7 @@ godot --path .
- **Collapsing:** the arrow beside a table's name collapses it. A collapsed table still shows - **Collapsing:** the arrow beside a table's name collapses it. A collapsed table still shows
its last result. **Collapse all / Expand all** in the top bar does every table at once. its last result. **Collapse all / Expand all** in the top bar does every table at once.
- **Groups:** in Build mode, Ctrl- or Shift-click card headers (or Ctrl-drag on the felt) to - **Groups:** in Build mode, Ctrl- or Shift-click card headers (or Ctrl-drag on the felt) to
select cards, then **Group** (Ctrl+G, the selection bar, or **+ Card ▾**). A group is a select cards, then **Group** (Ctrl+G, the selection bar, or **+ Table ▾**). A group is a
frame behind its cards; drag its title bar to move them all, drop a card into a frame to frame behind its cards; drag its title bar to move them all, drop a card into a frame to
add it, drag it out to take it out. The chevron collapses the group into one compact add it, drag it out to take it out. The chevron collapses the group into one compact
card that still shows its cards' last results, with pipes attached to its edges. The card that still shows its cards' last results, with pipes attached to its edges. The
@ -81,7 +74,7 @@ godot --path .
group and its cards (with undo). **Collapse all** and **Fit** include groups. group and its cards (with undo). **Collapse all** and **Fit** include groups.
- **Templates:** save a card (⚙ → Save as template…), a group (⋯ → Save as template…) or a - **Templates:** save a card (⚙ → Save as template…), a group (⋯ → Save as template…) or a
selection as a reusable template. Write `{$name}` in any text to make a parameter; the selection as a reusable template. Write `{$name}` in any text to make a parameter; the
save dialog finds them and asks for a label and default. **+ Card ▾ → From template…** save dialog finds them and asks for a label and default. **+ Table ▾ → From template…**
lists your templates and the built-in ones (2D skill check, ask-and-repeat, pick menu, lists your templates and the built-in ones (2D skill check, ask-and-repeat, pick menu,
counter, simple sheet), asks for the parameters and drops fresh copies at the view counter, simple sheet), asks for the parameters and drops fresh copies at the view
centre. Pipes to cards outside the template relink by name, or are listed if they can't. centre. Pipes to cards outside the template relink by name, or are listed if they can't.

View file

@ -252,11 +252,7 @@ func report() -> Dictionary:
## Problems found without rolling anything. Array of {kind, table_id, ## Problems found without rolling anything. Array of {kind, table_id,
## entry_id ("" for the card), table (display name), text}, in board order. ## 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]: static func static_checks(b: TowerBoard) -> Array[Dictionary]:
var out: Array[Dictionary] = [] var out: Array[Dictionary] = []
var add := func(kind: String, t: RollTable, eid: String, text: String) -> void: var add := func(kind: String, t: RollTable, eid: String, text: String) -> void:
@ -313,20 +309,14 @@ static func static_checks(b: TowerBoard) -> Array[Dictionary]:
var t: RollTable = null var t: RollTable = null
var eid := "" var eid := ""
var text := str(item) var text := str(item)
var lkind := "pipes"
var level := ""
if item is Dictionary: if item is Dictionary:
var d: Dictionary = item var d: Dictionary = item
t = b.get_table(str(d.get("table_id", d.get("table", "")))) t = b.get_table(str(d.get("table_id", d.get("table", ""))))
eid = str(d.get("entry_id", d.get("entry", ""))) eid = str(d.get("entry_id", d.get("entry", "")))
text = str(d.get("text", d.get("message", d.get("problem", text)))) 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: if t == null:
t = RollTable.new("", "") t = RollTable.new("", "")
add.call(lkind, t, eid, text) add.call("pipes", t, eid, text)
if level != "":
out.back()["level"] = level
return out return out

View file

@ -1,487 +0,0 @@
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"

View file

@ -1 +0,0 @@
uid://bsyjk1ayxdxej

View file

@ -1,675 +0,0 @@
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):
var u := Builder.unquote(s)
return u if u != "" else "empty"
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 <condition>"; "" 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 <condition>" or "otherwise", the count ("×2", "×Terms") and
## "saves <name>". "" 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: <condition>)".
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) + "…"

View file

@ -1 +0,0 @@
uid://gqkj2l7wn7kh

View file

@ -142,12 +142,8 @@ static func validate(text: String) -> Array[Dictionary]:
## Runs every statement against the context. Returns the log, one line per ## Runs every statement against the context. Returns the log, one line per
## statement: Array of {"text": String, "error": bool (only when true)}. ## statement: Array of {"text": String, "error": bool (only when true)}.
## `source_id` is stored as the variables' source table. `facts`, when given, ## `source_id` is stored as the variables' source table.
## gets one why-trace fact per statement that changed something: static func run(text: String, ctx: RollContext, source_id: String = "") -> Array[Dictionary]:
## {"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] = [] var log: Array[Dictionary] = []
if text.strip_edges() == "": if text.strip_edges() == "":
return log return log
@ -163,9 +159,9 @@ static func run(text: String, ctx: RollContext, source_id: String = "", facts: V
continue continue
st["target"] = rt["target"] st["target"] = rt["target"]
if st["op"] == "reset": if st["op"] == "reset":
log.append(_reset(st["target"], ctx, facts)) log.append(_reset(st["target"], ctx))
else: else:
log.append(_assign(st, ctx, source_id, facts)) log.append(_assign(st, ctx, source_id))
return log return log
@ -177,7 +173,7 @@ static func log_text(log: Array) -> PackedStringArray:
return out return out
static func _assign(st: Dictionary, ctx: RollContext, source_id: String, facts: Variant = null) -> Dictionary: static func _assign(st: Dictionary, ctx: RollContext, source_id: String) -> Dictionary:
var target: String = st["target"] var target: String = st["target"]
var op: String = st["op"] var op: String = st["op"]
var r := Expr.evaluate(st["expr"], ctx) var r := Expr.evaluate(st["expr"], ctx)
@ -244,12 +240,10 @@ static func _assign(st: Dictionary, ctx: RollContext, source_id: String, facts:
value = floori(float(a2) / float(b2)) value = floori(float(a2) / float(b2))
line = "%s ÷%s → %s" % [label, Expr.format_value(b2), _shown(value)] line = "%s ÷%s → %s" % [label, Expr.format_value(b2), _shown(value)]
ctx.save(target, value, source_id) 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} return {"text": line}
static func _reset(target: String, ctx: RollContext, facts: Variant = null) -> Dictionary: static func _reset(target: String, ctx: RollContext) -> Dictionary:
if target.ends_with("*"): if target.ends_with("*"):
var prefix := target.trim_prefix("@").trim_suffix("*") var prefix := target.trim_prefix("@").trim_suffix("*")
var names := {} var names := {}
@ -266,17 +260,12 @@ static func _reset(target: String, ctx: RollContext, facts: Variant = null) -> D
errors.append(r) errors.append(r)
if not errors.is_empty(): if not errors.is_empty():
return {"text": "reset %s: %s" % [target, "; ".join(errors)], "error": true} 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()]} return {"text": "Reset %s (%d)" % [target, names.size()]}
var name := target.trim_prefix("@") var name := target.trim_prefix("@")
var before: Variant = ctx.get_value("@" + name)
var err := reset_one(name, ctx) var err := reset_one(name, ctx)
if err != "": if err != "":
return {"text": "reset %s: %s" % [target, err], "error": true} return {"text": "reset %s: %s" % [target, err], "error": true}
var v: Variant = ctx.get_value("@" + name) 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: if v == null:
return {"text": "Reset %s (cleared)" % ctx.display_name(name)} return {"text": "Reset %s (cleared)" % ctx.display_name(name)}
return {"text": "Reset %s → %s" % [ctx.display_name(name), _shown(v)]} return {"text": "Reset %s → %s" % [ctx.display_name(name), _shown(v)]}

View file

@ -112,27 +112,6 @@ static func check(src: String) -> String:
return str(_parsed(src)["error"]) 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 ## Number-like text becomes a number ("12" -> 12, "2.5" -> 2.5); whole floats
## become ints; anything else is unchanged. ## become ints; anything else is unchanged.
static func to_value(v: Variant) -> Variant: static func to_value(v: Variant) -> Variant:
@ -503,13 +482,6 @@ class _Base:
var error: String = "" var error: String = ""
func _d(n: int, sides: int) -> int: 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) return Expr.roll_dice(n, sides, ctx.rng if ctx != null else null)
func dm(x: Variant) -> int: func dm(x: Variant) -> int:

View file

@ -79,10 +79,6 @@ var root: Dictionary = {}
var running: int = 0 var running: int = 0
## While true the roller never awaits the prompt hook (sync Roller.roll()). ## While true the roller never awaits the prompt hook (sync Roller.roll()).
var no_prompt: bool = false 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: Dictionary = {}
var _decl_built := false var _decl_built := false
@ -216,7 +212,7 @@ func declared(name: String) -> RollTable:
_decl.clear() _decl.clear()
if board != null: if board != null:
for t in board.tables: for t in board.tables:
if t.kind == RollTable.KIND_VARIABLE and t.var_name != "" and t.var_type != RollTable.VAR_COLLECTION and not _decl.has(t.var_name): if t.kind == RollTable.KIND_VARIABLE and t.var_name != "" and not _decl.has(t.var_name):
_decl[t.var_name] = t _decl[t.var_name] = t
return _decl.get(name.strip_edges().trim_prefix("@")) return _decl.get(name.strip_edges().trim_prefix("@"))

View file

@ -24,21 +24,12 @@ const KIND_LOOP := "loop"
const KIND_VARIABLE := "variable" const KIND_VARIABLE := "variable"
const KIND_SHEET := "sheet" const KIND_SHEET := "sheet"
const KIND_ROUTER := "router" const KIND_ROUTER := "router"
const KIND_CHECK := "check" const KINDS: Array[String] = [KIND_ROLL, KIND_CHOICE, KIND_LOOP, KIND_VARIABLE, KIND_SHEET, KIND_ROUTER]
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). ## A new router's first case condition (an even chance, so both cases can come up).
const ROUTER_DEFAULT_WHEN := "1d6 >= 4" const ROUTER_DEFAULT_WHEN := "1d6 >= 4"
const CHOICES: Array[String] = ["pick", "number", "text"] const CHOICES: Array[String] = ["pick", "number", "text"]
const LOOPS: Array[String] = ["times", "while", "until"] const LOOPS: Array[String] = ["times", "while", "until"]
## A variable card with var_type "collection" declares a group of board const VAR_TYPES: Array[String] = ["number", "text", "list"]
## values @<var_name>_<item> (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 id: String = ""
var name: String = "" var name: String = ""
@ -84,17 +75,6 @@ var loop_expr: String = ""
var var_name: String = "" var var_name: String = ""
var var_type: String = "number" var var_type: String = "number"
var initial: String = "" 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: Dice = null
var _dice_cache_text: String = "" var _dice_cache_text: String = ""
@ -108,13 +88,11 @@ func _init(p_id: String = "", p_name: String = "") -> void:
## A well-formed card of any kind. `sub` picks the variant: the choice ## A well-formed card of any kind. `sub` picks the variant: the choice
## ("pick", "number", "text"), the loop mode ("times", "while", "until") or ## ("pick", "number", "text"), the loop mode ("times", "while", "until") or
## the variable type ("number", "text", "list", "collection"). ## the variable type ("number", "text", "list").
## roll: four "Result N" entries · choice pick: three options · ## roll: four "Result N" entries · choice pick: three options ·
## choice number/text: one "Answer" entry · loop: "Each time" and ## choice number/text: one "Answer" entry · loop: "Each time" and
## "Afterwards" · variable: no entries · sheet: one template entry · ## "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: static func create(p_kind: String, p_id: String, p_name: String, sub: String = "") -> RollTable:
var t := RollTable.new(p_id, p_name) var t := RollTable.new(p_id, p_name)
t.kind = p_kind if KINDS.has(p_kind) else KIND_ROLL t.kind = p_kind if KINDS.has(p_kind) else KIND_ROLL
@ -143,8 +121,6 @@ static func create(p_kind: String, p_id: String, p_name: String, sub: String = "
KIND_VARIABLE: KIND_VARIABLE:
t.var_type = sub if VAR_TYPES.has(sub) else "number" 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" 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 "" t.initial = "0" if t.var_type == "number" else ""
KIND_SHEET: KIND_SHEET:
t.entries.append(TableEntry.new("e1", "[b]%s[/b]" % p_name)) t.entries.append(TableEntry.new("e1", "[b]%s[/b]" % p_name))
@ -153,57 +129,9 @@ static func create(p_kind: String, p_id: String, p_name: String, sub: String = "
first.when = ROUTER_DEFAULT_WHEN first.when = ROUTER_DEFAULT_WHEN
t.entries.append(first) t.entries.append(first)
t.entries.append(TableEntry.new("e2", "Otherwise")) 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 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). ## True for a pick choice whose options come from variables (options_from).
func is_dynamic() -> bool: func is_dynamic() -> bool:
return kind == KIND_CHOICE and choice == "pick" and options_from.strip_edges() != "" return kind == KIND_CHOICE and choice == "pick" and options_from.strip_edges() != ""
@ -289,14 +217,6 @@ func dice_obj() -> Dice:
## Rolls the ranged table's dice. Returns {"value": int, "error": String}. ## Rolls the ranged table's dice. Returns {"value": int, "error": String}.
func roll_value(ctx: RollContext) -> Dictionary: func roll_value(ctx: RollContext) -> Dictionary:
if not is_expr_dice(): 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": ""} return {"value": dice_obj().roll(ctx.rng), "error": ""}
var r := Expr.evaluate(dice, ctx) var r := Expr.evaluate(dice, ctx)
if r["error"] != "": if r["error"] != "":
@ -307,8 +227,6 @@ func roll_value(ctx: RollContext) -> Dictionary:
## Label for the dice: "d100", "2d6", "1d8+2". Plain tables label by entry ## Label for the dice: "d100", "2d6", "1d8+2". Plain tables label by entry
## count; expression dice show the expression. ## count; expression dice show the expression.
func dice_label() -> String: func dice_label() -> String:
if kind == KIND_CHECK:
return check_dice.strip_edges()
if is_ranged(): if is_ranged():
return dice.strip_edges() if is_expr_dice() else dice_obj().label() return dice.strip_edges() if is_expr_dice() else dice_obj().label()
return "d%d" % die_size() return "d%d" % die_size()
@ -544,25 +462,6 @@ func to_dict() -> Dictionary:
d["var_type"] = var_type d["var_type"] = var_type
if initial != "": if initial != "":
d["initial"] = 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 return d
@ -596,16 +495,6 @@ static func from_dict(d: Dictionary) -> RollTable:
var vt := str(d.get("var_type", "number")) var vt := str(d.get("var_type", "number"))
t.var_type = vt if VAR_TYPES.has(vt) else "number" t.var_type = vt if VAR_TYPES.has(vt) else "number"
t.initial = expr_text(d.get("initial", ""), "") 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", []): for ed: Variant in d.get("entries", []):
if ed is Dictionary: if ed is Dictionary:
t.entries.append(TableEntry.from_dict(ed)) t.entries.append(TableEntry.from_dict(ed))

View file

@ -23,12 +23,6 @@ extends RefCounted
## node ("after": true) ## node ("after": true)
## limit: true on the "Stopped after 10,000 actions" stop node ## limit: true on the "Stopped after 10,000 actions" stop node
## cancelled: true on the "Cancelled" 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 ## 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 ## never recurse in GDScript, so chains of thousands of steps are fine. Only
@ -46,7 +40,7 @@ const CANCELLED := "Cancelled"
const NO_CASE := "No case matched" const NO_CASE := "No case matched"
const NO_OPTIONS := "No options available" const NO_OPTIONS := "No options available"
enum { OP_ROLL, OP_PIPE, OP_LOOP, OP_RESTORE } enum { OP_ROLL, OP_PIPE, OP_LOOP }
## A RollContext wired to this board: it resolves [[names]] against the board's ## A RollContext wired to this board: it resolves [[names]] against the board's
@ -126,28 +120,9 @@ static func roll_async(board: TowerBoard, table_id: String, ctx: RollContext, de
ctx.halted = "" ctx.halted = ""
ctx.root = {} ctx.root = {}
ctx.forget_declarations() ctx.forget_declarations()
apply_starting_values(board, ctx)
return await _chain(board, table_id, depth, ctx) return await _chain(board, table_id, depth, ctx)
## A variable card that says "starts at …" gives its variable that value
## the first time a roll needs it: before a top-level roll, each declared
## variable that isn't set yet and has a starting value is set to it (and
## saved like any other change). Variables with no starting value stay unset,
## and collections are left alone.
static func apply_starting_values(board: TowerBoard, ctx: RollContext) -> void:
if board == null:
return
for t in board.tables:
if t.kind != RollTable.KIND_VARIABLE or t.is_collection() or t.var_name == "":
continue
if t.initial.strip_edges() == "" or ctx.get_value("@" + t.var_name) != null:
continue
var r := t.initial_value(ctx)
if str(r.get("error", "")) == "":
ctx.save("@" + t.var_name, r["value"], t.id)
## The steps of the tree built so far (ctx.root), e.g. while a prompt is open. ## The steps of the tree built so far (ctx.root), e.g. while a prompt is open.
static func progress(ctx: RollContext) -> Array: static func progress(ctx: RollContext) -> Array:
return flatten(ctx.root, []) return flatten(ctx.root, [])
@ -188,13 +163,6 @@ static func _chain(board: TowerBoard, table_id: String, depth: int, ctx: RollCon
_do_pipe(board, f, ctx, stack) _do_pipe(board, f, ctx, stack)
OP_LOOP: OP_LOOP:
await _do_loop(f, ctx, stack) 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 ctx.running -= 1
var kids: Array = holder["children"] var kids: Array = holder["children"]
return kids[0] if not kids.is_empty() else {} return kids[0] if not kids.is_empty() else {}
@ -209,13 +177,6 @@ static func _stop(t: RollTable, why: String, extra: Dictionary = {}) -> Dictiona
static func _attach(f: Dictionary, node: Dictionary, ctx: RollContext) -> void: static func _attach(f: Dictionary, node: Dictionary, ctx: RollContext) -> void:
if str(f.get("save", "")) != "": if str(f.get("save", "")) != "":
node["save_as"] = f["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) (f["parent"]["children"] as Array).append(node)
if f.get("top", false): if f.get("top", false):
ctx.root = node ctx.root = node
@ -239,7 +200,6 @@ static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack:
return return
if not _take_action(f, t, ctx): if not _take_action(f, t, ctx):
return return
_bind_inputs(t, f, ctx, stack)
if t.entries.is_empty(): if t.entries.is_empty():
_attach(f, _stop(t, "This table has no results"), ctx) _attach(f, _stop(t, "This table has no results"), ctx)
return return
@ -250,8 +210,6 @@ static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack:
_start_loop(t, f, ctx, stack) _start_loop(t, f, ctx, stack)
RollTable.KIND_ROUTER: RollTable.KIND_ROUTER:
await _do_router(t, f, ctx, stack) await _do_router(t, f, ctx, stack)
RollTable.KIND_CHECK:
await _do_check(t, f, ctx, stack)
RollTable.KIND_SHEET: RollTable.KIND_SHEET:
var sheet := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "", var sheet := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "",
"kind": RollTable.KIND_SHEET} "kind": RollTable.KIND_SHEET}
@ -259,9 +217,6 @@ static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack:
await _enter(sheet, f, ctx, stack, true, true) await _enter(sheet, f, ctx, stack, true, true)
_: _:
var node := _pick_node(t, ctx) var node := _pick_node(t, ctx)
if node.has("nat"):
ctx.chain_vars["nat"] = node["nat"]
node.erase("nat")
_attach(f, node, ctx) _attach(f, node, ctx)
if not node.has("stop"): if not node.has("stop"):
await _enter(node, f, ctx, stack) await _enter(node, f, ctx, stack)
@ -274,7 +229,6 @@ static func _pick_node(t: RollTable, ctx: RollContext) -> Dictionary:
var index: int var index: int
var value: int var value: int
var reshuffled := false var reshuffled := false
var fact: Dictionary
if t.card_mode: if t.card_mode:
var decks: Dictionary = ctx.get_meta("decks", {}) var decks: Dictionary = ctx.get_meta("decks", {})
if not decks.has(t.id): if not decks.has(t.id):
@ -290,25 +244,11 @@ static func _pick_node(t: RollTable, ctx: RollContext) -> Dictionary:
var card := deck.draw(t, rng) var card := deck.draw(t, rng)
index = int(card["index"]) index = int(card["index"])
value = int(card["value"]) value = int(card["value"])
fact = {"type": "roll", "pick": "card", "dice": t.dice_label(), "total": value}
elif t.is_ranged(): elif t.is_ranged():
var was: Variant = ctx.faces
ctx.faces = []
var rv := t.roll_value(ctx) 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"] != "": if rv["error"] != "":
return _stop(t, "Can't roll %s: %s" % [t.dice, rv["error"]]) return _stop(t, "Can't roll %s: %s" % [t.dice, rv["error"]])
value = int(rv["value"]) 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) index = t.entry_index_clamped(value) if t.is_expr_dice() else t.entry_index_for(value)
if index < 0: if index < 0:
return _stop(t, "No result for %s" % t.fmt(value), {"value": value}) return _stop(t, "No result for %s" % t.fmt(value), {"value": value})
@ -317,18 +257,10 @@ static func _pick_node(t: RollTable, ctx: RollContext) -> Dictionary:
if index < 0: if index < 0:
return _stop(t, "No result can come up") return _stop(t, "No result can come up")
value = index + 1 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": [], var node := {"table": t, "index": index, "value": value, "entry": t.entries[index], "children": [],
"summary": "", "why": [fact]} "summary": ""}
if reshuffled: if reshuffled:
node["reshuffled"] = true 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 return node
@ -344,9 +276,7 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr
var e: TableEntry = node["entry"] var e: TableEntry = node["entry"]
var depth := int(f.get("depth", 0)) var depth := int(f.get("depth", 0))
if e.effects.strip_edges() != "": if e.effects.strip_edges() != "":
var facts: Array = [] _log(node, Effects.run(e.effects, ctx, t.id))
_log(node, Effects.run(e.effects, ctx, t.id, facts))
_why(node, facts)
if expand: if expand:
ctx.depth = depth + 1 ctx.depth = depth + 1
var ex: Dictionary = await TextExpander.expand_async(e.text, ctx, live) var ex: Dictionary = await TextExpander.expand_async(e.text, ctx, live)
@ -378,29 +308,14 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr
if e.pipes.is_empty(): if e.pipes.is_empty():
return return
var log: Array = [] var log: Array = []
var why: Array = [] var plan := pipe_plan(e, ctx, log)
var plan := pipe_plan(e, ctx, log, why)
_log(node, log) _log(node, log)
_why(node, why)
for k in range(plan.size() - 1, -1, -1): for k in range(plan.size() - 1, -1, -1):
var item: Dictionary = plan[k] var item: Dictionary = plan[k]
if not item["run"]: if not item["run"]:
continue continue
var p: String = item["to"] var p: String = item["to"]
var fr := {"op": OP_PIPE, "node": node, "entry": e, "to": p, "left": int(item["count"]), "save": e.save_for(p), "depth": depth} stack.append({"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". ## Appends effect-log lines to a node's "effects".
@ -414,19 +329,14 @@ static func _log(node: Dictionary, lines: Array) -> void:
## The snapshot of an entry's pipes, taken once after the entry's effects ran ## 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, ## and its text expanded: one item per pipe, in pipe order,
## {"to": table id, "run": bool, "count": int, "with": {name: value}} ("with" ## {"to": table id, "run": bool, "count": int}.
## 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 ## - A pipe with a condition ("when") runs only if it's true. An error
## counts as false and adds an error line to `log`. ## counts as false and adds an error line to `log`.
## - An "otherwise" pipe runs only if none of the entry's conditions was true. ## - An "otherwise" pipe runs only if none of the entry's conditions was true.
## - Any other pipe always runs. ## - Any other pipe always runs.
## Counts are worked out only for pipes that run (0 for the others); an ## Counts are worked out only for pipes that run (0 for the others); an
## expression count's error gives 0 and an error line. `why` gets the trace ## expression count's error gives 0 and an error line.
## facts: {"type": "when", "to", "expr", "values": {name: value}, "result": static func pipe_plan(e: TableEntry, ctx: RollContext, log: Array = []) -> Array:
## 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 plan: Array = []
var any_true := false var any_true := false
for p in e.pipes: for p in e.pipes:
@ -434,104 +344,22 @@ static func pipe_plan(e: TableEntry, ctx: RollContext, log: Array = [], why: Arr
var run := true var run := true
if w != "": if w != "":
var r := Expr.evaluate(w, ctx) 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"] != "": if r["error"] != "":
log.append({"text": "Pipe condition %s: %s" % [w, r["error"]], "error": true}) log.append({"text": "Pipe condition %s: %s" % [w, r["error"]], "error": true})
run = false run = false
fact["error"] = str(r["error"])
else: else:
run = Expr.truthy(r["value"]) run = Expr.truthy(r["value"])
fact["result"] = run
why.append(fact)
any_true = any_true or run any_true = any_true or run
plan.append({"to": p, "run": run, "count": 0, "otherwise": w == "" and e.is_otherwise(p)}) plan.append({"to": p, "run": run, "count": 0, "otherwise": w == "" and e.is_otherwise(p)})
for item: Dictionary in plan: for item: Dictionary in plan:
if item["otherwise"]: if item["otherwise"]:
item["run"] = not any_true item["run"] = not any_true
why.append({"type": "otherwise", "to": item["to"], "result": item["run"]})
item.erase("otherwise") item.erase("otherwise")
if item["run"]: if item["run"]:
item["count"] = e.count_value(str(item["to"]), ctx, log) 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 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: static func _do_pipe(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: Array) -> void:
if int(f["left"]) <= 0: if int(f["left"]) <= 0:
return return
@ -540,121 +368,38 @@ static func _do_pipe(board: TowerBoard, f: Dictionary, ctx: RollContext, stack:
return return
f["left"] = int(f["left"]) - 1 f["left"] = int(f["left"]) - 1
stack.append(f) stack.append(f)
var fr := {"op": OP_ROLL, "id": f["to"], "parent": f["node"], "save": f["save"], "depth": f["depth"]} stack.append({"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 ---------- # ---------- Routers ----------
## The index of the first router case whose condition is true (an empty ## The index of the first router case whose condition is true (an empty
## condition, the Otherwise case, always matches), or -1. Errors count as ## condition, the Otherwise case, always matches), or -1. Errors count as
## false and add a line to `log`. `why` gets one fact per case tried: ## false and add a line to `log`.
## {"type": "case", "index", "expr" ("" for Otherwise), "values", "result", static func route(t: RollTable, ctx: RollContext, log: Array = []) -> int:
## "error"?}.
static func route(t: RollTable, ctx: RollContext, log: Array = [], why: Array = []) -> int:
for k in t.entries.size(): for k in t.entries.size():
var w := t.entries[k].when.strip_edges() var w := t.entries[k].when.strip_edges()
if w == "": if w == "":
why.append({"type": "case", "index": k, "expr": "", "values": {}, "result": true})
return k return k
var r := Expr.evaluate(w, ctx) 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"] != "": if r["error"] != "":
log.append({"text": "Case %s: %s" % [w, r["error"]], "error": true}) log.append({"text": "Case %s: %s" % [w, r["error"]], "error": true})
fact["error"] = str(r["error"])
elif Expr.truthy(r["value"]): elif Expr.truthy(r["value"]):
fact["result"] = true
return k return k
return -1 return -1
static func _do_router(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void: static func _do_router(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
var log: Array = [] var log: Array = []
var why: Array = [] var k := route(t, ctx, log)
var k := route(t, ctx, log, why)
if k < 0: if k < 0:
var stop := _stop(t, NO_CASE, {"kind": RollTable.KIND_ROUTER}) var stop := _stop(t, NO_CASE, {"kind": RollTable.KIND_ROUTER})
_log(stop, log) _log(stop, log)
_why(stop, why)
_attach(f, stop, ctx) _attach(f, stop, ctx)
return return
var node := {"table": t, "index": k, "entry": t.entries[k], "children": [], "summary": "", var node := {"table": t, "index": k, "entry": t.entries[k], "children": [], "summary": "",
"kind": RollTable.KIND_ROUTER, "case": k} "kind": RollTable.KIND_ROUTER, "case": k}
_log(node, log) _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) _attach(f, node, ctx)
await _enter(node, f, ctx, stack) await _enter(node, f, ctx, stack)
@ -745,9 +490,7 @@ static func _do_loop(f: Dictionary, ctx: RollContext, stack: Array) -> void:
static func request_for(t: RollTable, ctx: RollContext) -> Dictionary: static func request_for(t: RollTable, ctx: RollContext) -> Dictionary:
var options: Array = [] var options: Array = []
var log: Array = [] var log: Array = []
var why: Array = []
var hidden := 0 var hidden := 0
var chosen_hidden := false
if t.choice == "pick": if t.choice == "pick":
var ranged := t.is_ranged() var ranged := t.is_ranged()
for k in range(t.fixed_start(), t.entries.size()): for k in range(t.fixed_start(), t.entries.size()):
@ -757,11 +500,9 @@ static func request_for(t: RollTable, ctx: RollContext) -> Dictionary:
continue continue
options.append({"index": k, "entry": k, "text": TextExpander.render(e.text, ctx), "details": e.details, 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)}) "weight": e.span() if ranged else maxi(0, e.weight)})
if t.is_dynamic() and not t.entries.is_empty() and not option_shown(t.entries[0], ctx, log): if t.is_dynamic() and not t.entries.is_empty() and 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 chosen := t.entries[0]
var cands := dynamic_options(t, ctx, log, why) var cands := dynamic_options(t, ctx, log)
for j in cands.size(): for j in cands.size():
var c: Dictionary = cands[j] var c: Dictionary = cands[j]
var vt := Expr.format_value(c["value"]) if str(c["kind"]) == "prefix" else "" var vt := Expr.format_value(c["value"]) if str(c["kind"]) == "prefix" else ""
@ -777,10 +518,8 @@ static func request_for(t: RollTable, ctx: RollContext) -> Dictionary:
def = lo def = lo
elif t.choice == "text": elif t.choice == "text":
def = "" 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), 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, "why": why} "options": options, "min": lo, "max": hi, "default": def, "log": log, "hidden": hidden}
## Whether a pick option is offered now: its show_if is empty or true. An ## Whether a pick option is offered now: its show_if is empty or true. An
@ -801,9 +540,8 @@ static func option_shown(e: TableEntry, ctx: RollContext, log: Array = []) -> bo
## variable name without "@", or the list item), label, value}. A prefix ## variable name without "@", or the list item), label, value}. A prefix
## gives one per set variable, sorted by label ("Pilot"); a list gives one ## 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 ## per item, in list order (label and value are the item). A filter error
## counts as false and adds one line to `log`. With a filter, `why` gets ## counts as false and adds one line to `log`.
## {"type": "options_where", "from", "expr", "kept", "total"}. static func dynamic_options(t: RollTable, ctx: RollContext, log: Array = []) -> Array:
static func dynamic_options(t: RollTable, ctx: RollContext, log: Array = [], why: Array = []) -> Array:
var out: Array = [] var out: Array = []
var src := RollTable.parse_options_from(t.options_from) var src := RollTable.parse_options_from(t.options_from)
if str(src["error"]) != "": if str(src["error"]) != "":
@ -841,7 +579,6 @@ static func dynamic_options(t: RollTable, ctx: RollContext, log: Array = [], why
ctx.chain_vars[k] = saved[k] ctx.chain_vars[k] = saved[k]
else: else:
ctx.chain_vars.erase(k) 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 return out
@ -888,7 +625,6 @@ static func _do_choice(t: RollTable, f: Dictionary, ctx: RollContext, stack: Arr
if t.choice == "pick" and opts.is_empty(): if t.choice == "pick" and opts.is_empty():
var none := _stop(t, NO_OPTIONS, {"kind": RollTable.KIND_CHOICE}) var none := _stop(t, NO_OPTIONS, {"kind": RollTable.KIND_CHOICE})
_log(none, req["log"]) _log(none, req["log"])
_why(none, req["why"])
_attach(f, none, ctx) _attach(f, none, ctx)
return return
var reply: Variant = await ask(ctx, req) var reply: Variant = await ask(ctx, req)
@ -923,7 +659,6 @@ static func _do_choice(t: RollTable, f: Dictionary, ctx: RollContext, stack: Arr
# A plain fixed list: Random rolls the card the usual way # A plain fixed list: Random rolls the card the usual way
# (weights, ranges, card mode). # (weights, ranges, card mode).
node = _pick_node(t, ctx) node = _pick_node(t, ctx)
node.erase("nat")
node["random"] = true node["random"] = true
else: else:
var k := _pick_option(opts, ctx.rng) var k := _pick_option(opts, ctx.rng)
@ -934,7 +669,6 @@ static func _do_choice(t: RollTable, f: Dictionary, ctx: RollContext, stack: Arr
node["random"] = true node["random"] = true
node["kind"] = RollTable.KIND_CHOICE node["kind"] = RollTable.KIND_CHOICE
_log(node, req["log"]) _log(node, req["log"])
_why(node, req["why"])
_attach(f, node, ctx) _attach(f, node, ctx)
if node.has("stop"): if node.has("stop"):
return return
@ -1059,9 +793,7 @@ static func _can_finish(t: RollTable, board: TowerBoard, done: Dictionary) -> bo
## is saved in the roll history. "text" is BBCode with internal markers. ## is saved in the roll history. "text" is BBCode with internal markers.
## Logic-card keys (only when they apply): kind, effects (Array of {text, ## Logic-card keys (only when they apply): kind, effects (Array of {text,
## error?}), answer, passes, pass, after, picked, random, limit, cancelled, ## error?}), answer, passes, pass, after, picked, random, limit, cancelled,
## case (router nodes: the matched case's index), option, check ({nat, mod, ## case (router nodes: the matched case's index).
## 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: static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
var t: RollTable = n["table"] var t: RollTable = n["table"]
var step := { var step := {
@ -1087,11 +819,9 @@ static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
step["kind"] = n["kind"] step["kind"] = n["kind"]
if n.has("effects"): if n.has("effects"):
step["effects"] = (n["effects"] as Array).duplicate(true) step["effects"] = (n["effects"] as Array).duplicate(true)
for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled", "case", "option", "check", "inputs"]: for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled", "case", "option"]:
if n.has(k): if n.has(k):
step[k] = n[k] step[k] = n[k]
if n.has("why"):
step["why"] = (n["why"] as Array).duplicate()
return step return step
@ -1210,14 +940,10 @@ static func live_context(board: TowerBoard, persistent: Dictionary) -> RollConte
## Live display of a variable card: its current value as text, or its ## Live display of a variable card: its current value as text, or its
## starting value (marked) when it isn't set yet. A collection shows its set ## starting value (marked) when it isn't set yet.
## members ("Gun Combat 1, Pilot 0"; set is false when there are none).
## Returns {"text": String, "set": bool, "error": String}. ## Returns {"text": String, "set": bool, "error": String}.
static func variable_display(board: TowerBoard, persistent: Dictionary, t: RollTable) -> Dictionary: static func variable_display(board: TowerBoard, persistent: Dictionary, t: RollTable) -> Dictionary:
var ctx := live_context(board, persistent) 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) var v: Variant = ctx.get_value("@" + t.var_name)
if v != null: if v != null:
return {"text": Expr.format_value(v), "set": true, "error": ""} return {"text": Expr.format_value(v), "set": true, "error": ""}
@ -1248,8 +974,6 @@ static func lint_pipes(board: TowerBoard) -> Array[Dictionary]:
for t in board.tables: for t in board.tables:
out.append_array(lint_router(t)) out.append_array(lint_router(t))
out.append_array(lint_options(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(): for i in t.entries.size():
var e := t.entries[i] var e := t.entries[i]
var first_other := "" var first_other := ""
@ -1329,79 +1053,6 @@ static func lint_options(t: RollTable) -> Array[Dictionary]:
return out 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: static func _table_name(board: TowerBoard, id: String) -> String:
var t := board.get_table(id) var t := board.get_table(id)
return Formatter.strip_tags(t.name) if t else id return Formatter.strip_tags(t.name) if t else id

View file

@ -127,28 +127,6 @@ func set_setting(key: String, value: Variant) -> void:
_dirty = true _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 ---------- # ---------- Forgetting ----------
## Drops everything stored for a collection (decks, variables, its history). ## Drops everything stored for a collection (decks, variables, its history).

View file

@ -30,10 +30,6 @@ var pipe_when: Dictionary = {}
## target table id -> true: the pipe runs only when none of this entry's ## target table id -> true: the pipe runs only when none of this entry's
## conditional pipes did. Ignored while the pipe has a condition. ## conditional pipes did. Ignored while the pipe has a condition.
var pipe_otherwise: Dictionary = {} 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 ## Router cards: this case's condition. "" is the Otherwise case (always
## matches). Ignored on other kinds. ## matches). Ignored on other kinds.
var when: String = "" var when: String = ""
@ -154,29 +150,6 @@ func has_conditional_pipes() -> bool:
return false 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: func set_pipe_save(target: String, name: String) -> void:
name = name.strip_edges() name = name.strip_edges()
if name == "": if name == "":
@ -200,7 +173,6 @@ func remove_pipe(target: String) -> void:
pipe_save.erase(target) pipe_save.erase(target)
pipe_when.erase(target) pipe_when.erase(target)
pipe_otherwise.erase(target) pipe_otherwise.erase(target)
pipe_with.erase(target)
func to_dict() -> Dictionary: func to_dict() -> Dictionary:
@ -223,8 +195,7 @@ func to_dict() -> Dictionary:
var s := save_for(p) var s := save_for(p)
var w := when_for(p) var w := when_for(p)
var other := is_otherwise(p) var other := is_otherwise(p)
var wv: Variant = pipe_with.get(p) if expr == "" and n == 1 and s == "" and w == "" and not other:
if expr == "" and n == 1 and s == "" and w == "" and not other and wv == null:
list.append(p) list.append(p)
else: else:
var po := {"table": p} var po := {"table": p}
@ -238,8 +209,6 @@ func to_dict() -> Dictionary:
po["when"] = w po["when"] = w
elif other: elif other:
po["otherwise"] = true po["otherwise"] = true
if wv is Dictionary and not (wv as Dictionary).is_empty():
po["with"] = (wv as Dictionary).duplicate()
list.append(po) list.append(po)
d["pipes"] = list d["pipes"] = list
if has_range: if has_range:
@ -262,8 +231,6 @@ 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.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_when(target, str(p.get("when", "")) if p.get("when") != null else "")
e.set_pipe_otherwise(target, bool(p.get("otherwise", false))) 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) != "": elif str(p) != "":
e.add_pipe(str(p)) e.add_pipe(str(p))
var r: Variant = d.get("range") var r: Variant = d.get("range")

View file

@ -72,7 +72,7 @@ static func make(board: TowerBoard, table_ids: Array, kind: String, tname: Strin
continue continue
var np := {"table": other.name, "outside": true} var np := {"table": other.name, "outside": true}
if p is Dictionary: if p is Dictionary:
for k in ["count", "save_as", "with"]: for k in ["count", "save_as"]:
if (p as Dictionary).has(k): if (p as Dictionary).has(k):
np[k] = p[k] np[k] = p[k]
pipes.append(np) pipes.append(np)
@ -259,7 +259,7 @@ static func instantiate(tpl: Dictionary, values: Dictionary, board: TowerBoard,
continue continue
var np := {"table": to} var np := {"table": to}
if p is Dictionary: if p is Dictionary:
for k in ["count", "save_as", "with"]: for k in ["count", "save_as"]:
if (p as Dictionary).has(k): if (p as Dictionary).has(k):
np[k] = p[k] np[k] = p[k]
pipes.append(np) pipes.append(np)

View file

@ -18,10 +18,8 @@ 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 | | `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 | | `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 | | `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, and Every kind except `variable` can be the start of a roll and can be the target of a pipe.
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 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 "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). also have a condition, or be an "otherwise" pipe (§3a).
@ -170,7 +168,7 @@ lazy). No existing test changed.
## 3b. Router cards ## 3b. Router cards
A router (`kind: "router"`, "Router" in the **+ Card ▾** menu, "if / else if / otherwise") A router (`kind: "router"`, "Router" in the **+ Table ▾** menu, "if / else if / otherwise")
has no dice. Its entries are **cases**, each with an entry-level `when` expression. has no dice. Its entries are **cases**, each with an entry-level `when` expression.
- When the chain reaches it, the cases are checked top to bottom and the **first** true case - When the chain reaches it, the cases are checked top to bottom and the **first** true case
@ -187,67 +185,11 @@ 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 be reordered and removed on the card, and their conditions edited there or in the
settings dialog. settings dialog.
`Roller.lint_pipes(board)` lists problems for a board check (it also includes `Roller.lint_pipes(board)` lists problems for a board check: `when` or case conditions that
`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 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 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 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}`; items no cases or whose Otherwise case isn't last. Each item is `{table_id, entry_id, message}`.
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": {"<name>": "<expression>"}`.
- 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 ## 4. Expressions
@ -292,14 +234,6 @@ when the expression has modifiers.
declaration is needed. A **variable card** (`kind: variable`) is optional and gives a 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 variable a label, a type (`number`, `text` or `list`), a starting value (an expression) and
details. 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
`@<stem>_<item>` (`@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 - `reset @name` sets a declared variable back to its starting value, or deletes an undeclared
one. `reset @skill_*` resets every variable with that prefix. one. `reset @skill_*` resets every variable with that prefix.
- Chain variables (no `@`, e.g. `answer`, `i`, `-> hero`) last for one top-level roll, as - Chain variables (no `@`, e.g. `answer`, `i`, `-> hero`) last for one top-level roll, as
@ -377,45 +311,16 @@ step's result.
## 9. File format additions ## 9. File format additions
Table keys: Table keys:
- `kind` (`roll` is the default and is omitted; `check` is a check card) - `kind` (`roll` is the default and is omitted)
- `choice`, `prompt`, `save_as`, `min`, `max` (choice cards) - `choice`, `prompt`, `save_as`, `min`, `max` (choice cards)
- `options_from`, `options_where` (pick choices with options from variables, §2a) - `options_from`, `options_where` (pick choices with options from variables, §2a)
- `loop`, `loop_expr` (loop cards) - `loop`, `loop_expr` (loop cards)
- `var_name`, `var_type` (`number`, `text`, `list` or `collection`), `initial` (variable cards) - `var_name`, `var_type`, `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: Entry keys:
- `effects` (String) - `effects` (String)
- `when` (String, router cases; empty or missing is Otherwise) - `when` (String, router cases; empty or missing is Otherwise)
- `show_if` (String, pick options; empty or missing is always shown) - `show_if` (String, pick options; empty or missing is always shown)
Pipe objects may have `"count": "<expression>"`, `"when": "<expression>"`, Pipe objects may have `"count": "<expression>"`, `"when": "<expression>"` and
`"otherwise": true` (left out when the pipe has a `when`) and `"otherwise": true` (left out when the pipe has a `when`).
`"with": {"<input name>": "<expression>"}` (§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.

View file

@ -1,143 +0,0 @@
# TableTower: Plain Build (usability pass)
**Status:** Spec · **Branch:** `plain-build` · **Mockup:** https://claude.ai/code/artifact/caad5536-59a0-4b74-9c0d-b3024a9767c1
**Goal:** a person can build logic boards without learning the rule language, and anyone
can read a board and see why a roll went the way it did.
**Constraint:** the stored format stays the rule text from `docs/LOGIC.md`, so old boards
open unchanged and power users can always edit as text. Everything here is a layer in
front of it. New keys are additive.
## 1. Describe: rules in plain words (`core/describe.gd`, class `Describe`)
Pure functions that turn stored rules into short phrases. They use value labels
(§3) and fall back to the original text for anything they can't parse.
| Function | Input | Example output |
|---|---|---|
| `effect(stmt, board) -> String` | one effect statement | `@luck -= 1` → "Luck −1"; `@skill_pilot += 1` → "Pilot +1"; `@town = "Millbrook"` → "Town = Millbrook"; `reset @skill_*` → "Clear all Skills"; `@[option] += 1` → "Chosen skill +1" (or "Chosen value +1" outside a skills collection) |
| `effects(text, board) -> Array[String]` | effects field | one phrase per statement |
| `condition(expr, board) -> String` | a `when` / `show_if` / `options_where` / loop rule | `@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" |
| `dice(expr, board) -> String` | dice / count expression | `2d6 + dm(@str)` → "2D + Strength modifier"; `1d6 + tier` → "1D + Tier" |
| `options(table, board) -> String` | dynamic pick source | "your Skills, level 1 or more" |
| `pipe(entry, target_id, board) -> String` | a pipe's label | "Tier 3 · only if Luck is 2 or more", "otherwise", "×2 · saves Weapon" |
| `check(table, board) -> String` | a Check card | "Roll 2D + Strength modifier, need 8 or more" |
| `why(fact, board, plain := true) -> String` | one trace fact (§5) | "Skipped Tier 3 because Luck was 1 (needs 2 or more)" |
Comparisons read as "is", "is not", "is at least", "is at most", "is more than" and "is less
than". `>= N` reads "is N or more" when it sits after a value name.
## 2. Builders: structured models that round-trip with text (`core/builder.gd`, class `Builder`)
- `parse_effect(stmt) -> {ok, op, var, amount}`
- `op` is one of `set`, `add`, `subtract`, `multiply`, `divide`, `reset`, `append` or `remove`.
- `var` may be `@name`, `@prefix_*` (reset only) or `@[option]`.
- `ok: false` means the statement doesn't fit the builder, so the UI shows it as text.
- `effect_text(model) -> String` is the inverse. `parse_effect(effect_text(m))` must equal `m`.
- `parse_condition(expr) -> {ok, join: "and"|"or", clauses: [{var, cmp, value}]}`
- `cmp` is one of `eq`, `ne`, `ge`, `le`, `gt`, `lt`, `has` (list contains), `set` or `unset`.
- `value` is a number, quoted text, or another `@name`.
- Mixed and/or, function calls other than `has`, and dice give `ok: false`.
- `condition_text(model) -> String` is the inverse.
- `known_values(board) -> Array[{name, label, kind, source}]`: every value the board uses.
- `kind` is `number`, `text`, `list` or `collection`.
- Sources: variable cards, collections, effect targets, `save_as`, card inputs, and chain names (`answer`, `option`, `i`, `total`, `nat`, `effect`).
- It's used by value pickers, with variable-card labels first.
## 3. Value labels and collections
- **Labels.** A value's label comes from its variable card's name, then from the collection
it belongs to (`skill_gun_combat` in the Skills collection reads "Gun Combat"), and otherwise
from a pretty form of its name (`soc` → "Soc"). A label table for common short names
(`str` → "Strength") isn't built in; variable cards are how boards name things.
- **Collection** is a variable card with `var_type: "collection"`. Its `var_name` is the stem
(e.g. `skill`), its name is the label ("Skills"), and its members are the board values
`@<stem>_<item>`.
- On the board it shows a list editor: members with their values, plus "+ Add".
- `options_from: "@skill_*"` reads "your Skills".
- `count("skill_")` and `{@skill_*}` work as before.
- `Describe` uses the collection to label its members.
## 4. New engine features
1. **Check card** (`kind: "check"`).
- Fields: `check_dice` (default `"2d6"`), `check_mod` (an expression, default `""`, e.g.
`dm(@str)`), `check_cmp` (`ge`, the default, or `le`) and `check_target` (an expression,
default `"8"`).
- Two fixed entries: **Success** (index 0) and **Failure** (index 1), each with effects and pipes.
- Rolling sets the chain variables `nat` (the dice alone), `total` (dice plus modifier) and
`effect` (total minus target).
- The node gets `check: {nat, mod, total, target, success}`. It counts as one action.
2. **Card inputs (pipe parameters).**
- A table may declare `inputs: [{name, label, default}]`.
- A pipe object may carry `with: {name: "<expr>"}`. The expressions are evaluated in the
entry's snapshot (LOGIC §3a), with the other pipe values.
- While that pipe's subtree runs, each input is a chain value (`tier`, `{tier}` in text).
When the subtree ends, the previous values come back. Two pipes to the same card can pass
different values.
- Missing inputs use their default. A roll that starts on the card uses the defaults.
- JSON: `inputs` on tables and `with` on pipe objects.
3. **`nat`** is also set on every dice roll of a roll table (the dice part only), so
"natural 2" rules can test `nat = 2`.
4. **Why trace.** Every node gets `why: Array[Dictionary]` facts, recorded by the roller:
- `roll`: dice faces, modifier and total.
- `check`.
- `when`: the pipe, the expression, the values it read, and the result.
- `otherwise`.
- `case` (router): the case tried, its values and its result.
- `show_if` / `options_where` (summarized).
- `effect`: before and after.
- `input`: name and value.
`Describe.why` turns each fact into a sentence. Steps from `Roller.flatten` carry the facts.
Facts are plain data and survive JSON (history).
## 5. Display preference
`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
`[op] [amount] [to/from] [value ▾]`).
- **Then go to:** one box per pipe with inputs, **Only if** (condition builder rows of
`[value ▾] [comparison ▾] [amount]`, plus and/or), **Otherwise**, count and save as.
- **Cards:** kind-specific fields (check dice, modifier picker and target; collection members;
declared inputs; options source as "from [collection ▾] where [condition]"; and so on).
- A value picker lists `known_values` with search and "+ New value…".
- "Edit as text" on any builder switches it to the text field, and back when it parses.
- **Display:**
- Plain chips for effects, plain pipe labels, router cases, choice option sources and loop rules.
- Check, collection and input visuals on the cards.
- "Why this?" on tray chips and in step hover.
- Plain previews in the choice pop-up.
- A **Plain words / Text** switch.

View file

@ -10,14 +10,11 @@ extends RefCounted
## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode], ## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode],
## [deck_empty], [kind], [choice], [prompt], [save_as], [options_from], ## [deck_empty], [kind], [choice], [prompt], [save_as], [options_from],
## [options_where], [min], [max], ## [options_where], [min], [max],
## [loop], [loop_expr], [var_name], [var_type], [initial], ## [loop], [loop_expr], [var_name], [var_type], [initial], entries
## [check_dice], [check_mod], [check_cmp], [check_target],
## [inputs: [{name, [label], [default]}, ...]], entries
## entry: id, text, [details], [weight], [range], [effects], [when], [show_if], ## entry: id, text, [details], [weight], [range], [effects], [when], [show_if],
## [pipes] ## [pipes]
## pipe: a table id String, or {"table": id, "count": n or "<expression>", ## pipe: a table id String, or {"table": id, "count": n or "<expression>",
## "save_as": name, "when": "<expression>", "otherwise": true, ## "save_as": name, "when": "<expression>", "otherwise": true}
## "with": {input name: "<expression>"}}
## ("otherwise" is dropped when the pipe has a "when") ## ("otherwise" is dropped when the pipe has a "when")
## The logic-card keys (docs/LOGIC.md §9) are Strings, and are left out when ## The logic-card keys (docs/LOGIC.md §9) are Strings, and are left out when
## they have their default value. ## they have their default value.
@ -132,11 +129,6 @@ static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Di
for key in ["prompt", "initial"]: for key in ["prompt", "initial"]:
if t5.has(key): if t5.has(key):
t5[key] = clean.call(str(t5[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"): if t5.has("tags"):
var tags: Array = [] var tags: Array = []
for tag in t5["tags"]: for tag in t5["tags"]:
@ -192,11 +184,6 @@ static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Di
np["save_as"] = clean.call(str(np["save_as"])) np["save_as"] = clean.call(str(np["save_as"]))
if np.has("when"): if np.has("when"):
np["when"] = clean.call(str(np["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) pipes.append(np)
else: else:
pipes.append(target) pipes.append(target)
@ -326,25 +313,13 @@ static func _canon_table(td: Dictionary) -> Dictionary:
if RollTable.KINDS.has(kind) and kind != "roll": if RollTable.KINDS.has(kind) and kind != "roll":
t["kind"] = kind t["kind"] = kind
var defaults := {"choice": "pick", "prompt": "", "save_as": "", "options_from": "", "options_where": "", "min": "0", "max": "99", 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: for key: String in defaults:
if not td.has(key) or td[key] == null: if not td.has(key) or td[key] == null:
continue continue
var s := RollTable.expr_text(td[key], str(defaults[key])) var s := RollTable.expr_text(td[key], str(defaults[key]))
if s != str(defaults[key]): if s != str(defaults[key]):
t[key] = s 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 entries: Array = []
var src_entries: Variant = td.get("entries", []) var src_entries: Variant = td.get("entries", [])
if src_entries is Array: if src_entries is Array:
@ -398,29 +373,12 @@ static func _canon_entry(ev: Variant) -> Dictionary:
np["when"] = pw np["when"] = pw
elif p.get("otherwise", false) is bool and bool(p.get("otherwise", false)): elif p.get("otherwise", false) is bool and bool(p.get("otherwise", false)):
np["otherwise"] = true np["otherwise"] = true
var wv := _canon_with(p.get("with"))
if not wv.is_empty():
np["with"] = wv
pipes.append(np) pipes.append(np)
if not pipes.is_empty(): if not pipes.is_empty():
e["pipes"] = pipes e["pipes"] = pipes
return e 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 # -------------------------------------------------------------- helpers
## Turns whole floats (as JSON parsing gives) into ints; returns `fallback` ## Turns whole floats (as JSON parsing gives) into ints; returns `fallback`
@ -455,8 +413,7 @@ static func unique_id(base: String, used: Dictionary) -> String:
## Normalizes a pipe (String or Dictionary) to {"table", "count", "save_as", ## Normalizes a pipe (String or Dictionary) to {"table", "count", "save_as",
## "count_expr", "when", "otherwise", "with"} ("with": {name: expression}, ## "count_expr", "when", "otherwise"}. An expression count ("@terms") reads as
## {} for none). An expression count ("@terms") reads as
## count 1, with the expression in "count_expr" ("" otherwise). "when" is the ## count 1, with the expression in "count_expr" ("" otherwise). "when" is the
## pipe's condition ("" for none); "otherwise" is true only without one. ## pipe's condition ("" for none); "otherwise" is true only without one.
static func pipe_info(p: Variant) -> Dictionary: static func pipe_info(p: Variant) -> Dictionary:
@ -467,9 +424,8 @@ static func pipe_info(p: Variant) -> Dictionary:
expr = (c as String).strip_edges() expr = (c as String).strip_edges()
var w := str(p.get("when", "")).strip_edges() if p.get("when") != null else "" 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, 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)), "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}
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" ## Edge label for a pipe: "" (plain), "×2", "→ weapon" or "×2 → weapon"
@ -487,9 +443,6 @@ static func pipe_label(info: Dictionary) -> String:
parts.append("×%d" % int(info["count"])) parts.append("×%d" % int(info["count"]))
if str(info["save_as"]) != "": if str(info["save_as"]) != "":
parts.append("→ " + 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) return " ".join(parts)

View file

@ -1,220 +0,0 @@
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")

View file

@ -1 +0,0 @@
uid://02r1wlwv3fsf

View file

@ -1,665 +0,0 @@
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")

View file

@ -1 +0,0 @@
uid://i7gun1udginh

View file

@ -132,16 +132,6 @@ func _test_preview_content() -> void:
if d == null: if d == null:
return return
_check(d.board == main.data, "the dialog finds the board") _check(d.board == main.data, "the dialog finds the board")
# Plain words (the default): effects and counts read as phrases.
_check(d.plain, "previews read in plain words by default")
var pp := d.preview_for_option(0)
_check(_has(pp, "Gold −5") and _has(pp, "WHEN THIS COMES UP"), "the plain preview lists the option's effects in words")
pp.free()
var pq := d.preview_for_option(1)
_check(_has(pq, "×Terms"), "the plain preview names an expression count by its label")
pq.free()
# The rest checks the stored text (Text view).
d.plain = false
# Option 1 pipes to a ranged table, twice. # Option 1 pipes to a ranged table, twice.
var p := d.preview_for_option(0) var p := d.preview_for_option(0)
_check(p != null, "an option that pipes on has a preview") _check(p != null, "an option that pipes on has a preview")

View file

@ -1,356 +0,0 @@
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()

View file

@ -1 +0,0 @@
uid://bicuhdrq56on

View file

@ -1,570 +0,0 @@
extends SceneTree
## The Build inspector (docs/PLAIN.md §6): selection, the effects and
## condition builders, Otherwise, pipe inputs, check fields and the modifier
## picker, collection members, options source, the value picker, the
## Plain/Text switch, undo, and dirty/save.
## Run: godot --headless --path . -s res://tests/test_inspector.gd -- --sample
var _failures := 0
var main: Main
var insp: Inspector
func _init() -> void:
if not OS.get_cmdline_user_args().has("--sample"):
print("Run with -- --sample so the test can't touch saved data.")
quit(2)
return
main = load("res://ui/main.tscn").instantiate()
root.add_child(main)
for i in 5:
await process_frame
if main._saving_enabled:
print("Saving is enabled; refusing to run.")
quit(2)
return
main.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT)
main.size = Vector2(1440, 900)
main.set_mode(Main.Mode.BUILD)
insp = main.inspector
await _load()
await _test_selection()
await _test_effects()
await _test_unparseable()
await _test_conditions()
await _test_otherwise()
await _test_pipe_inputs()
await _test_check()
await _test_collection()
await _test_options()
await _test_value_picker()
await _test_rules_view()
await _test_undo()
await _test_dirty_and_save()
await _test_other_cards()
await _test_add_kinds()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
func _check(ok: bool, what: String) -> void:
if ok:
print(" ok %s" % what)
else:
_failures += 1
print(" FAIL %s" % what)
func _eq(a: Variant, b: Variant, what: String) -> void:
_check(a == b, "%s (got %s, want %s)" % [what, JSON.stringify(a), JSON.stringify(b)])
func _frames(n: int = 2) -> void:
for i in n:
await process_frame
func _board_dict() -> Dictionary:
return {"format_version": 2, "id": "insp-test", "name": "Inspector test", "tables": [
{"id": "gate", "name": "Force the gate", "kind": "check", "x": 40, "y": 40, "check_dice": "2d6",
"check_mod": "dm(@str)", "check_cmp": "ge", "check_target": "8",
"entries": [{"id": "e1", "text": "Success", "pipes": ["beyond"]}, {"id": "e2", "text": "Failure"}]},
{"id": "beyond", "name": "Beyond the gate", "x": 340, "y": 40, "entries": [
{"id": "e1", "text": "Store room"},
{"id": "e2", "text": "The warden's vault", "effects": "@luck -= 1", "pipes": [
{"table": "loot", "with": {"tier": "3"}, "when": "@luck >= 2"},
{"table": "curios", "with": {"tier": "1"}, "otherwise": true}]}]},
{"id": "loot", "name": "Loot", "x": 700, "y": 20, "inputs": [{"name": "tier", "label": "Tier", "default": "1"}],
"entries": [{"id": "e1", "text": "Silver"}]},
{"id": "curios", "name": "Curios", "x": 700, "y": 300, "inputs": [{"name": "tier", "label": "Tier", "default": "1"}],
"entries": [{"id": "e1", "text": "A curio"}]},
{"id": "learn", "name": "Learn", "kind": "choice", "choice": "pick", "x": 340, "y": 380,
"entries": [{"id": "e1", "text": "Option 1"}, {"id": "e2", "text": "Option 2"}]},
{"id": "str", "name": "Strength", "kind": "variable", "var_name": "str", "var_type": "number", "initial": "9", "x": 40, "y": 330, "entries": []},
{"id": "luck", "name": "Luck", "kind": "variable", "var_name": "luck", "var_type": "number", "initial": "2", "x": 40, "y": 470, "entries": []},
{"id": "skills", "name": "Skills", "kind": "variable", "var_name": "skill", "var_type": "collection", "x": 40, "y": 610, "entries": []},
{"id": "rt", "name": "Router", "kind": "router", "x": 1000, "y": 40, "entries": [
{"id": "c1", "text": "Strong", "when": "@str >= 8"}, {"id": "c2", "text": "Otherwise"}]},
{"id": "lp", "name": "Repeat", "kind": "loop", "loop_mode": "times", "loop_expr": "3", "x": 1000, "y": 300,
"entries": [{"id": "e1", "text": "Each time"}, {"id": "e2", "text": "Afterwards"}]},
]}
func _load() -> void:
main.data.load_dict(_board_dict())
main.lit_entries.clear()
main.lit_pipes.clear()
main.persistent_vars.clear()
main._rebuild_cards()
main.clear_inspector()
await _frames(4)
func _t(id: String) -> RollTable:
return main.data.get_table(id)
func _vault() -> TableEntry:
return _t("beyond").find_entry("e2")
# ---------- Selection ----------
func _test_selection() -> void:
print("Selection")
_check(insp.visible, "the inspector shows in Build mode")
_check(insp.selection.is_empty(), "nothing is selected at first")
_check(_has_text(insp, "Select a card, a result or a pipe to edit it."), "the empty state says how to select")
main.select_card("gate")
_eq(main.inspector_selection(), {"kind": "card", "tid": "gate"}, "select_card")
_check(insp.fields.has("check_dice"), "a check card shows its dice field")
main.select_result("beyond", "e2")
_eq(insp.selection.get("kind"), "result", "select_result")
_check(insp.effects != null and insp.pipe_parts.has("loot") and insp.pipe_parts.has("curios"), "a result shows its effects and both pipes")
main.select_pipe("beyond:e2>loot")
_eq(insp.selection.get("to"), "loot", "select_pipe")
_eq(insp.pipe_parts.keys(), ["loot"], "a pipe shows only its own box")
_eq(main.board.pipes.select_key, "beyond:e2>loot", "the selected pipe is highlighted on the board")
main.clear_inspector()
_check(insp.selection.is_empty(), "clear_inspector")
main.open_pipe_options("beyond:e2>curios", Vector2(10, 10))
_eq(insp.selection.get("to"), "curios", "clicking a pipe in Build selects it in the inspector")
main.request_table_settings("loot")
_eq(insp.selection, {"kind": "card", "tid": "loot"}, "the card's ⚙ selects the card")
main.select_result("beyond", "nope")
_eq(insp.selection.get("tid"), "loot", "a missing result isn't selected")
main.set_mode(Main.Mode.PLAY)
_check(not insp.visible and insp.selection.is_empty(), "Play hides and clears the inspector")
main.set_mode(Main.Mode.BUILD)
_check(insp.visible, "Build shows it again")
insp.set_collapsed(true)
_check(insp.custom_minimum_size.x == Inspector.STRIP, "the inspector collapses to a strip")
main.select_card("gate")
_check(not insp.collapsed, "selecting something opens it again")
# Deleting the selected card empties the inspector.
main.select_card("lp")
var keep := _t("lp").to_dict()
main.delete_table("lp")
await _frames(2)
_check(insp.selection.is_empty(), "deleting the selected card clears the inspector")
main.undo()
await _frames(2)
_check(_t("lp") != null, "(undo brings the card back)")
_eq(_t("lp").to_dict()["name"], keep["name"], "(same card)")
func _has_text(n: Node, s: String) -> bool:
for c in n.get_children():
if (c is Label and (c as Label).text == s) or _has_text(c, s):
return true
return false
# ---------- Effects ----------
func _test_effects() -> void:
print("Effects builder")
main.select_result("beyond", "e2")
var fx := insp.effects
_eq(fx.rows.size(), 1, "one row per statement")
_eq([fx.rows[0]["op"], fx.rows[0]["var"], fx.rows[0]["amount"]], ["subtract", "@luck", "1"], "the row reads Subtract 1 from Luck")
fx.set_row_amount(0, "2")
_eq(_vault().effects, "@luck -= 2", "changing the amount writes the statement")
fx.set_row_op(0, "add")
_eq(_vault().effects, "@luck += 2", "changing the op")
fx.add_row()
_eq(_vault().effects, "@luck += 2", "a new row isn't written until it's filled in")
fx.set_row_var(1, "@str")
_eq(_vault().effects, "@luck += 2\n@str += 1", "picking its value writes it, joined by a newline")
fx.set_row_op(1, "set")
fx.set_row_amount(1, "Millbrook")
_eq(_vault().effects, "@luck += 2\n@str = \"Millbrook\"", "a word typed as an amount becomes quoted text")
fx.set_row_amount(1, "1d6 + 2")
_eq(_vault().effects, "@luck += 2\n@str = 1d6 + 2", "an expression stays as written")
fx.set_row_op(1, "append")
fx.set_row_var(1, "@traits")
fx.set_row_amount(1, "Psionic")
_eq(_vault().effects, "@luck += 2\n@traits += \"Psionic\"", "Add to list")
fx.set_row_op(1, "remove")
_eq(_vault().effects, "@luck += 2\n@traits -= \"Psionic\"", "Remove from list")
fx.set_row_op(1, "reset")
_eq(_vault().effects, "@luck += 2\nreset @traits", "Clear")
fx.set_row_op(1, "multiply")
_eq(_vault().effects, "@luck += 2\n@traits *= 1", "Multiply after Clear starts at 1")
fx.remove_row(1)
_eq(_vault().effects, "@luck += 2", "× removes the row")
# Typing in the row's field.
var amt := InspectorKit.find_tagged(fx, "res.fx.0.amount") as LineEdit
amt.text = "3"
amt.text_changed.emit("3")
_eq(_vault().effects, "@luck += 3", "typing in the amount field writes the statement")
# Edit as text and back.
fx.set_text_mode(true)
_check(fx.text_mode and InspectorKit.find_tagged(fx, "res.fx.raw") != null, "Edit as text shows the whole effects text")
fx.set_raw("@luck -= 1\n@str += 2")
_eq(_vault().effects, "@luck -= 1\n@str += 2", "the text is written as typed")
fx.set_text_mode(false)
_eq(fx.rows.size(), 2, "Use the builder brings back one row per statement")
_eq(Builder.parse_effects(_vault().effects).size(), 2, "(still two statements)")
await _frames()
func _test_unparseable() -> void:
print("Unparseable statements")
_vault().effects = "@luck -= 1\n@gold += 2 +\n@str += 1"
main.mark_dirty()
await _frames(2)
var fx := insp.effects
_eq(fx.rows.size(), 3, "every statement gets a row")
_check(not fx.rows[1]["ok"], "the broken statement isn't a builder row")
var le := InspectorKit.find_tagged(fx, "res.fx.1.src") as LineEdit
_check(le != null and le.text == "@gold += 2 +", "it shows as a text field with its text")
fx.set_row_amount(0, "5")
_eq(_vault().effects, "@luck -= 5\n@gold += 2 +\n@str += 1", "editing another row keeps it exactly")
fx.set_text_mode(true)
fx.set_text_mode(false)
_check(fx.text_mode, "Use the builder waits until every statement parses")
fx.set_raw("@luck -= 5\n@gold += 2\n@str += 1")
fx.set_text_mode(false)
_check(not fx.text_mode and fx.rows.size() == 3 and fx.rows[1]["ok"], "then the builder takes over")
_vault().effects = "@luck -= 1"
main.mark_dirty()
await _frames(2)
# ---------- Conditions ----------
func _test_conditions() -> void:
print("Condition builder")
main.select_result("beyond", "e2")
var cond: ConditionBuilder = insp.pipe_parts["loot"]["when"]
_eq(cond.clauses, [{"var": "@luck", "cmp": "ge", "value": "2"}], "the Only if reads as one clause")
cond.add_clause()
_eq(_vault().when_for("loot"), "@luck >= 2", "an empty clause isn't written")
cond.set_clause_var(1, "@str")
cond.set_clause_value(1, "8")
_eq(_vault().when_for("loot"), "@luck >= 2 and @str >= 8", "two clauses join with and")
cond.set_join("or")
_eq(_vault().when_for("loot"), "@luck >= 2 or @str >= 8", "the switch makes it or")
cond.set_clause_cmp(1, "eq")
cond.set_clause_value(1, "Aslan")
_eq(_vault().when_for("loot"), "@luck >= 2 or @str = \"Aslan\"", "a word is compared as quoted text")
cond.set_clause_cmp(1, "set")
_eq(_vault().when_for("loot"), "@luck >= 2 or @str", "is set has no amount")
cond.remove_clause(1)
_eq(_vault().when_for("loot"), "@luck >= 2", "× removes a clause")
# A condition the builder can't show stays text.
_vault().set_pipe_when("loot", "@luck >= 2 and @str > 1 or @x")
main.mark_dirty()
await _frames(2)
cond = insp.pipe_parts["loot"]["when"]
_check(cond.text_mode, "mixed and/or shows as text")
cond.set_raw("@luck >= 3")
_eq(_vault().when_for("loot"), "@luck >= 3", "the text is written")
cond.set_raw("@luck >= = 3")
_eq(_vault().when_for("loot"), "@luck >= 3", "text that doesn't work isn't written")
cond.set_raw("@luck >= 2")
cond.set_text_mode(false)
_check(not cond.text_mode and cond.clauses.size() == 1, "Use the builder once it parses")
await _frames()
func _test_otherwise() -> void:
print("Otherwise")
main.select_result("beyond", "e2")
var loot_other: CheckBox = insp.pipe_parts["loot"]["otherwise"]
var cur_other: CheckBox = insp.pipe_parts["curios"]["otherwise"]
_check(cur_other.button_pressed and not cur_other.disabled, "the otherwise pipe is ticked")
_check(loot_other.disabled and not loot_other.button_pressed, "Otherwise is off while Only if is set")
insp.set_pipe_when("loot", "")
_check(not loot_other.disabled, "clearing Only if allows Otherwise")
insp.set_pipe_otherwise("loot", true)
_check(_vault().is_otherwise("loot") and loot_other.button_pressed, "ticking Otherwise writes it")
insp.set_pipe_when("loot", "@luck >= 2")
_check(not _vault().is_otherwise("loot") and loot_other.disabled, "an Only if turns Otherwise off")
insp.set_pipe_otherwise("curios", false)
_check(not _vault().is_otherwise("curios"), "unticking")
cur_other.toggled.emit(true)
_check(_vault().is_otherwise("curios"), "the checkbox writes it too")
insp.set_pipe_count("loot", "2")
_eq(_vault().count_text("loot"), "2", "count")
insp.set_pipe_count("loot", "@x +")
_eq(_vault().count_text("loot"), "2", "a bad count isn't written")
insp.set_pipe_save("loot", "@weapon")
_eq(_vault().save_for("loot"), "@weapon", "saves as")
insp.set_pipe_save("loot", "not a name")
_eq(_vault().save_for("loot"), "@weapon", "a bad name isn't saved")
insp.set_pipe_save("loot", "")
insp.set_pipe_count("loot", "1")
await _frames()
func _test_pipe_inputs() -> void:
print("Pipe inputs")
main.select_result("beyond", "e2")
var le: LineEdit = insp.pipe_parts["loot"]["inputs"]["tier"]
_eq(le.text, "3", "the target's input shows the passed value")
_eq(le.placeholder_text, "1", "its default is the placeholder")
le.text = "5"
le.text_changed.emit("5")
_eq(_vault().with_for("loot"), {"tier": "5"}, "typing writes pipe_with")
insp.set_pipe_input("loot", "tier", "@luck + 1")
_eq(_vault().with_for("loot"), {"tier": "@luck + 1"}, "an expression")
insp.set_pipe_input("loot", "tier", "@luck +")
_eq(_vault().with_for("loot"), {"tier": "@luck + 1"}, "a broken one isn't written")
insp.set_pipe_input("loot", "tier", "")
_eq(_vault().with_for("loot"), {}, "empty uses the default")
insp.set_pipe_input("loot", "tier", "3")
await _frames()
# ---------- Cards ----------
func _test_check() -> void:
print("Check card")
main.select_card("gate")
var t := _t("gate")
var sentence: Label = insp.fields["sentence"]
_eq(sentence.text, Describe.check(t, main.data), "a live sentence")
_check(sentence.text.contains("Strength"), "it names the modifier's value: %s" % sentence.text)
InspectorCard.set_check(insp, "check_target", "9")
_eq(t.check_target, "9", "target")
_check(sentence.text.contains("9"), "the sentence follows: %s" % sentence.text)
InspectorCard.set_check(insp, "check_cmp", "le")
_check(t.check_cmp == "le" and sentence.text.contains("or less"), "or less")
InspectorCard.set_check(insp, "check_dice", "3d6")
_eq(t.check_dice, "3d6", "dice")
InspectorCard.set_check(insp, "check_dice", "")
_eq(t.check_dice, "3d6", "empty dice aren't written")
_eq(InspectorCard.modifier_value("dm(@str)"), "@str", "dm(@str) reads as Strength in the picker")
_eq(InspectorCard.modifier_value(""), InspectorCard.NONE, "empty is none")
_eq(InspectorCard.modifier_value("@str + 1"), InspectorCard.AS_TEXT, "anything else is text")
var picker: ValuePicker = insp.fields["check_mod_picker"]
_eq(picker.value, "@str", "the picker shows the modifier's value")
picker.choose("@luck")
_eq(t.check_mod, "dm(@luck)", "picking Luck writes dm(@luck)")
InspectorCard.choose_modifier(insp, InspectorCard.NONE)
_eq(t.check_mod, "", "none clears it")
InspectorCard.choose_modifier(insp, InspectorCard.AS_TEXT)
var le: LineEdit = insp.fields.get("check_mod")
_check(le != null, "Edit as text shows the modifier as a field")
le.text = "@str - 1"
le.text_changed.emit("@str - 1")
_eq(t.check_mod, "@str - 1", "typed text is written")
insp.rebuild()
_check(insp.fields.has("check_mod"), "a modifier the picker can't show stays text")
InspectorCard.set_check(insp, "check_mod", "dm(@str)")
InspectorCard.set_check(insp, "check_cmp", "ge")
InspectorCard.set_check(insp, "check_target", "8")
InspectorCard.set_check(insp, "check_dice", "2d6")
await _frames()
func _test_collection() -> void:
print("Collection members")
main.select_card("skills")
var t := _t("skills")
_eq(insp.members(t), [], "no members at first")
var item := InspectorCard.add_member(insp, t)
_eq(item, "new", "+ Add member")
_eq(main.persistent_vars.get("skill_new", {}).get("value"), 0, "it's the board value @skill_new = 0")
InspectorCard.set_member(insp, t, "new", "2")
InspectorCard.rename_member(insp, t, "new", "pilot")
_check(not main.persistent_vars.has("skill_new"), "renaming drops the old name")
_eq(main.persistent_vars.get("skill_pilot", {}).get("value"), 2, "and keeps the value under the new one")
InspectorCard.add_member(insp, t)
InspectorCard.rename_member(insp, t, "new", "gun_combat")
_eq(insp.members(t), [["gun_combat", "0"], ["pilot", "2"]], "members list name and value")
_check(InspectorKit.find_tagged(insp, "member.pilot.value") != null, "each member has a value field")
InspectorCard.remove_member(insp, t, "gun_combat")
_eq(insp.members(t), [["pilot", "2"]], "× removes a member")
_eq(Describe.label("@skill_pilot", main.data), "Pilot", "(members are labelled through the collection)")
await _frames()
func _test_options() -> void:
print("Options source")
main.select_card("learn")
var t := _t("learn")
_check(not t.is_dynamic(), "a fixed list at first")
var err := InspectorCard.set_options(insp, "@skill_*", "")
_eq(err, "", "From a collection")
_check(t.is_dynamic() and t.options_from == "@skill_*", "options come from Skills")
var where: ConditionBuilder = insp.fields.get("options_where")
_check(where != null, "a where builder")
where.add_clause("option_value", "ge", "1")
_eq(t.options_where, "option_value >= 1", "where Its value is at least 1")
var picker: ValuePicker = insp.fields["options_from"]
_eq(picker.value, "@skill_*", "the source picker shows the collection")
_check(picker.items().any(func(it: Dictionary) -> bool: return it["name"] == "@skill_*"), "it offers collections")
_check(not picker.items().any(func(it: Dictionary) -> bool: return it["name"] == "@luck"), "but not numbers")
_eq(insp.apply_settings({"options_mode": "fixed"}, true), "", "back to a fixed list")
_check(t.options_from == "" and not t.is_dynamic(), "options_from is cleared")
await _frames()
func _test_value_picker() -> void:
print("Value picker")
var p := ValuePicker.new(main, "")
root.add_child(p)
var names := p.items().map(func(it: Dictionary) -> String: return it["name"])
_check(names.has("@luck") and names.has("@str"), "it lists the board's values")
var luck: Dictionary = p.items().filter(func(it: Dictionary) -> bool: return it["name"] == "@luck")[0]
_eq([luck["label"], luck["kind"], luck["group"]], ["Luck", "number", "Variables"], "with label, kind and group")
_check(names.find("@luck") < names.find("@skill_pilot") or not names.has("@skill_pilot"), "variables come first")
_check(names.has("@skill_pilot"), "collection members with values are offered")
_check(not names.has("@skill_*"), "collection patterns only where they fit")
p.allow_patterns = true
_check(p.items().any(func(it: Dictionary) -> bool: return it["name"] == "@skill_*" and it["group"] == "Collections"), "grouped under Collections")
_eq(p.filtered("lu").map(func(it: Dictionary) -> String: return it["name"]), ["@luck"], "search by label")
p.open_menu()
await _frames()
_check(p.shown_names().has("@luck"), "the open menu lists them")
p.close_menu()
var got: Array = []
p.value_chosen.connect(func(n: String) -> void: got.append(n))
p.choose("@str")
_eq(got, ["@str"], "choosing emits value_chosen")
_check(p.text.begins_with("Strength"), "the button shows the label: %s" % p.text)
var n := p.create_value("Fame", true)
_eq(n, "@fame", "+ New value… names it")
var card := main.variable_card("fame")
_check(card != null and card.name == "Fame", "Show on the board adds a variable card")
_eq(got.back(), "@fame", "and picks it")
var steps := main.edits.undo_stack.size()
n = p.create_value("Mood", false)
_eq(n, "@mood", "without a card")
_check(main.variable_card("mood") == null and main.edits.undo_stack.size() == steps, "no card, no board change")
p.queue_free()
await _frames()
func _test_rules_view() -> void:
print("Plain / Text switch")
var got: Array = []
main.rules_view_changed.connect(func(v: String) -> void: got.append(v))
_check(main.rules_plain() and main.rules_view() == "plain", "plain words by default")
main.select_result("beyond", "e2")
main.set_rules_view("text")
_eq(got, ["text"], "rules_view_changed fires")
_check(not main.rules_plain(), "rules_plain() follows")
_check(insp.effects.text_mode, "the inspector shows rule text")
_check((insp.pipe_parts["loot"]["when"] as ConditionBuilder).text_mode, "conditions too")
main.set_rules_view("text")
_eq(got.size(), 1, "setting the same view again doesn't fire")
main.set_rules_view("bogus")
_eq(main.rules_view(), "text", "unknown views are ignored")
main._rules_buttons[0].pressed.emit()
_eq(main.rules_view(), "plain", "the top-bar switch sets it")
_check(not insp.effects.text_mode, "builders are back")
await _frames()
func _test_undo() -> void:
print("Undo")
main._commit_edits()
main.select_result("beyond", "e2")
var before := _vault().effects
insp.effects.set_row_amount(0, "7")
main._commit_edits()
_eq(_vault().effects, "@luck -= 7", "(the edit)")
main.undo()
await _frames(2)
_eq(_vault().effects, before, "undo puts the effects back")
_eq(insp.effects.rows[0]["amount"], "1", "the inspector shows the old text")
_eq(insp.selection.get("eid"), "e2", "and keeps the selection")
main.redo()
await _frames(2)
_eq(_vault().effects, "@luck -= 7", "redo")
# Typing in a field is one step once it pauses.
var le: LineEdit = insp.fields["text"]
le.grab_focus()
var steps := main.edits.undo_stack.size()
for s in ["The vault", "The vaults", "The vaults!"]:
le.text = s
le.text_changed.emit(s)
_eq(main.edits.undo_stack.size(), steps, "typing waits for a pause")
main._commit_edits()
_eq(main.edits.undo_stack.size(), steps + 1, "then makes one step")
le.release_focus()
main.undo()
await _frames(2)
_eq(_vault().text, "The warden's vault", "one undo takes all the typing back")
await _frames()
func _test_dirty_and_save() -> void:
print("Dirty and save")
main.select_card("loot")
var rev := main.edit_rev
main._saving_enabled = true
main._save_timer.stop()
insp.apply_settings({"tags": "loot, treasure"})
_check(main.edit_rev > rev, "an inspector edit marks the board dirty")
_check(not main._save_timer.is_stopped(), "and schedules a save")
main._save_timer.stop()
main._saving_enabled = false
_eq(_t("loot").tags, ["loot", "treasure"], "tags")
var copy := TowerBoard.new()
copy.load_dict(main.data.to_dict())
_eq(copy.get_table("loot").tags, ["loot", "treasure"], "the saved form has it")
_eq(copy.get_table("beyond").find_entry("e2").with_for("loot"), {"tier": "3"}, "pipe inputs are saved")
main._commit_edits()
_check(main.can_undo(), "and it's an undo step")
await _frames()
func _test_other_cards() -> void:
print("Other cards")
main.select_card("loot")
var t := _t("loot")
var rows: Array = insp.fields["inputs_rows"]
_eq(rows.size(), 1, "declared inputs are listed")
var le := InspectorKit.find_tagged(insp, "card.in.0.default") as LineEdit
le.text = "2"
le.text_changed.emit("2")
_eq(t.inputs, [{"name": "tier", "label": "Tier", "default": "2"}], "editing a default")
(InspectorKit.find_tagged(insp, "card.name") as LineEdit).text_changed.emit("Treasure")
_eq(t.name, "Treasure", "name")
# Router cases.
main.select_card("rt")
var rt := _t("rt")
InspectorCard.add_case(insp)
_eq(rt.entries.size(), 3, "+ Add case")
_eq(rt.entries[2].id, "c2", "it goes before the Otherwise case")
insp.set_case_when(rt.entries[1].id, "@luck >= 1")
_eq(rt.entries[1].when, "@luck >= 1", "a case's condition")
_eq(Roller.lint_router(rt), [], "the router is fine")
# A router case from the result side.
main.select_result("rt", "c1")
_check(insp.case_builder != null and insp.case_builder.clauses.size() == 1, "a case result shows its condition builder")
# Loop.
main.select_card("lp")
InspectorCard.set_loop_mode(insp, "while")
_check(_t("lp").loop_mode == "while" and _t("lp").loop_expr == "i < 3", "a loop switches to while with a condition")
(insp.fields["loop_cond"] as ConditionBuilder).set_clause_value(0, "5")
_eq(_t("lp").loop_expr, "i < 5", "and the builder edits it")
InspectorCard.set_loop_mode(insp, "times")
_eq(_t("lp").loop_expr, "3", "back to times")
# Variable card.
main.select_card("luck")
_eq(insp.apply_settings({"initial": "3"}), "", "a variable's starting value")
_eq(_t("luck").initial, "3", "(written)")
_check(insp.apply_settings({"var_name": "Bad Name"}) != "", "a bad name is refused")
await _frames()
func _test_add_kinds() -> void:
print("+ Card ▾")
var labels: Array = main.ADD_KINDS.map(func(k: Array) -> String: return k[0])
_check(labels.any(func(s: String) -> bool: return s.begins_with("Check")), "Check card is in the menu")
_check(labels.any(func(s: String) -> bool: return s.begins_with("Collection")), "Collection is in the menu")
_eq(main._add_menu.text, "+ Card ▾", "the button reads + Card ▾")
var c := main.add_table(RollTable.KIND_CHECK)
_check(c.kind == RollTable.KIND_CHECK and c.name == "Check" and c.entries.size() == 2, "adding a check card")
_eq(insp.selection.get("tid"), c.id, "a new card is selected in the inspector")
var col := main.add_table(RollTable.KIND_VARIABLE, RollTable.VAR_COLLECTION)
_check(col.is_collection() and col.name == "Skills" and col.var_name == "skill_2", "adding a collection (%s, @%s)" % [col.name, col.var_name])
var v := main.add_table(RollTable.KIND_VARIABLE, "number")
_eq(v.name, "New variable", "a plain variable keeps its name")
await _frames()

View file

@ -1 +0,0 @@
uid://d2777xq1mqn57

View file

@ -466,10 +466,6 @@ func _test_dialog() -> void:
if c is Label and (c as Label).text == "1" and c.has_meta("option_value"): if c is Label and (c as Label).text == "1" and c.has_meta("option_value"):
badge = true badge = true
_check(badge, "the value shows as a badge") _check(badge, "the value shows as a badge")
var pp := d.preview_for_option(1)
_check(pp != null and _has(pp, "Chosen value +1") and _has(pp, "Gun Combat · level 2"), "the plain preview names the option, its level and the effect in words")
pp.free()
d.plain = false
var p := d.preview_for_option(1) var p := d.preview_for_option(1)
_check(p != null and _has(p, "@[option] += 1") and _has(p, "Next step"), "a dynamic option's preview shows the Chosen entry's effects and pipes") _check(p != null and _has(p, "@[option] += 1") and _has(p, "Next step"), "a dynamic option's preview shows the Chosen entry's effects and pipes")
_check(_has(p, "skill_gun_combat"), "the preview names the variable behind the option") _check(_has(p, "skill_gun_combat"), "the preview names the variable behind the option")
@ -484,20 +480,14 @@ func _test_dialog() -> void:
_check(got[0] != null and int(got[0]) == int((req["options"][2] as Dictionary)["index"]), "number keys answer the dynamic options") _check(got[0] != null and int(got[0]) == int((req["options"][2] as Dictionary)["index"]), "number keys answer the dynamic options")
await process_frame await process_frame
# TablePreview describes the card. # TablePreview describes the card.
var tpp := TablePreview.build(b, "raise", {"plain": true}) var tp := TablePreview.build(b, "raise")
_check(_has(tpp, "Options: your Skill values"), "the plain preview says where the options come from")
tpp.free()
var tp := TablePreview.build(b, "raise", {"plain": false})
_check(_has(tp, "Options: each @skill_* that's set"), "the preview describes where the options come from") _check(_has(tp, "Options: each @skill_* that's set"), "the preview describes where the options come from")
_check(_has(tp, "Chosen"), "the preview names the Chosen entry") _check(_has(tp, "Chosen"), "the preview names the Chosen entry")
tp.free() tp.free()
none.show_if = "@terms > 2" none.show_if = "@terms > 2"
tp = TablePreview.build(b, "raise", {"plain": false}) tp = TablePreview.build(b, "raise")
_check(_has(tp, "only if @terms > 2"), "the preview shows show_if conditions") _check(_has(tp, "only if @terms > 2"), "the preview shows show_if conditions")
tp.free() tp.free()
tp = TablePreview.build(b, "raise", {"plain": true})
_check(_has(tp, "only if Terms is more than 2"), "the plain preview shows show_if in words")
tp.free()
# ---------------------------------------------------------------- settings and card # ---------------------------------------------------------------- settings and card
@ -547,10 +537,6 @@ func _test_card() -> void:
main.data.tables.append(t) main.data.tables.append(t)
main.persistent_vars["skill_pilot"] = {"value": 1, "source": ""} main.persistent_vars["skill_pilot"] = {"value": 1, "source": ""}
main.persistent_vars["skill_admin"] = {"value": 0, "source": ""} main.persistent_vars["skill_admin"] = {"value": 0, "source": ""}
# These checks read the stored rule text (the Text view).
RulesView.fallback_plain = false
if main.has_method("set_rules_view"):
main.set_rules_view("text")
main._rebuild_cards() main._rebuild_cards()
await process_frame await process_frame
var card := main.card_for("raise_card") var card := main.card_for("raise_card")
@ -561,12 +547,9 @@ func _test_card() -> void:
main.set_mode(Main.Mode.BUILD) main.set_mode(Main.Mode.BUILD)
await process_frame await process_frame
card = main.card_for("raise_card") card = main.card_for("raise_card")
_check(_has(card, "only if @terms > 2"), "Build mode shows show_if under the option (edited in the inspector)") card._open_show_if["none"] = true
RulesView.fallback_plain = true
if main.has_method("set_rules_view"):
main.set_rules_view("plain")
card.rebuild() card.rebuild()
_check(_has(card, "only if Terms is more than 2"), "and in plain words in the Plain view") _check(_has(card, "Show only if"), "Build mode edits show_if under the option")
var d := TableSettingsDialog.new(t) var d := TableSettingsDialog.new(t)
main.add_child(d) main.add_child(d)
await process_frame await process_frame

View file

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

View file

@ -1 +0,0 @@
uid://c875lktcqrdsq

View file

@ -291,7 +291,6 @@ func _gui_input(ev: InputEvent) -> void:
if build_left: if build_left:
var key := pipes.pipe_at(world_mouse(), 11.0) var key := pipes.pipe_at(world_mouse(), 11.0)
if key != "": if key != "":
# The pipe opens in the inspector (Main.open_pipe_options).
main.open_pipe_options(key, mb.global_position) main.open_pipe_options(key, mb.global_position)
accept_event() accept_event()
return return
@ -311,7 +310,6 @@ func _gui_input(ev: InputEvent) -> void:
# A plain click on the felt (no drag) clears the selection. # A plain click on the felt (no drag) clears the selection.
if build_left and _press_at.x >= 0.0 and mb.position.distance_to(_press_at) < 4.0: if build_left and _press_at.x >= 0.0 and mb.position.distance_to(_press_at) < 4.0:
main.clear_selection() main.clear_selection()
main.clear_inspector()
_press_at = Vector2(-1, -1) _press_at = Vector2(-1, -1)
_panning = false _panning = false
mouse_default_cursor_shape = CURSOR_ARROW mouse_default_cursor_shape = CURSOR_ARROW

View file

@ -20,10 +20,6 @@ extends ModalCard
## Options from variables (docs/LOGIC.md §2a) come after the fixed ones, with ## Options from variables (docs/LOGIC.md §2a) come after the fixed ones, with
## their value as a badge on the right; their preview is the Chosen entry's. ## their value as a badge on the right; their preview is the Chosen entry's.
## ##
## Previews read rules in plain words (effects "Luck −1", pipe conditions
## "only if Luck is 2 or more", option sources) unless Main's rules view is
## Text (RulesView.plain); `plain` can also be set directly.
##
## The answer arrives through `reply.done`, a signal on a separate object so ## The answer arrives through `reply.done`, a signal on a separate object so
## the waiting roll never hangs: closing or freeing the dialog in any way ## the waiting roll never hangs: closing or freeing the dialog in any way
## (Esc, the window closing, a new roll replacing this one) answers null, ## (Esc, the window closing, a new roll replacing this one) answers null,
@ -53,8 +49,6 @@ const PREVIEW_WIDTH := 350.0
var board: TowerBoard var board: TowerBoard
## Board variables, so previews can show sheets filled in. ## Board variables, so previews can show sheets filled in.
var vars: Dictionary = {} var vars: Dictionary = {}
## Rules in plain words in the previews (from Main when it has a rules view).
var plain := true
var minimized := false var minimized := false
var preview_panel: PanelContainer var preview_panel: PanelContainer
var pill: PanelContainer var pill: PanelContainer
@ -242,13 +236,11 @@ func _build_text() -> void:
func _ready() -> void: func _ready() -> void:
super._ready() super._ready()
if board == null:
var m := get_parent() as Main var m := get_parent() as Main
if board == null and m: if m:
board = m.data board = m.data
vars = m.persistent_vars vars = m.persistent_vars
if m:
plain = RulesView.plain(m)
RulesView.watch(m, _on_rules_view_changed)
_refresh_preview() _refresh_preview()
if _spin: if _spin:
_spin.get_line_edit().grab_focus() _spin.get_line_edit().grab_focus()
@ -267,14 +259,6 @@ func _ready() -> void:
minimize.call_deferred() minimize.call_deferred()
func _on_rules_view_changed(_v: Variant = null) -> void:
var m := get_parent() as Main
if m:
plain = RulesView.plain(m)
_preview_for = -2
_refresh_preview()
## Enter on the number or text field, or OK. ## Enter on the number or text field, or OK.
func _confirm() -> void: func _confirm() -> void:
if _spin: if _spin:
@ -590,18 +574,12 @@ func preview_for_option(k: int) -> Control:
box.add_child(heading) box.add_child(heading)
var any := false var any := false
var o: Dictionary = (request.get("options", []) as Array)[k] if kind == "pick" else {} var o: Dictionary = (request.get("options", []) as Array)[k] if kind == "pick" else {}
var t := board.get_table(str(request.get("table_id", "")))
if o.get("dynamic", false): if o.get("dynamic", false):
# The variable (or list item) behind a dynamic option, and its value. # The variable (or list item) behind a dynamic option, and its value.
any = true any = true
var what := "option = %s" % str(o.get("option", "")) var what := "option = %s" % str(o.get("option", ""))
if str(o.get("value_text", "")) != "": if str(o.get("value_text", "")) != "":
what += " · value %s" % str(o["value_text"]) what += " · value %s" % str(o["value_text"])
if plain:
var src := RulesView.options_line(t, board, true) if t != null else ""
what = "%s%s" % [Formatter.strip_tags(str(o.get("label", o.get("option", "")))), (" · level %s" % o["value_text"]) if str(o.get("value_text", "")) != "" else ""]
if src != "":
what += "\n" + src
var ol := Style.make_label(what, Style.body_bold(), 13, RichText.VAR_INK) var ol := Style.make_label(what, Style.body_bold(), 13, RichText.VAR_INK)
ol.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART ol.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
ol.mouse_filter = Control.MOUSE_FILTER_IGNORE ol.mouse_filter = Control.MOUSE_FILTER_IGNORE
@ -612,13 +590,13 @@ func preview_for_option(k: int) -> Control:
var d := RichText.label(RichText.decorate(det), 14, Style.INK, false) var d := RichText.label(RichText.decorate(det), 14, Style.INK, false)
d.mouse_filter = Control.MOUSE_FILTER_IGNORE d.mouse_filter = Control.MOUSE_FILTER_IGNORE
box.add_child(d) box.add_child(d)
var fx: Array = Describe.effects(e.effects, board, t) if plain else Array(Effects.split(e.effects)) var fx := Effects.split(e.effects)
if not fx.is_empty(): if not fx.is_empty():
any = true any = true
box.add_child(_rule()) box.add_child(_rule())
box.add_child(section("When this comes up" if plain else "Effects")) box.add_child(section("Effects"))
for st: Variant in fx: for st in fx:
var l := Style.make_label(str(st), Style.body_bold(), 13, RichText.VAR_INK) var l := Style.make_label(st, Style.body_bold(), 13, RichText.VAR_INK)
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
l.mouse_filter = Control.MOUSE_FILTER_IGNORE l.mouse_filter = Control.MOUSE_FILTER_IGNORE
box.add_child(l) box.add_child(l)
@ -627,14 +605,7 @@ func preview_for_option(k: int) -> Control:
shown.append(tid) shown.append(tid)
any = true any = true
box.add_child(_rule()) box.add_child(_rule())
var how := Describe.pipe(e, tid, board) if plain else PipeLayer._pipe_tag(e, tid) box.add_child(TablePreview.build(board, tid, {"count": e.count_text(tid), "vars": vars}))
if how != "":
var hl := Style.make_label(("Then: " if plain else "pipe: ") + how, Style.body_bold(), 12, Style.COPPER_DARK)
hl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
hl.mouse_filter = Control.MOUSE_FILTER_IGNORE
hl.set_meta("pipe_line", true)
box.add_child(hl)
box.add_child(TablePreview.build(board, tid, {"count": e.count_text(tid), "vars": vars, "plain": plain}))
var mentioned: Array[String] = [] var mentioned: Array[String] = []
for name in TextExpander.references(e.text, func(n: String) -> String: return Roller.resolve(board, n)): for name in TextExpander.references(e.text, func(n: String) -> String: return Roller.resolve(board, n)):
var rid := Roller.resolve(board, name) var rid := Roller.resolve(board, name)
@ -645,7 +616,7 @@ func preview_for_option(k: int) -> Control:
box.add_child(_rule()) box.add_child(_rule())
box.add_child(section("Mentioned in the text")) box.add_child(section("Mentioned in the text"))
for rid in mentioned: for rid in mentioned:
box.add_child(TablePreview.build(board, rid, {"vars": vars, "plain": plain})) box.add_child(TablePreview.build(board, rid, {"vars": vars}))
if not any: if not any:
box.free() box.free()
return null return null

View file

@ -5,11 +5,6 @@ extends PanelContainer
## ##
## It ignores the mouse, so it never blocks clicks, stays inside the window, ## It ignores the mouse, so it never blocks clicks, stays inside the window,
## and hides itself as soon as the control that opened it is no longer hovered. ## and hides itself as soon as the control that opened it is no longer hovered.
##
## Hover summaries follow RulesView.plain(main): an entry's effects, show_if,
## router condition and pipe labels read in plain words or as written, and a
## step of the last roll (a chip, or a lit row on a card) adds its "Why this?"
## reasons (WhyPopover.why_lines).
const WIDTH := 300.0 const WIDTH := 300.0
const DELAY := 0.28 const DELAY := 0.28
@ -138,69 +133,12 @@ func show_table(owner: Control, tid: String, only_if_details: bool = false) -> v
func show_entry(owner: Control, tid: String, eid: String) -> void: func show_entry(owner: Control, tid: String, eid: String) -> void:
var t := main.data.get_table(tid) var t := main.data.get_table(tid)
var e := t.find_entry(eid) if t else null var e := t.find_entry(eid) if t else null
if e == null: if e == null or e.details.strip_edges() == "":
return
var plain := RulesView.plain(main)
var parts := PackedStringArray()
if e.details.strip_edges() != "":
parts.append(e.details)
var rules := rules_bbcode(t, e, main.data, plain)
if rules != "":
parts.append(rules)
if main.is_entry_lit(tid, eid):
var found := step_for(tid, eid)
if not found.is_empty():
var why := why_bbcode(found["steps"], int(found["index"]), main.data, plain)
if why != "":
parts.append(why)
if parts.is_empty():
return return
var shown := main.lit_text(tid, eid) var shown := main.lit_text(tid, eid)
if shown == "": if shown == "":
shown = RichText.preview(e.text, main.data) shown = RichText.preview(e.text, main.data)
show_for(owner, _short(Formatter.strip_tags(shown)), "\n\n".join(parts), Formatter.strip_tags(t.name)) show_for(owner, _short(Formatter.strip_tags(shown)), e.details, Formatter.strip_tags(t.name))
## An entry's rules as short BBCode lines: "only if …", "Changes: Luck −1 ·
## Gold + 2D", and "→ Loot: Tier 3 · only if Luck is 2 or more" for each pipe
## with options. Router conditions are on the row itself, so they're left out.
static func rules_bbcode(t: RollTable, e: TableEntry, board: TowerBoard, plain: bool) -> String:
var muted := Style.MUTED.to_html(false)
var lines := PackedStringArray()
if t.kind == RollTable.KIND_CHOICE and t.choice == "pick" and e.show_if.strip_edges() != "":
lines.append("[color=#%s]Offered[/color] %s" % [muted, RichText.plain(RulesView.show_if_line(e, board, plain))])
if e.effects.strip_edges() != "":
var fx: Array = Describe.effects(e.effects, board, t) if plain else Array(Effects.split(e.effects))
var ss := PackedStringArray()
for f: Variant in fx:
ss.append(RichText.plain(str(f)))
lines.append("[color=#%s]Changes:[/color] [b]%s[/b]" % [muted, " · ".join(ss)])
for to in e.pipes:
var lab := Describe.pipe(e, to, board) if plain else PipeLayer._pipe_tag(e, to)
if lab == "":
continue
var target := board.get_table(to) if board else null
var nm := Formatter.strip_tags(target.name) if target else to
lines.append("[color=#%s]→ %s:[/color] %s" % [muted, RichText.plain(nm), RichText.plain(lab)])
return "\n".join(lines)
## The "Why this?" reasons for steps[index] as a small BBCode section, or "".
static func why_bbcode(steps: Array, index: int, board: TowerBoard, plain: bool) -> String:
var ls := WhyPopover.why_lines(steps, index, board, plain)
if ls.is_empty():
return ""
return "[color=#%s][b]WHY THIS?[/b][/color]\n%s" % [Style.MUTED.to_html(false), WhyPopover.bbcode_list(ls)]
## The last step of the current roll for an entry: {"steps", "index"} or {}.
func step_for(tid: String, eid: String) -> Dictionary:
var steps: Array = main.current.get("steps", [])
for k in range(steps.size() - 1, -1, -1):
var s: Dictionary = steps[k]
if str(s.get("table_id", "")) == tid and str(s.get("entry_id", "")) == eid:
return {"steps": steps, "index": k}
return {}
## Plain one-line title, cut down to a readable length. ## Plain one-line title, cut down to a readable length.
@ -211,18 +149,13 @@ static func _short(s: String) -> String:
return s if s.length() <= 90 else s.substr(0, 88).strip_edges() + "…" return s if s.length() <= 90 else s.substr(0, 88).strip_edges() + "…"
## A result chip: the entry's details, else the table's, then the step's ## A result chip: the entry's details, else the table's.
## "Why this?" reasons when `steps` and `index` are given. func show_step(owner: Control, step: Dictionary) -> void:
func show_step(owner: Control, step: Dictionary, steps: Array = [], index: int = -1) -> void:
var t := main.data.get_table(str(step.get("table_id", ""))) var t := main.data.get_table(str(step.get("table_id", "")))
if t == null: if t == null:
return return
var e := t.find_entry(str(step.get("entry_id", ""))) var e := t.find_entry(str(step.get("entry_id", "")))
var body := e.details if e and e.details.strip_edges() != "" else t.details var body := e.details if e and e.details.strip_edges() != "" else t.details
if index >= 0:
var why := why_bbcode(steps, index, main.data, RulesView.plain(main))
if why != "":
body = (body.strip_edges() + "\n\n" + why) if body.strip_edges() != "" else why
if body.strip_edges() == "": if body.strip_edges() == "":
return return
var title := _short(Formatter.strip_tags(str(step.get("text", "")))) if e and e.details.strip_edges() != "" else Formatter.strip_tags(t.name) var title := _short(Formatter.strip_tags(str(step.get("text", "")))) if e and e.details.strip_edges() != "" else Formatter.strip_tags(t.name)
@ -291,21 +224,14 @@ func table_summary(t: RollTable) -> String:
RollTable.KIND_CHOICE: RollTable.KIND_CHOICE:
return {"pick": "Choice · %d options" % t.entries.size(), "number": "Choice · a number", "text": "Choice · open ended"}.get(t.choice, "Choice") return {"pick": "Choice · %d options" % t.entries.size(), "number": "Choice · a number", "text": "Choice · open ended"}.get(t.choice, "Choice")
RollTable.KIND_LOOP: RollTable.KIND_LOOP:
return "Loop · " + RulesView.loop_rule(t, main.data, RulesView.plain(main)) return "Loop · " + TableCard.loop_rule(t)
RollTable.KIND_VARIABLE: RollTable.KIND_VARIABLE:
if RulesView.plain(main):
return "Collection · kept between rolls" if t.is_collection() else "%s · kept between rolls" % t.var_type.capitalize()
return "Variable @%s · %s" % [t.var_name, t.var_type] return "Variable @%s · %s" % [t.var_name, t.var_type]
RollTable.KIND_CHECK:
return RulesView.check_line(t, main.data, RulesView.plain(main))
RollTable.KIND_SHEET: RollTable.KIND_SHEET:
return "Sheet" return "Sheet"
RollTable.KIND_ROUTER: RollTable.KIND_ROUTER:
return "Router · %d cases · the first true case is taken" % t.entries.size() return "Router · %d cases · the first true case is taken" % t.entries.size()
var dl := t.dice_label() var parts := PackedStringArray([t.dice_label()])
if t.is_expr_dice() and RulesView.plain(main):
dl = Describe.dice(t.dice, main.data)
var parts := PackedStringArray([dl])
parts.append("%d %s" % [t.entries.size(), "ranges" if t.is_ranged() else "results"]) parts.append("%d %s" % [t.entries.size(), "ranges" if t.is_ranged() else "results"])
if t.card_mode: if t.card_mode:
var left := main.cards_left(t.id) var left := main.cards_left(t.id)

View file

@ -1,669 +0,0 @@
class_name Inspector
extends PanelContainer
## The Build-mode inspector (docs/PLAIN.md §6): a panel docked right of the
## board that edits the selected card, result or pipe with fill-in builders.
## Plain words mode shows builders; Text mode shows the rule text.
##
## Every change goes through Main (mark_dirty), so it is saved and is an undo
## step; typing is one step once it pauses. The panel rebuilds when the
## selected card changes from outside (an undo, an edit on the card), and
## keeps focus in the field being typed in.
const WIDTH := 340.0
const STRIP := 30.0
var main: Main
## {kind: "card" | "result" | "pipe", tid, eid?, to?}, or {} for nothing.
var selection: Dictionary = {}
var collapsed := false
var _body: VBoxContainer
var _scroll: ScrollContainer
var _content: VBoxContainer
var _strip: PanelContainer
var _sig := ""
var _sync_queued := false
var _writing := false
## Run after every write, to refresh live sentences and problem lines.
var _live: Array[Callable] = []
var _title_label: Label
# Parts the tests drive (rebuilt with the panel).
var effects: EffectsBuilder
var show_if_builder: ConditionBuilder
var case_builder: ConditionBuilder
## target id -> {box, when (ConditionBuilder), otherwise (CheckBox), count, save, inputs: {name: LineEdit}, taken}
var pipe_parts: Dictionary = {}
## Named fields of the card section ("name", "dice", "check_mod", ...).
var fields: Dictionary = {}
func setup(p_main: Main) -> void:
main = p_main
theme = Style.card_theme()
custom_minimum_size = Vector2(WIDTH, 0)
size_flags_vertical = Control.SIZE_EXPAND_FILL
var sb := Style.box(Style.CARD, 0, [0, 0, 0, 0])
sb.border_width_left = 1
sb.border_color = Color(0, 0, 0, 0.25)
add_theme_stylebox_override("panel", sb)
var stack := Control.new()
stack.size_flags_vertical = Control.SIZE_EXPAND_FILL
add_child(stack)
_body = VBoxContainer.new()
_body.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
_body.add_theme_constant_override("separation", 0)
stack.add_child(_body)
_scroll = ScrollContainer.new()
_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
_scroll.size_flags_vertical = Control.SIZE_EXPAND_FILL
_body.add_child(_scroll)
var pad := MarginContainer.new()
pad.size_flags_horizontal = Control.SIZE_EXPAND_FILL
for k in ["margin_left", "margin_right"]:
pad.add_theme_constant_override(k, 16)
pad.add_theme_constant_override("margin_top", 14)
pad.add_theme_constant_override("margin_bottom", 18)
_scroll.add_child(pad)
_content = InspectorKit.vbox(14)
pad.add_child(_content)
_strip = PanelContainer.new()
_strip.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
_strip.add_theme_stylebox_override("panel", Style.box(Style.CARD, 0, [2, 8, 2, 8]))
var open := Button.new()
open.text = "«"
open.tooltip_text = "Show the inspector"
open.size_flags_vertical = Control.SIZE_SHRINK_BEGIN
Style.skin_button(open, Style.box(Color(0, 0, 0, 0), 5, [4, 2, 4, 2]), Style.box(Style.HOVER_ROW, 5, [4, 2, 4, 2]),
Style.box(Style.HOVER_ROW, 5, [4, 2, 4, 2]), Style.COPPER_DARK)
open.add_theme_font_size_override("font_size", 18)
open.pressed.connect(func() -> void: set_collapsed(false))
_strip.add_child(open)
_strip.hide()
stack.add_child(_strip)
rebuild()
# ---------- Selection ----------
func select(sel: Dictionary) -> void:
if collapsed:
set_collapsed(false)
selection = sel
rebuild()
_mark_cards()
func clear() -> void:
selection = {}
rebuild()
_mark_cards()
## Puts the copper selection bar on the selected result's row, and clears it
## everywhere else.
func _mark_cards() -> void:
if main == null:
return
var tid := str(selection.get("tid", ""))
var eid := str(selection.get("eid", "")) if str(selection.get("kind", "")) == "result" else ""
for c in main.cards.values():
var card := c as TableCard
if card and card.has_method("set_selected_entry"):
card.set_selected_entry(eid if card.table.id == tid else "")
func set_collapsed(on: bool) -> void:
collapsed = on
custom_minimum_size.x = STRIP if on else WIDTH
_body.visible = not on
_strip.visible = on
if main and main.state:
main.state.set_setting("inspector_collapsed", on)
func selected_table() -> RollTable:
if selection.is_empty() or main == null:
return null
return main.data.get_table(str(selection.get("tid", "")))
func selected_entry() -> TableEntry:
var t := selected_table()
if t == null or not selection.has("eid"):
return null
return t.find_entry(str(selection["eid"]))
## Rebuilds once, at the end of the frame, if the selection changed from outside.
func sync() -> void:
if _writing or _sync_queued:
return
_sync_queued = true
_do_sync.call_deferred()
func _do_sync() -> void:
_sync_queued = false
if _signature() != _sig:
rebuild()
func _signature() -> String:
var t := selected_table()
if selection.is_empty():
return ""
if t == null or (selection.has("eid") and selected_entry() == null):
return "gone"
var d := t.to_dict()
for k in ["x", "y", "collapsed"]:
d.erase(k)
var parts := PackedStringArray([JSON.stringify(d), main.rules_view(), str(main.mode)])
for x in main.data.tables:
if x.kind == RollTable.KIND_VARIABLE:
parts.append("%s|%s|%s" % [x.name, x.var_name, x.var_type])
for e in t.entries:
for p in e.pipes:
var target := main.data.get_table(p)
parts.append(("%s|%s" % [target.name, JSON.stringify(target.inputs)]) if target else "-")
parts.append(str(main.lit_pipes.has(Roller.pipe_key(t.id, e.id, p))))
parts.append(str(main.is_entry_lit(t.id, e.id)))
if t.is_collection():
parts.append(JSON.stringify(members(t)))
return str(hash("\n".join(parts)))
# ---------- Writing ----------
## After the inspector changed table `t`: Main refreshes the card(s) and
## records the undo step. `rebuild_panel` redraws the inspector too (for
## changes that add or remove rows).
func wrote(t: RollTable, all_cards: bool = false, rebuild_panel: bool = false) -> void:
_writing = true
main.inspector_edited(t.id, all_cards)
main.mark_dirty()
_writing = false
_sig = _signature()
for f in _live:
if f.is_valid():
f.call()
_refresh_title()
if rebuild_panel:
rebuild()
## Applies table settings through TableSettingsDialog.apply_settings (the
## same rules as the settings dialog). Returns "" or the problem.
func apply_settings(over: Dictionary, rebuild_panel: bool = false) -> String:
var t := selected_table()
if t == null:
return "Nothing selected"
var s := {"name": t.name, "details": t.details, "tags": ", ".join(t.tags), "ranged": t.is_ranged(),
"dice": t.dice, "card_mode": t.card_mode, "deck_empty": t.deck_empty}
s.merge(over, true)
var r := TableSettingsDialog.apply_settings(t, s)
if not r["ok"]:
return str(r["error"])
if r.get("deck_reset", false) and main.state and main.data.id != "":
main.state.clear_deck(main.data.id, t.id)
wrote(t, t.kind == RollTable.KIND_VARIABLE, rebuild_panel)
return ""
func set_entry_text(s: String) -> void:
var e := selected_entry()
if e and e.text != s:
e.text = s
wrote(selected_table())
func set_entry_details(s: String) -> void:
var e := selected_entry()
if e and e.details != s:
e.details = s
wrote(selected_table())
func set_entry_effects(s: String) -> void:
var e := selected_entry()
if e and e.effects != s:
e.effects = s
wrote(selected_table())
func set_entry_show_if(s: String) -> void:
var e := selected_entry()
if e and e.show_if != s.strip_edges() and TableSettingsDialog.when_error(s) == "":
e.show_if = s.strip_edges()
wrote(selected_table())
## A router case's condition ("" makes it the Otherwise case).
func set_case_when(eid: String, s: String) -> void:
var t := selected_table()
var e := t.find_entry(eid) if t else null
if e and e.when != s.strip_edges() and TableSettingsDialog.when_error(s) == "":
e.when = s.strip_edges()
wrote(t)
func _pipe_entry() -> TableEntry:
return selected_entry()
func set_pipe_when(to: String, s: String) -> void:
var e := _pipe_entry()
if e == null or PipePopover.when_error(s) != "" or s.strip_edges() == e.when_for(to):
return
e.set_pipe_when(to, s)
wrote(selected_table())
_refresh_otherwise(to)
func set_pipe_otherwise(to: String, on: bool) -> void:
var e := _pipe_entry()
if e == null or on == e.is_otherwise(to):
return
e.set_pipe_otherwise(to, on)
wrote(selected_table())
_refresh_otherwise(to)
## Sets one input value passed down the pipe ("" uses the card's default).
func set_pipe_input(to: String, input_name: String, expr: String) -> void:
var e := _pipe_entry()
if e == null:
return
var w := e.with_for(to)
var s := expr.strip_edges()
if s != "" and InspectorKit.expr_error(s) != "":
return
if s == "":
w.erase(input_name)
else:
w[input_name] = s
if w == e.with_for(to):
return
e.set_pipe_with(to, w)
wrote(selected_table())
func set_pipe_count(to: String, s: String) -> void:
var e := _pipe_entry()
if e == null or PipePopover._count_error(s) != "":
return
var before := e.count_text(to)
e.set_pipe_count(to, s.strip_edges() if s.strip_edges() != "" else "1")
if e.count_text(to) != before:
wrote(selected_table())
func set_pipe_save(to: String, s: String) -> void:
var e := _pipe_entry()
if e == null or _save_error(s) != "" or s.strip_edges() == e.save_for(to):
return
e.set_pipe_save(to, s)
wrote(selected_table())
func remove_pipe(to: String) -> void:
var t := selected_table()
var e := selected_entry()
if t == null or e == null:
return
var was_pipe := str(selection.get("kind", "")) == "pipe"
main.remove_pipe(Roller.pipe_key(t.id, e.id, to))
if was_pipe:
select({"kind": "result", "tid": t.id, "eid": e.id})
else:
rebuild()
static func _save_error(s: String) -> String:
var t := TemplateKit.probe(s.strip_edges())
if t == "" or RegEx.create_from_string(PipePopover.SAVE_PATTERN).search(t) != null:
return ""
return "Use a name like weapon, or @weapon to keep it between rolls."
# ---------- Collections ----------
## A collection card's members: Array of [item, value] (item without the stem).
func members(t: RollTable) -> Array:
var out: Array = []
var pre := t.var_name + "_"
var names: Array = main.persistent_vars.keys()
names.sort_custom(func(a: String, b: String) -> bool: return a.naturalnocasecmp_to(b) < 0)
for n: String in names:
if n.begins_with(pre) and n.length() > pre.length():
var v: Variant = main.persistent_vars[n]
out.append([n.substr(pre.length()), Expr.format_value(v.get("value") if v is Dictionary else v)])
return out
# ---------- Building ----------
func rebuild() -> void:
var focus_key := ""
var caret := -1
var f := get_viewport().gui_get_focus_owner() if is_inside_tree() else null
if f and is_ancestor_of(f) and f.has_meta(InspectorKit.KEY):
focus_key = str(f.get_meta(InspectorKit.KEY))
if f is LineEdit:
caret = (f as LineEdit).caret_column
for c in _content.get_children():
_content.remove_child(c)
c.queue_free()
_live.clear()
effects = null
show_if_builder = null
case_builder = null
pipe_parts.clear()
fields.clear()
var t := selected_table()
var e := selected_entry()
if selection.has("eid") and e == null:
t = null
if t == null:
selection = {}
_empty()
else:
match str(selection.get("kind", "card")):
"result":
_result_section(t, e)
"pipe":
_pipe_section(t, e, str(selection.get("to", "")))
_:
InspectorCard.build(self, _content, t)
_sig = _signature()
if main and main.board and main.board.pipes:
main.board.pipes.select_key = Roller.pipe_key(t.id, e.id, str(selection["to"])) if t and str(selection.get("kind", "")) == "pipe" else ""
if focus_key != "":
var c := InspectorKit.find_tagged(_content, focus_key)
if c:
c.grab_focus()
if c is LineEdit and caret >= 0:
(c as LineEdit).caret_column = caret
func _head(kind: String, title: String) -> Control:
var h := InspectorKit.hbox(6)
var v := InspectorKit.vbox(2)
v.size_flags_horizontal = Control.SIZE_EXPAND_FILL
v.add_child(InspectorKit.flabel(kind))
var tl := Style.make_label(title, Style.display(), 22, Style.INK)
_title_label = tl
tl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
tl.custom_minimum_size = Vector2(120, 0)
v.add_child(tl)
h.add_child(v)
var hide_b := Button.new()
hide_b.text = "»"
hide_b.tooltip_text = "Hide the inspector"
hide_b.size_flags_vertical = Control.SIZE_SHRINK_BEGIN
Style.skin_button(hide_b, Style.box(Color(0, 0, 0, 0), 5, [6, 0, 6, 2]), Style.box(Style.HOVER_ROW, 5, [6, 0, 6, 2]),
Style.box(Style.HOVER_ROW, 5, [6, 0, 6, 2]), Style.MUTED, Style.INK)
hide_b.add_theme_font_size_override("font_size", 18)
hide_b.focus_mode = Control.FOCUS_NONE
hide_b.pressed.connect(func() -> void: set_collapsed(true))
h.add_child(hide_b)
return h
## Keeps the heading in step with the name or text being typed.
func _refresh_title() -> void:
if not is_instance_valid(_title_label):
return
var t := selected_table()
match str(selection.get("kind", "")):
"card":
if t:
_title_label.text = _title_of(t.name, "(no name)")
"result":
var e := selected_entry()
if e:
_title_label.text = _title_of(e.text, "(no text)")
func _empty() -> void:
_content.add_child(_head("Inspector", "Nothing selected"))
_content.add_child(InspectorKit.note("Select a card, a result or a pipe to edit it.", Style.MUTED, 15))
_content.add_child(InspectorKit.note("Click a card's title for the card, a result's text for the result, or a pipe on the felt for its options.", Style.MUTED, 13))
static func _title_of(s: String, fallback: String) -> String:
var t := Formatter.strip_tags(s).strip_edges()
return t if t != "" else fallback
## A link back to the card the result or pipe belongs to.
func _card_link(t: RollTable) -> Button:
var b := InspectorKit.link("On %s · edit the card" % _title_of(t.name, "this card"), "Show the card's settings")
b.add_theme_color_override("font_color", Style.MUTED)
b.pressed.connect(func() -> void: select({"kind": "card", "tid": t.id}))
return b
func _result_section(t: RollTable, e: TableEntry) -> void:
_content.add_child(_head("Selected result", _title_of(e.text, "(no text)")))
_content.add_child(_card_link(t))
var plain := main.rules_plain()
if t.kind != RollTable.KIND_SHEET:
var le := InspectorKit.line(e.text, "What this result says")
InspectorKit.tag(le, "res.text")
le.text_changed.connect(set_entry_text)
fields["text"] = le
_content.add_child(InspectorKit.field("Text", le))
var det := InspectorKit.text_box(e.details, "Shown on hover (optional)", 36.0)
InspectorKit.tag(det, "res.details")
det.text_changed.connect(func() -> void: set_entry_details(det.text))
fields["details"] = det
_content.add_child(InspectorKit.field("Details", det))
if t.kind == RollTable.KIND_CHOICE and t.choice == "pick" and not (t.is_dynamic() and t.entries.find(e) == 0):
show_if_builder = ConditionBuilder.new()
show_if_builder.setup(main, e.show_if, not plain, "res.show_if", {"empty_note": "Always offered."})
show_if_builder.changed.connect(set_entry_show_if)
_content.add_child(InspectorKit.field("Offer only if", show_if_builder))
if t.kind == RollTable.KIND_ROUTER:
_content.add_child(InspectorCard.case_block(self, t, e))
effects = EffectsBuilder.new()
effects.setup(main, e.effects, t, not plain, "res.fx")
effects.changed.connect(set_entry_effects)
_content.add_child(InspectorKit.field("When this comes up", effects))
var go := InspectorKit.vbox(8)
if e.pipes.is_empty():
go.add_child(InspectorKit.note("No pipes yet. Drag from the ● at the end of this result to a card.", Style.MUTED, 14))
for p in e.pipes:
go.add_child(_pipe_box(t, e, p))
_content.add_child(InspectorKit.field("Then go to", go))
_lint_lines(t, e)
func _pipe_section(t: RollTable, e: TableEntry, to: String) -> void:
if not e.pipes.has(to):
_result_section(t, e)
return
var target := main.data.get_table(to)
_content.add_child(_head("Selected pipe", "%s → %s" % [_title_of(e.text, "(no text)"), _title_of(target.name, to) if target else to]))
var back := InspectorKit.link("Edit the whole result", "Show the result this pipe leaves from")
back.add_theme_color_override("font_color", Style.MUTED)
back.pressed.connect(func() -> void: select({"kind": "result", "tid": t.id, "eid": e.id}))
_content.add_child(back)
_content.add_child(_pipe_box(t, e, to))
_lint_lines(t, e)
## Problems and hints the board check finds on this result's pipes.
func _lint_lines(t: RollTable, e: TableEntry) -> void:
var box := InspectorKit.vbox(3)
var fill := func() -> void:
for c in box.get_children():
box.remove_child(c)
c.queue_free()
for it: Dictionary in Roller.lint_pipes(main.data):
if str(it["table_id"]) == t.id and str(it["entry_id"]) == e.id:
var hint := str(it.get("level", "error")) == "hint" or str(it["message"]).contains("otherwise")
box.add_child(InspectorKit.note(("Note: " if hint else "Problem: ") + str(it["message"]) + ".",
Style.MUTED if hint else Style.DANGER_INK, 13))
box.visible = box.get_child_count() > 0
fill.call()
_live.append(fill)
_content.add_child(box)
func _pipe_box(t: RollTable, e: TableEntry, to: String) -> Control:
var target := main.data.get_table(to)
var parts := {"inputs": {}}
var taken := main.lit_pipes.has(Roller.pipe_key(t.id, e.id, to))
var panel := PanelContainer.new()
var sb := Style.bordered(Style.box(InspectorKit.TAKEN_BG if taken else InspectorKit.BOX_BG, 8, [10, 9, 10, 10]), 1, Style.BRASS if taken else Style.RULE)
panel.add_theme_stylebox_override("panel", sb)
var v := InspectorKit.vbox(8)
panel.add_child(v)
parts["box"] = panel
parts["taken"] = taken
var head := InspectorKit.hbox(8)
head.add_child(InspectorKit.word("→", Style.COPPER, true))
var tn := Style.make_label(_title_of(target.name, to) if target else to + " (missing)", Style.display(), 19, Style.INK)
tn.size_flags_horizontal = Control.SIZE_EXPAND_FILL
tn.clip_text = true
head.add_child(tn)
if taken:
head.add_child(_chip("taken last roll", Style.BRASS_DARK, Style.LIT))
elif main.is_entry_lit(t.id, e.id):
head.add_child(Style.make_label("not taken", Style.body_bold(), 12, Style.MUTED))
v.add_child(head)
# Inputs the target declares (and any extra names the pipe passes).
var w := e.with_for(to)
var names: Array = target.input_names() if target else []
for nm: String in w:
if not names.has(nm):
names.append(nm)
for nm: String in names:
var decl: Dictionary = target.find_input(nm) if target else {}
var row := InspectorKit.hbox(6)
var lab := str(decl.get("label", "")) if not decl.is_empty() else ""
var cap := InspectorKit.word(lab if lab != "" else RollContext.pretty_name(nm))
cap.custom_minimum_size = Vector2(64, 0)
cap.tooltip_text = "Input %s of %s" % [nm, target.name if target else to]
row.add_child(cap)
var def := str(decl.get("default", ""))
var le := InspectorKit.amount(str(w.get(nm, "")), def if def != "" else "0")
le.tooltip_text = "An expression passed as %s. Empty uses the card's default%s." % [nm, (" (" + def + ")") if def != "" else ""]
InspectorKit.tag(le, "pipe.%s.in.%s" % [to, nm])
var err := InspectorKit.error_label()
var nm_c := nm
le.text_changed.connect(func(s: String) -> void:
var msg := InspectorKit.expr_error(s, "This value")
InspectorKit.show_error(err, msg)
InspectorKit.mark(le, msg == "")
set_pipe_input(to, nm_c, s)
)
row.add_child(le)
if decl.is_empty():
row.add_child(InspectorKit.word("(not an input of this card)", Style.MUTED))
(parts["inputs"] as Dictionary)[nm] = le
v.add_child(row)
v.add_child(err)
# Only if / Otherwise.
var cond := ConditionBuilder.new()
cond.setup(main, e.when_for(to), not main.rules_plain(), "pipe.%s.when" % to,
{"add_label": "+ Only if…" if e.when_for(to) == "" else "+ Add condition"})
cond.changed.connect(func(s: String) -> void: set_pipe_when(to, s))
parts["when"] = cond
var when_box := InspectorKit.vbox(4)
when_box.add_child(InspectorKit.flabel("Only if"))
when_box.add_child(cond)
v.add_child(when_box)
var other := InspectorKit.check_box("Otherwise", e.is_otherwise(to))
other.tooltip_text = "Runs only when none of this result's \"Only if\" pipes is true"
other.toggled.connect(func(on: bool) -> void: set_pipe_otherwise(to, on))
parts["otherwise"] = other
v.add_child(other)
# Count and saves as.
var cr := InspectorKit.flow()
cr.add_child(InspectorKit.word("Rolls"))
var count := InspectorKit.amount(e.count_text(to), "1")
count.tooltip_text = "A number, or an expression such as @terms, answer or 1d3 (worked out when the pipe runs)"
InspectorKit.tag(count, "pipe.%s.count" % to)
var cerr := InspectorKit.error_label()
count.text_changed.connect(func(s: String) -> void:
var msg := PipePopover._count_error(s)
InspectorKit.show_error(cerr, msg)
InspectorKit.mark(count, msg == "")
set_pipe_count(to, s)
)
cr.add_child(count)
cr.add_child(InspectorKit.word("times"))
var sr := InspectorKit.hbox(6)
sr.add_child(InspectorKit.word("Saves as"))
var save := InspectorKit.line(e.save_for(to), "nothing (or a name)")
save.tooltip_text = "Keep the result as a value: a name lasts one roll, @name is kept between rolls"
InspectorKit.tag(save, "pipe.%s.save" % to)
save.text_changed.connect(func(s: String) -> void:
var msg := _save_error(s)
InspectorKit.show_error(cerr, msg)
InspectorKit.mark(save, msg == "")
set_pipe_save(to, s)
)
sr.add_child(save)
parts["count"] = count
parts["save"] = save
v.add_child(cr)
v.add_child(sr)
v.add_child(cerr)
var rm := InspectorKit.link("Remove pipe", "Delete this pipe")
rm.add_theme_color_override("font_color", Style.DANGER_INK)
rm.add_theme_color_override("font_hover_color", Style.DANGER_INK)
rm.pressed.connect(func() -> void: remove_pipe(to))
v.add_child(rm)
pipe_parts[to] = parts
_refresh_otherwise(to)
return panel
## Otherwise is off and disabled while the pipe has an Only if.
func _refresh_otherwise(to: String) -> void:
var parts: Dictionary = pipe_parts.get(to, {})
var e := _pipe_entry()
if parts.is_empty() or e == null:
return
var cb := parts["otherwise"] as CheckBox
var has_when := e.when_for(to) != ""
cb.disabled = has_when
cb.set_pressed_no_signal(e.is_otherwise(to))
cb.tooltip_text = "Turn off \"Only if\" first: a pipe with a condition isn't an otherwise pipe" if has_when \
else "Runs only when none of this result's \"Only if\" pipes is true"
static func _chip(text: String, fg: Color, bg: Color) -> Control:
var p := PanelContainer.new()
p.add_theme_stylebox_override("panel", Style.bordered(Style.box(bg, 9, [7, 1, 7, 2]), 1, Style.BRASS))
p.add_child(Style.make_label(text, Style.body_bold(), 12, fg))
p.size_flags_vertical = Control.SIZE_SHRINK_CENTER
return p
## Closes any open value-picker menu (before an undo rebuilds the board).
func close_menus() -> void:
_close_pickers(self)
func _close_pickers(n: Node) -> void:
for c in n.get_children():
if c is ValuePicker:
(c as ValuePicker).close_menu()
_close_pickers(c)

View file

@ -1 +0,0 @@
uid://dsfd4orwwbxt3

View file

@ -1,694 +0,0 @@
class_name InspectorCard
extends RefCounted
## The card section of the inspector: name, details, tags and inputs for
## every card, then the kind's own fields (roll dice, check, choice, loop,
## router cases, variable, collection members, sheet template). Writes go
## through Inspector (apply_settings / wrote), so the settings dialog's rules
## and the undo history apply.
const KIND_NAMES := {
RollTable.KIND_ROLL: "Roll table", RollTable.KIND_CHOICE: "Choice", RollTable.KIND_LOOP: "Loop",
RollTable.KIND_VARIABLE: "Variable", RollTable.KIND_SHEET: "Sheet", RollTable.KIND_ROUTER: "Router",
RollTable.KIND_CHECK: "Check",
}
const DM_PATTERN := "^dm\\(\\s*(@[a-z_][a-z0-9_]*)\\s*\\)$"
const NONE := "__none"
const AS_TEXT := "__text"
static func build(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
var kind := "Collection" if t.is_collection() else str(KIND_NAMES.get(t.kind, "Card"))
box.add_child(insp._head("Selected card · " + kind, Inspector._title_of(t.name, "(no name)")))
var plain := insp.main.rules_plain()
var name := InspectorKit.line(t.name, "Name")
InspectorKit.tag(name, "card.name")
name.text_changed.connect(func(s: String) -> void:
if s.strip_edges() != "":
insp.apply_settings({"name": s})
)
insp.fields["name"] = name
box.add_child(InspectorKit.field("Label" if t.kind == RollTable.KIND_VARIABLE else "Name", name))
match t.kind:
RollTable.KIND_ROLL:
_roll(insp, box, t)
RollTable.KIND_CHECK:
_check(insp, box, t, plain)
RollTable.KIND_CHOICE:
_choice(insp, box, t, plain)
RollTable.KIND_LOOP:
_loop(insp, box, t, plain)
RollTable.KIND_ROUTER:
_router(insp, box, t, plain)
RollTable.KIND_VARIABLE:
if t.is_collection():
_collection(insp, box, t)
else:
_variable(insp, box, t)
RollTable.KIND_SHEET:
_sheet(insp, box, t)
var det := InspectorKit.text_box(t.details, "Notes about this card (optional)", 36.0)
InspectorKit.tag(det, "card.details")
det.text_changed.connect(func() -> void: insp.apply_settings({"details": det.text}))
insp.fields["details"] = det
box.add_child(InspectorKit.field("Details", det))
var tags := InspectorKit.line(", ".join(t.tags), "e.g. loot, town")
InspectorKit.tag(tags, "card.tags")
tags.text_changed.connect(func(s: String) -> void: insp.apply_settings({"tags": s}))
insp.fields["tags"] = tags
box.add_child(InspectorKit.field("Tags", tags))
if t.kind != RollTable.KIND_VARIABLE:
box.add_child(_inputs(insp, t))
var more := InspectorKit.link("More settings…", "Card mode, colours and the other settings")
more.pressed.connect(func() -> void: insp.main.open_table_settings(t.id))
box.add_child(more)
# ---------- Inputs (every rollable card) ----------
static func _inputs(insp: Inspector, t: RollTable) -> Control:
var v := InspectorKit.vbox(5)
v.add_child(InspectorKit.flabel("Inputs"))
v.add_child(InspectorKit.note("Values a pipe into this card can pass, like a Tier. Each one has a starting value.", Style.MUTED, 13))
var rows: Array = []
for inp: Dictionary in t.inputs:
rows.append(inp.duplicate())
insp.fields["inputs_rows"] = rows
var grid := GridContainer.new()
grid.columns = 4
grid.add_theme_constant_override("h_separation", 5)
grid.add_theme_constant_override("v_separation", 5)
v.add_child(grid)
var err := InspectorKit.error_label()
var write := func() -> void:
t.inputs = RollTable.clean_inputs(rows)
insp.wrote(t)
var lint := func() -> void:
var msgs := PackedStringArray()
for it: Dictionary in Roller.lint_inputs(insp.main.data, t):
if str(it["entry_id"]) == "":
msgs.append(str(it["message"]) + ".")
InspectorKit.show_error(err, "\n".join(msgs))
if not rows.is_empty():
for h in ["Name", "Label", "Default", ""]:
grid.add_child(InspectorKit.flabel(h))
for i in rows.size():
var r: Dictionary = rows[i]
for k in ["name", "label", "default"]:
var le := InspectorKit.line(str(r.get(k, "")), {"name": "tier", "label": "Tier", "default": "1"}[k], 0.0)
le.custom_minimum_size = Vector2(70, 0)
InspectorKit.tag(le, "card.in.%d.%s" % [i, k])
var key: String = k
le.text_changed.connect(func(s: String) -> void:
r[key] = s.strip_edges().trim_prefix("@").to_lower() if key == "name" else s
write.call()
)
grid.add_child(le)
var x := InspectorKit.xbutton("Remove this input")
x.pressed.connect(func() -> void:
rows.remove_at(i)
t.inputs = RollTable.clean_inputs(rows)
insp.wrote(t, false, true)
)
grid.add_child(x)
var add := InspectorKit.link("+ Add input")
add.pressed.connect(func() -> void:
var used := t.input_names()
var nm := "tier"
var k := 2
while used.has(nm):
nm = "input_%d" % k
k += 1
t.inputs.append({"name": nm, "label": RollContext.pretty_name(nm), "default": "1"})
insp.wrote(t, false, true)
)
v.add_child(add)
v.add_child(err)
lint.call()
insp._live.append(lint)
return v
# ---------- Roll ----------
static func _roll(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
var v := InspectorKit.vbox(6)
var ranged := t.is_ranged()
var dice := InspectorKit.line(t.dice, "2d6", 90.0)
InspectorKit.tag(dice, "card.dice")
insp.fields["dice"] = dice
var err := InspectorKit.error_label()
var seg := ModalCard.segmented(["Plain", "Ranged"], 1 if ranged else 0, func(i: int) -> void:
var msg := insp.apply_settings({"ranged": i == 1, "dice": dice.text.strip_edges() if dice.text.strip_edges() != "" else "1d6"}, true)
InspectorKit.show_error(err, msg)
)
v.add_child(seg)
if ranged:
var row := InspectorKit.hbox(6)
row.add_child(InspectorKit.word("Roll"))
row.add_child(dice)
v.add_child(row)
v.add_child(InspectorKit.note(Describe.dice(t.dice, insp.main.data), Style.MUTED, 13))
dice.text_changed.connect(func(s: String) -> void:
if not TableSettingsDialog.dice_ok_text(s):
InspectorKit.show_error(err, "“%s” isn't dice such as 2d6 or 1d100." % s.strip_edges())
InspectorKit.mark(dice, false)
return
InspectorKit.mark(dice, true)
InspectorKit.show_error(err, insp.apply_settings({"ranged": true, "dice": s.strip_edges()}))
)
var probs := t.range_problems()
if probs != "":
v.add_child(InspectorKit.note(probs, Style.WARN_INK, 13))
else:
v.add_child(InspectorKit.note("Each result is equally likely, unless you give it a weight on the card.", Style.MUTED, 13))
v.add_child(err)
box.add_child(InspectorKit.field("Rolls", v))
# ---------- Check ----------
## The modifier picker's value for check_mod text: "" -> none, "dm(@str)" ->
## "@str", anything else -> AS_TEXT.
static func modifier_value(mod: String) -> String:
var s := mod.strip_edges()
if s == "":
return NONE
var m := RegEx.create_from_string(DM_PATTERN).search(s)
return m.get_string(1) if m else AS_TEXT
static func _check(insp: Inspector, box: VBoxContainer, t: RollTable, plain: bool) -> void:
var main := insp.main
var sentence := InspectorKit.note("", Style.INK, 15)
sentence.add_theme_font_override("font", Style.body_bold())
var sp := PanelContainer.new()
sp.add_theme_stylebox_override("panel", Style.bordered(Style.box(InspectorKit.TAKEN_BG, 8, [10, 7, 10, 8]), 1, Style.BRASS))
sp.add_child(sentence)
box.add_child(sp)
insp.fields["sentence"] = sentence
var errs := InspectorKit.error_label()
var refresh := func() -> void:
sentence.text = Describe.check(t, main.data) if plain else "Roll %s%s, need %s %s" % [t.check_dice, (" + " + t.check_mod) if t.check_mod != "" else "", t.check_target, "or more" if t.check_cmp == "ge" else "or less"]
var msgs := PackedStringArray()
for it: Dictionary in Roller.lint_check(t):
msgs.append(str(it["message"]) + ".")
InspectorKit.show_error(errs, "\n".join(msgs))
insp._live.append(refresh)
var dice := InspectorKit.line(t.check_dice, "2d6", 80.0)
InspectorKit.tag(dice, "card.check_dice")
insp.fields["check_dice"] = dice
dice.text_changed.connect(func(s: String) -> void: set_check(insp, "check_dice", s))
var r1 := InspectorKit.flow()
r1.add_child(InspectorKit.word("Roll"))
r1.add_child(dice)
box.add_child(InspectorKit.field("Dice", r1))
# Modifier: [Strength ▾] modifier, none, or text.
var mv := modifier_value(t.check_mod)
var mod_box := InspectorKit.vbox(5)
var once := insp.has_meta("mod_text_once")
if once:
insp.remove_meta("mod_text_once")
if mv == AS_TEXT or not plain or once:
var le := InspectorKit.line(t.check_mod, "e.g. dm(@str) or @skill_melee")
InspectorKit.code(le)
InspectorKit.tag(le, "card.check_mod")
insp.fields["check_mod"] = le
var merr := InspectorKit.error_label()
le.text_changed.connect(func(s: String) -> void:
var msg := InspectorKit.expr_error(s, "The modifier")
InspectorKit.show_error(merr, msg)
InspectorKit.mark(le, msg == "")
if msg == "":
set_check(insp, "check_mod", s)
)
mod_box.add_child(le)
mod_box.add_child(merr)
var back := InspectorKit.link("Use the picker", "Pick a value's modifier instead")
back.disabled = modifier_value(t.check_mod) == AS_TEXT
back.tooltip_text = "Pick a value's modifier instead" if not back.disabled else "The picker shows \"none\" or one value's modifier, dm(@value)"
back.pressed.connect(func() -> void: insp.rebuild())
if plain:
mod_box.add_child(back)
else:
var row := InspectorKit.flow()
var picker := ValuePicker.new(main, mv if mv != NONE else NONE)
picker.kinds = ["number"]
picker.extras = [{"name": NONE, "label": "none", "kind": ""}, {"name": AS_TEXT, "label": "Edit as text…", "kind": ""}]
picker.set_value(mv)
insp.fields["check_mod_picker"] = picker
picker.value_chosen.connect(func(n: String) -> void: choose_modifier(insp, n))
row.add_child(picker)
row.add_child(InspectorKit.word("modifier" if mv != NONE else "", Style.INK))
mod_box.add_child(row)
mod_box.add_child(InspectorKit.note("A value's modifier is dm(value): −1 at 3–5, 0 at 6–8, +1 at 9–11 and so on.", Style.MUTED, 12))
box.add_child(InspectorKit.field("Modifier", mod_box))
var r3 := InspectorKit.flow()
r3.add_child(InspectorKit.word("Need"))
var target := InspectorKit.amount(t.check_target, "8")
InspectorKit.tag(target, "card.check_target")
insp.fields["check_target"] = target
target.text_changed.connect(func(s: String) -> void: set_check(insp, "check_target", s))
r3.add_child(target)
var cmp := InspectorKit.dropdown(["or more", "or less"], 0 if t.check_cmp == "ge" else 1)
cmp.item_selected.connect(func(k: int) -> void: set_check(insp, "check_cmp", "ge" if k == 0 else "le"))
insp.fields["check_cmp"] = cmp
r3.add_child(cmp)
box.add_child(InspectorKit.field("Target", r3))
box.add_child(errs)
box.add_child(InspectorKit.note("Success and Failure are the card's two results; select one to give it changes and pipes.", Style.MUTED, 13))
refresh.call()
## Sets a check field (check_dice, check_mod, check_target, check_cmp).
static func set_check(insp: Inspector, key: String, value: String) -> void:
var t := insp.selected_table()
if t == null or t.kind != RollTable.KIND_CHECK:
return
var s := value.strip_edges()
if key == "check_cmp":
if not RollTable.CHECK_CMPS.has(s):
return
elif key != "check_mod" and s == "":
return
if str(t.get(key)) == s:
return
t.set(key, s)
insp.wrote(t)
## The modifier picker: none, a value (dm(@value)) or Edit as text.
static func choose_modifier(insp: Inspector, n: String) -> void:
match n:
NONE:
set_check(insp, "check_mod", "")
insp.rebuild()
AS_TEXT:
_rebuild_as_text(insp)
_:
set_check(insp, "check_mod", "dm(%s)" % n)
insp.rebuild()
static func _rebuild_as_text(insp: Inspector) -> void:
# A one-shot flag: the next build shows the modifier as text.
insp.set_meta("mod_text_once", true)
insp.rebuild()
# ---------- Choice ----------
static func _choice(insp: Inspector, box: VBoxContainer, t: RollTable, plain: bool) -> void:
var main := insp.main
var err := InspectorKit.error_label()
var seg := ModalCard.segmented(TableSettingsDialog.CHOICE_LABELS, maxi(0, RollTable.CHOICES.find(t.choice)), func(i: int) -> void:
InspectorKit.show_error(err, insp.apply_settings({"choice": RollTable.CHOICES[i]}, true))
)
box.add_child(InspectorKit.field("Type", seg))
var q := InspectorKit.line(t.prompt, "Which one?")
InspectorKit.tag(q, "card.prompt")
q.text_changed.connect(func(s: String) -> void: insp.apply_settings({"prompt": s}))
insp.fields["prompt"] = q
box.add_child(InspectorKit.field("Question", q))
var save := InspectorKit.line(t.save_as, "nothing (e.g. career, or @career to keep)")
InspectorKit.tag(save, "card.save_as")
insp.fields["save_as"] = save
save.text_changed.connect(func(s: String) -> void:
var msg := Inspector._save_error(s)
InspectorKit.mark(save, msg == "")
InspectorKit.show_error(err, msg if msg != "" else insp.apply_settings({"save_as": s}))
)
box.add_child(InspectorKit.field("Save the answer as", save))
if t.choice == "number":
var r := InspectorKit.flow()
r.add_child(InspectorKit.word("From"))
var lo := InspectorKit.amount(t.min_expr, "0")
var hi := InspectorKit.amount(t.max_expr, "99")
InspectorKit.tag(lo, "card.min")
InspectorKit.tag(hi, "card.max")
lo.text_changed.connect(func(s: String) -> void: InspectorKit.show_error(err, insp.apply_settings({"min": s, "max": hi.text})))
hi.text_changed.connect(func(s: String) -> void: InspectorKit.show_error(err, insp.apply_settings({"min": lo.text, "max": s})))
r.add_child(lo)
r.add_child(InspectorKit.word("to"))
r.add_child(hi)
box.add_child(InspectorKit.field("Allowed answers", r))
if t.choice == "pick":
box.add_child(_options(insp, t, plain, err))
box.add_child(err)
## Pick cards: Fixed list, or From [collection or list ▾] where [condition].
static func _options(insp: Inspector, t: RollTable, plain: bool, err: Label) -> Control:
var main := insp.main
var v := InspectorKit.vbox(6)
var dynamic := t.is_dynamic()
var from_picker := ValuePicker.new(main, t.options_from)
from_picker.kinds = ["collection", "list"]
from_picker.allow_patterns = true
from_picker.placeholder = "a collection or list"
insp.fields["options_from"] = from_picker
var seg := ModalCard.segmented(["Fixed list", "From a value"], 1 if dynamic else 0, func(i: int) -> void:
if i == 0:
InspectorKit.show_error(err, insp.apply_settings({"options_mode": "fixed"}, true))
else:
var first := _first_source(main.data)
if first == "":
InspectorKit.show_error(err, "Add a collection (+ Card ▾ → Collection) or a list value first, then pick it here.")
return
InspectorKit.show_error(err, set_options(insp, first, ""))
)
v.add_child(seg)
if dynamic:
var row := InspectorKit.flow()
row.add_child(InspectorKit.word("From"))
from_picker.value_chosen.connect(func(n: String) -> void:
InspectorKit.show_error(err, set_options(insp, n, t.options_where)))
row.add_child(from_picker)
v.add_child(row)
var where := ConditionBuilder.new()
where.setup(main, t.options_where, not plain, "card.where", {"empty_note": "Every one is offered.",
"extras": [{"name": "option_value", "label": "Its value", "kind": "number"}, {"name": "option_label", "label": "Its name", "kind": "text"}],
"add_label": "+ Only where…"})
where.changed.connect(func(s: String) -> void:
if TableSettingsDialog.when_error(s) == "":
InspectorKit.show_error(err, set_options(insp, t.options_from, s)))
insp.fields["options_where"] = where
v.add_child(InspectorKit.word("where", Style.MUTED))
v.add_child(where)
var desc := Describe.options(t, main.data)
if desc != "" and plain:
v.add_child(InspectorKit.note("Offers %s, plus the fixed options. The Chosen result runs for the one picked." % desc, Style.MUTED, 13))
else:
v.add_child(InspectorKit.note("The player picks one of the card's results, or Random.", Style.MUTED, 13))
return InspectorKit.field("Options", v)
## The first collection (@stem_*) or list value on the board, or "".
static func _first_source(board: TowerBoard) -> String:
for k: Dictionary in Builder.known_values(board):
if str(k["kind"]) == "collection" or str(k["kind"]) == "list":
return str(k["name"])
return ""
## Options from `from` where `where` (a pick card). Returns "" or the problem.
static func set_options(insp: Inspector, from: String, where: String) -> String:
var t := insp.selected_table()
var was := t.is_dynamic()
return insp.apply_settings({"options_mode": "vars", "options_from": from, "options_where": where}, not was or from != t.options_from)
# ---------- Loop ----------
static func _loop(insp: Inspector, box: VBoxContainer, t: RollTable, plain: bool) -> void:
var labels := ["Times", "While", "Until"]
var err := InspectorKit.error_label()
var seg := ModalCard.segmented(labels, maxi(0, RollTable.LOOPS.find(t.loop_mode)), func(i: int) -> void:
set_loop_mode(insp, RollTable.LOOPS[i])
)
box.add_child(InspectorKit.field("Repeat", seg))
if t.loop_mode == "times":
var r := InspectorKit.flow()
r.add_child(InspectorKit.word("Run Each time"))
var n := InspectorKit.amount(t.loop_expr, "3")
InspectorKit.tag(n, "card.loop_expr")
insp.fields["loop_expr"] = n
n.text_changed.connect(func(s: String) -> void:
var msg := "Fill in how many times." if s.strip_edges() == "" else InspectorKit.expr_error(s, "The count")
InspectorKit.show_error(err, msg)
InspectorKit.mark(n, msg == "")
if msg == "" and s.strip_edges() != t.loop_expr:
t.loop_expr = s.strip_edges()
insp.wrote(t)
)
r.add_child(n)
r.add_child(InspectorKit.word("times, then Afterwards."))
box.add_child(r)
else:
var cond := ConditionBuilder.new()
cond.setup(insp.main, t.loop_expr, not plain, "card.loop_cond", {})
cond.changed.connect(func(s: String) -> void:
if s.strip_edges() != "" and TableSettingsDialog.when_error(s) == "" and s.strip_edges() != t.loop_expr:
t.loop_expr = s.strip_edges()
insp.wrote(t)
)
insp.fields["loop_cond"] = cond
var cap := "Keep going while" if t.loop_mode == "while" else "Stop once"
box.add_child(InspectorKit.field(cap, cond))
box.add_child(InspectorKit.note(TableSettingsDialog.LOOP_NOTES.get(t.loop_mode, ""), Style.MUTED, 13))
box.add_child(err)
static func set_loop_mode(insp: Inspector, m: String) -> void:
var t := insp.selected_table()
if t == null or m == t.loop_mode or not RollTable.LOOPS.has(m):
return
var cond_like := Builder.parse_condition(t.loop_expr)
var is_cond: bool = cond_like["ok"] and not (cond_like["clauses"] as Array).is_empty() \
and str((cond_like["clauses"] as Array)[0]["cmp"]) != "set"
if m == "times" and is_cond:
t.loop_expr = "3"
elif m != "times" and not is_cond:
t.loop_expr = "i < 3"
t.loop_mode = m
insp.wrote(t, false, true)
# ---------- Router ----------
static func _router(insp: Inspector, box: VBoxContainer, t: RollTable, plain: bool) -> void:
var v := InspectorKit.vbox(8)
for e in t.entries:
v.add_child(case_block(insp, t, e, true))
var add := InspectorKit.link("+ Add case", "Add a case before the Otherwise case")
add.pressed.connect(func() -> void: add_case(insp))
v.add_child(add)
var lint := InspectorKit.error_label()
var fill := func() -> void:
var msgs := PackedStringArray()
for it: Dictionary in Roller.lint_router(t):
msgs.append(str(it["message"]) + ".")
InspectorKit.show_error(lint, "\n".join(msgs))
fill.call()
insp._live.append(fill)
v.add_child(lint)
box.add_child(InspectorKit.field("Cases (the first that holds is taken)", v))
## One router case: its condition, or Otherwise for the last case.
static func case_block(insp: Inspector, t: RollTable, e: TableEntry, framed: bool = false) -> Control:
var i := t.entries.find(e)
var last := i == t.entries.size() - 1
var v := InspectorKit.vbox(6)
if framed:
var head := InspectorKit.hbox(6)
var cap := InspectorKit.word("%d. %s" % [i + 1, Inspector._title_of(e.text, "(no text)")], Style.INK, true)
cap.size_flags_horizontal = Control.SIZE_EXPAND_FILL
cap.clip_text = true
head.add_child(cap)
var open := InspectorKit.link("Edit", "Edit this case's result")
open.pressed.connect(func() -> void: insp.select({"kind": "result", "tid": t.id, "eid": e.id}))
head.add_child(open)
if t.entries.size() > 1:
var x := InspectorKit.xbutton("Delete this case")
x.pressed.connect(func() -> void: insp.main.delete_entry(t.id, e.id))
head.add_child(x)
v.add_child(head)
var other := e.when.strip_edges() == ""
if last:
var cb := InspectorKit.check_box("Otherwise (when no case above holds)", other)
cb.toggled.connect(func(on: bool) -> void:
if on:
insp.set_case_when(e.id, "")
insp.rebuild()
else:
insp.set_meta("open_case", e.id)
insp.rebuild()
)
v.add_child(cb)
var opening := insp.has_meta("open_case") and str(insp.get_meta("open_case")) == e.id
if not (last and other) or opening:
var cond := ConditionBuilder.new()
cond.setup(insp.main, e.when, not insp.main.rules_plain(), "case.%s" % e.id, {})
if other and cond.clauses.is_empty() and not cond.text_mode:
cond.add_clause()
cond.changed.connect(func(s: String) -> void:
if s.strip_edges() != "":
insp.set_case_when(e.id, s))
if not framed:
insp.case_builder = cond
var cap := "Taken when" if framed else "This case is taken when"
var fv := InspectorKit.vbox(4)
fv.add_child(InspectorKit.flabel(cap))
fv.add_child(cond)
if other and not last:
fv.add_child(InspectorKit.note("Empty, so this case is an Otherwise and the cases after it never run.", Style.WARN_INK, 13))
v.add_child(fv)
if opening:
insp.remove_meta("open_case")
if framed:
var p := PanelContainer.new()
p.add_theme_stylebox_override("panel", Style.bordered(Style.box(InspectorKit.BOX_BG, 8, [10, 8, 10, 9]), 1, Style.RULE))
p.add_child(v)
return p
return v
## Adds a case before a final Otherwise case (or at the end).
static func add_case(insp: Inspector) -> void:
var t := insp.selected_table()
if t == null:
return
var e := TableEntry.new(TowerBoard.new_id("e"), "Case %d" % (t.entries.size() + 1))
var at := t.entries.size()
if not t.entries.is_empty() and t.entries.back().when.strip_edges() == "":
at -= 1
t.entries.insert(at, e)
insp.set_meta("open_case", e.id)
insp.wrote(t, false, true)
# ---------- Variable ----------
static func _variable(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
var err := InspectorKit.error_label()
var vn := InspectorKit.line(t.var_name, "luck")
InspectorKit.code(vn)
InspectorKit.tag(vn, "card.var_name")
insp.fields["var_name"] = vn
vn.text_changed.connect(func(s: String) -> void:
var msg := insp.apply_settings({"var_name": s})
InspectorKit.mark(vn, msg == "")
InspectorKit.show_error(err, msg)
)
box.add_child(InspectorKit.field("Name in rules (@name)", vn))
var types := ["number", "text", "list"]
var seg := ModalCard.segmented(["Number", "Text", "List"], maxi(0, types.find(t.var_type)), func(i: int) -> void:
InspectorKit.show_error(err, insp.apply_settings({"var_type": types[i]}, true))
)
box.add_child(InspectorKit.field("Type", seg))
var init := InspectorKit.line(t.initial, "0" if t.var_type == "number" else "nothing")
InspectorKit.tag(init, "card.initial")
insp.fields["initial"] = init
init.text_changed.connect(func(s: String) -> void:
var msg := insp.apply_settings({"initial": s})
InspectorKit.mark(init, msg == "")
InspectorKit.show_error(err, msg)
)
box.add_child(InspectorKit.field("Starting value", init))
box.add_child(err)
# ---------- Collection ----------
static func _collection(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
var err := InspectorKit.error_label()
var vn := InspectorKit.line(t.var_name, "skill")
InspectorKit.code(vn)
InspectorKit.tag(vn, "card.var_name")
insp.fields["var_name"] = vn
vn.text_changed.connect(func(s: String) -> void:
var msg := insp.apply_settings({"var_name": s})
InspectorKit.mark(vn, msg == "")
InspectorKit.show_error(err, msg)
)
box.add_child(InspectorKit.field("Members are named", vn))
box.add_child(InspectorKit.note("Each member is the value @%s_<name>, e.g. @%s_pilot. Choices can offer “one of your %s”." % [t.var_name, t.var_name, Inspector._title_of(t.name, "members")], Style.MUTED, 13))
var v := InspectorKit.vbox(5)
var list := insp.members(t)
insp.fields["members"] = list
if list.is_empty():
v.add_child(InspectorKit.note("No members yet.", Style.MUTED, 14))
var grid := GridContainer.new()
grid.columns = 3
grid.add_theme_constant_override("h_separation", 6)
grid.add_theme_constant_override("v_separation", 5)
for pair: Array in list:
var item := str(pair[0])
var nm := InspectorKit.line(RollContext.pretty_name(item), item, 0.0)
nm.size_flags_horizontal = Control.SIZE_EXPAND_FILL
nm.tooltip_text = "@%s_%s" % [t.var_name, item]
InspectorKit.tag(nm, "member.%s.name" % item)
var commit_name := func() -> void:
var slug := JsonIO.slug(nm.text, "")
if slug == "" or slug == item:
return
rename_member(insp, t, item, slug)
nm.text_submitted.connect(func(_s: String) -> void: commit_name.call())
nm.focus_exited.connect(commit_name)
grid.add_child(nm)
var val := InspectorKit.amount(str(pair[1]), "0")
InspectorKit.tag(val, "member.%s.value" % item)
var commit_val := func() -> void:
if val.text.strip_edges() != str(pair[1]):
set_member(insp, t, item, val.text.strip_edges())
val.text_submitted.connect(func(_s: String) -> void: commit_val.call())
val.focus_exited.connect(commit_val)
grid.add_child(val)
var x := InspectorKit.xbutton("Remove this member")
x.pressed.connect(func() -> void: remove_member(insp, t, item))
grid.add_child(x)
v.add_child(grid)
var add := InspectorKit.link("+ Add member")
add.pressed.connect(func() -> void: add_member(insp, t))
v.add_child(add)
v.add_child(InspectorKit.note("Members are saved values of this board, like the Variables panel shows; they aren't part of undo.", Style.MUTED, 12))
box.add_child(InspectorKit.field("Members", v))
box.add_child(err)
static func set_member(insp: Inspector, t: RollTable, item: String, value: String) -> void:
insp.main.set_collection_member(t, item, value)
insp.rebuild()
static func rename_member(insp: Inspector, t: RollTable, old_item: String, new_item: String) -> void:
var cur: Variant = insp.main.persistent_vars.get("%s_%s" % [t.var_name, old_item])
var value := Expr.format_value(cur.get("value") if cur is Dictionary else cur)
insp.main.remove_collection_member(t, old_item)
insp.main.set_collection_member(t, new_item, value)
insp.rebuild()
static func remove_member(insp: Inspector, t: RollTable, item: String) -> void:
insp.main.remove_collection_member(t, item)
insp.rebuild()
static func add_member(insp: Inspector, t: RollTable) -> String:
var used := {}
for pair: Array in insp.members(t):
used[str(pair[0])] = true
var item := "new"
var k := 2
while used.has(item):
item = "new_%d" % k
k += 1
insp.main.set_collection_member(t, item, "0")
insp.rebuild()
var nm := InspectorKit.find_tagged(insp, "member.%s.name" % item) as LineEdit
if nm and nm.is_inside_tree():
nm.grab_focus()
nm.select_all()
return item
# ---------- Sheet ----------
static func _sheet(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
var tpl := InspectorKit.text_box(t.entries[0].text if not t.entries.is_empty() else "", "[b]{@name}[/b]\nStrength {@str}", 120.0)
InspectorKit.code(tpl)
InspectorKit.tag(tpl, "card.template")
insp.fields["template"] = tpl
tpl.text_changed.connect(func() -> void: insp.apply_settings({"template": tpl.text}))
box.add_child(InspectorKit.field("Template", tpl))
box.add_child(InspectorKit.note("Write {@value} where a value goes. The sheet shows the values as they are now.", Style.MUTED, 13))

View file

@ -1 +0,0 @@
uid://b13ma21b5hlrb

View file

@ -1,247 +0,0 @@
class_name ConditionBuilder
extends VBoxContainer
## A condition editor: clauses `[value ▾] [comparison ▾] [amount] ×`, an
## and/or switch once there are two, and "+ Add condition"
## (Builder.parse_condition / condition_text). A condition the builder can't
## show (mixed and/or, dice, functions…) is a text field with its problem;
## "Edit as text" and "Use the builder" switch between the two.
## Emits `changed(text)`; clauses not filled in yet are left out.
signal changed(text: String)
const CMPS := ["eq", "ne", "ge", "le", "gt", "lt", "has", "set", "unset"]
const CMP_LABELS := ["is", "is not", "is at least", "is at most", "is more than", "is less than", "includes", "is set", "is not set"]
var main: Main
var join := "and"
var clauses: Array[Dictionary] = []
var text_mode := false
## What an empty condition means, shown when there are no clauses ("Always").
var empty_note := ""
## Extra values for the pickers ([{name, label, kind}]), e.g. option_value.
var extras: Array = []
## Names that stay unquoted in amounts (chain names, inputs).
var known: Array = []
var add_label := "+ Add condition"
var _raw := ""
var _key := "cond"
func setup(p_main: Main, expr: String, as_text: bool, key: String = "cond", opts: Dictionary = {}) -> void:
main = p_main
_key = key
empty_note = str(opts.get("empty_note", ""))
extras = opts.get("extras", [])
add_label = str(opts.get("add_label", add_label))
known = []
for x: Dictionary in extras:
known.append(str(x["name"]))
if main:
for k: Dictionary in Builder.known_values(main.data):
if not str(k["name"]).begins_with("@"):
known.append(str(k["name"]))
add_theme_constant_override("separation", 6)
size_flags_horizontal = Control.SIZE_EXPAND_FILL
_raw = expr.strip_edges()
var m := Builder.parse_condition(_raw)
text_mode = as_text or not m["ok"]
if m["ok"]:
join = str(m["join"])
clauses.clear()
for c: Dictionary in m["clauses"]:
clauses.append(c.duplicate())
_render()
func text() -> String:
if text_mode:
return _raw.strip_edges()
var parts := PackedStringArray()
for c in clauses:
var t := Builder.clause_text(c)
if t != "":
parts.append(t)
return (" %s " % join).join(parts)
func _emit() -> void:
changed.emit(text())
# ---------- Editing (also used by tests) ----------
func add_clause(v: String = "", cmp: String = "ge", value: String = "") -> void:
clauses.append({"var": v, "cmp": cmp, "value": value})
_render()
_emit()
func remove_clause(i: int) -> void:
if i < 0 or i >= clauses.size():
return
clauses.remove_at(i)
_render()
_emit()
func set_join(j: String) -> void:
if j != "and" and j != "or":
return
join = j
_render()
_emit()
func set_clause_var(i: int, n: String) -> void:
clauses[i]["var"] = n
_render()
_emit()
func set_clause_cmp(i: int, cmp: String) -> void:
clauses[i]["cmp"] = cmp
if cmp == "set" or cmp == "unset":
clauses[i]["value"] = ""
_render()
_emit()
## Sets a clause's amount from what a person typed (text gets quoted).
func set_clause_value(i: int, typed: String) -> void:
clauses[i]["value"] = InspectorKit.value_token(typed, known)
_emit()
func set_text_mode(on: bool) -> void:
if on == text_mode:
return
if on:
_raw = text()
text_mode = true
else:
var m := Builder.parse_condition(_raw)
if not m["ok"]:
return
join = str(m["join"])
clauses.clear()
for c: Dictionary in m["clauses"]:
clauses.append(c.duplicate())
text_mode = false
_render()
func set_raw(t: String) -> void:
_raw = t
if TableSettingsDialog.when_error(t) == "":
_emit()
# ---------- UI ----------
func _render() -> void:
var focus_key := ""
var f := get_viewport().gui_get_focus_owner() if is_inside_tree() else null
if f and is_ancestor_of(f) and f.has_meta(InspectorKit.KEY):
focus_key = str(f.get_meta(InspectorKit.KEY))
for c in get_children():
remove_child(c)
c.queue_free()
if text_mode:
_render_text()
else:
if clauses.is_empty() and empty_note != "":
add_child(InspectorKit.note(empty_note, Style.MUTED, 14))
if clauses.size() > 1:
var jr := InspectorKit.hbox(6)
jr.add_child(InspectorKit.word("Needs", Style.MUTED))
var jd := InspectorKit.dropdown(["all of these (and)", "any of these (or)"], 0 if join == "and" else 1)
jd.tooltip_text = "And: every condition must hold. Or: one is enough."
jd.item_selected.connect(func(k: int) -> void: set_join("and" if k == 0 else "or"))
jr.add_child(jd)
add_child(jr)
for i in clauses.size():
add_child(_clause_row(i))
var foot := InspectorKit.hbox(12)
var add := InspectorKit.link(add_label, "Add a comparison")
add.pressed.connect(func() -> void: add_clause())
foot.add_child(add)
var as_text := InspectorKit.link("Edit as text", "Edit this condition as rule text")
as_text.add_theme_color_override("font_color", Style.MUTED)
as_text.pressed.connect(func() -> void: set_text_mode(true))
foot.add_child(as_text)
add_child(foot)
if focus_key != "":
var c := InspectorKit.find_tagged(self, focus_key)
if c:
c.grab_focus.call_deferred()
func _render_text() -> void:
var le := InspectorKit.line(_raw, "e.g. @str >= 8 (empty: always)")
InspectorKit.code(le)
InspectorKit.tag(le, _key + ".raw")
var err := InspectorKit.error_label()
var back := InspectorKit.link("Use the builder", "Show this condition as rows")
var check := func() -> void:
var e := TableSettingsDialog.when_error(_raw)
InspectorKit.show_error(err, "" if e == "" else "This condition can't be worked out: " + e)
InspectorKit.mark(le, e == "")
var m := Builder.parse_condition(_raw)
back.disabled = not m["ok"]
back.tooltip_text = "Show this condition as rows" if m["ok"] else "The builder can't show this (%s), so it stays as text" % str(m.get("error", "")).to_lower()
le.text_changed.connect(func(s: String) -> void:
set_raw(s)
check.call()
)
add_child(le)
add_child(err)
back.pressed.connect(func() -> void: set_text_mode(false))
add_child(back)
check.call()
func _clause_row(i: int) -> Control:
var c := clauses[i]
var v := InspectorKit.vbox(3)
var f := InspectorKit.flow()
v.add_child(f)
var picker := ValuePicker.new(main, str(c["var"]))
picker.extras = extras
picker.value_chosen.connect(func(n: String) -> void: set_clause_var(i, n))
f.add_child(picker)
var cmp := str(c["cmp"])
var dd := InspectorKit.dropdown(CMP_LABELS, maxi(0, CMPS.find(cmp)))
dd.item_selected.connect(func(k: int) -> void: set_clause_cmp(i, CMPS[k]))
f.add_child(dd)
var err := InspectorKit.error_label()
var le: LineEdit = null
if cmp != "set" and cmp != "unset":
le = InspectorKit.amount(InspectorKit.shown_token(str(c["value"])), "8")
le.tooltip_text = "A number, a word, or a value such as @soc"
InspectorKit.tag(le, "%s.%d.value" % [_key, i])
var lref := le
le.text_changed.connect(func(s: String) -> void:
set_clause_value(i, s)
_check_clause(i, lref, err)
)
f.add_child(le)
var x := InspectorKit.xbutton("Remove this condition")
x.pressed.connect(remove_clause.bind(i))
f.add_child(x)
v.add_child(err)
_check_clause(i, le, err)
return v
func _check_clause(i: int, le: LineEdit, err: Label) -> void:
var c := clauses[i]
var msg := ""
if str(c["var"]) == "":
msg = "Pick a value to compare."
elif str(c["cmp"]) != "set" and str(c["cmp"]) != "unset" and str(c["value"]) == "":
msg = "Fill in what to compare with."
elif Builder.clause_text(c) != "" and TableSettingsDialog.when_error(Builder.clause_text(c)) != "":
msg = "This can't be worked out: " + TableSettingsDialog.when_error(Builder.clause_text(c))
InspectorKit.show_error(err, msg)
if le:
InspectorKit.mark(le, msg == "" or str(c["var"]) == "")

View file

@ -1 +0,0 @@
uid://dj44x24wmyugq

View file

@ -1,319 +0,0 @@
class_name EffectsBuilder
extends VBoxContainer
## The inspector's "When this comes up" editor: one row per effect statement
## (Builder.parse_effects), each `[op ▾] [amount] to/from [value ▾] ×`, plus
## "+ Add a change". A statement the builder can't show stays a text field
## with its problem. "Edit as text" switches to the whole effects text, and
## "Use the builder" switches back when every statement parses.
## Emits `changed(text)` with the statements (Builder.effect_text) joined by
## newlines; rows not filled in yet are left out.
signal changed(text: String)
const OPS := ["set", "add", "subtract", "multiply", "divide", "reset", "append", "remove"]
const OP_LABELS := ["Set", "Add", "Subtract", "Multiply", "Divide", "Clear", "Add to list", "Remove from list"]
var main: Main
var table: RollTable
## Each row: a Builder model ({ok, op, var, amount}) or {ok: false, src, error}.
var rows: Array[Dictionary] = []
var text_mode := false
var _raw := ""
var _key := "fx"
func setup(p_main: Main, text: String, p_table: RollTable, as_text: bool, key: String = "fx") -> void:
main = p_main
table = p_table
_key = key
_raw = text
add_theme_constant_override("separation", 6)
size_flags_horizontal = Control.SIZE_EXPAND_FILL
rows.clear()
for m in Builder.parse_effects(text):
rows.append(m)
# One unreadable statement doesn't turn the whole field into text: it
# shows as a text row among the others. Text mode starts as text.
text_mode = as_text
_render()
static func _all_ok(text: String) -> bool:
for m in Builder.parse_effects(text):
if not m["ok"]:
return false
return true
## The effects text the rows stand for.
func text() -> String:
if text_mode:
return _raw.strip_edges()
var parts := PackedStringArray()
for m in rows:
var t := ""
if m["ok"]:
t = Builder.effect_text(m)
else:
t = str(m.get("src", "")).strip_edges()
if t != "":
parts.append(t)
return "\n".join(parts)
func _emit() -> void:
changed.emit(text())
func _known_names() -> Array:
var out: Array = []
if main:
for k: Dictionary in Builder.known_values(main.data):
if not str(k["name"]).begins_with("@"):
out.append(str(k["name"]))
if table:
out.append_array(table.input_names())
return out
# ---------- Editing (also used by tests) ----------
func add_row() -> void:
rows.append({"ok": true, "op": "add", "var": "", "amount": "1"})
_render()
_emit()
func remove_row(i: int) -> void:
if i < 0 or i >= rows.size():
return
rows.remove_at(i)
_render()
_emit()
func set_row_op(i: int, op: String) -> void:
var m := rows[i]
if not m["ok"] or not OPS.has(op):
return
var was := str(m["op"])
m["op"] = op
var amt := str(m.get("amount", ""))
var listy := op == "append" or op == "remove"
var was_listy := was == "append" or was == "remove"
if op == "reset":
m["amount"] = ""
elif listy and not was_listy:
m["amount"] = Builder.unquote(amt)
elif not listy and was_listy:
m["amount"] = InspectorKit.amount_expr(amt, _known_names()) if amt != "" else ""
elif amt == "" and was == "reset":
m["amount"] = "1"
_render()
_emit()
## Sets a row's amount from what a person typed (quoted when it's text).
func set_row_amount(i: int, typed: String, render: bool = false) -> void:
var m := rows[i]
if not m["ok"]:
return
var listy := str(m["op"]) == "append" or str(m["op"]) == "remove"
m["amount"] = typed.strip_edges() if listy else InspectorKit.amount_expr(typed, _known_names())
if render:
_render()
_emit()
func set_row_var(i: int, n: String) -> void:
var m := rows[i]
if not m["ok"]:
return
m["var"] = n
_render()
_emit()
## A text row's statement.
func set_row_src(i: int, src: String) -> void:
var m := rows[i]
m["src"] = src
var p := Builder.parse_effect(src)
m["error"] = str(p.get("error", ""))
_emit()
func set_text_mode(on: bool) -> void:
if on == text_mode:
return
if on:
_raw = text()
text_mode = true
else:
if not _all_ok(_raw):
return
rows.clear()
for m in Builder.parse_effects(_raw):
rows.append(m)
text_mode = false
_render()
func set_raw(t: String) -> void:
_raw = t
_emit()
# ---------- UI ----------
func _render() -> void:
var focus_key := ""
var f := get_viewport().gui_get_focus_owner() if is_inside_tree() else null
if f and is_ancestor_of(f) and f.has_meta(InspectorKit.KEY):
focus_key = str(f.get_meta(InspectorKit.KEY))
for c in get_children():
remove_child(c)
c.queue_free()
if text_mode:
_render_text()
else:
for i in rows.size():
add_child(_row(i))
var foot := InspectorKit.hbox(12)
var add := InspectorKit.link("+ Add a change", "Add a statement that changes a value")
add.pressed.connect(add_row)
InspectorKit.tag(add, _key + ".add")
foot.add_child(add)
var as_text := InspectorKit.link("Edit as text", "Edit these changes as rule text")
as_text.add_theme_color_override("font_color", Style.MUTED)
as_text.pressed.connect(func() -> void: set_text_mode(true))
foot.add_child(as_text)
add_child(foot)
if focus_key != "":
var c := InspectorKit.find_tagged(self, focus_key)
if c:
c.grab_focus.call_deferred()
func _render_text() -> void:
var te := InspectorKit.text_box(_raw, "@luck -= 1", 60.0)
InspectorKit.code(te)
InspectorKit.tag(te, _key + ".raw")
var err := InspectorKit.error_label()
var back := InspectorKit.link("Use the builder", "Show these changes as rows again")
var check := func() -> void:
var problems := Effects.validate(_raw)
var lines := PackedStringArray()
for p: Dictionary in problems:
lines.append("Line %d (%s) can't be used: %s" % [int(p["index"]) + 1, p["src"], p["error"]])
InspectorKit.show_error(err, "\n".join(lines))
InspectorKit.mark(te, problems.is_empty())
back.disabled = not _all_ok(_raw)
back.tooltip_text = "Show these changes as rows again" if not back.disabled else "Some of this text doesn't fit the builder, so it stays as text"
te.text_changed.connect(func() -> void:
_raw = te.text
check.call()
if Effects.validate(_raw).is_empty():
_emit()
)
add_child(te)
add_child(err)
back.pressed.connect(func() -> void: set_text_mode(false))
add_child(back)
check.call()
func _row(i: int) -> Control:
var m := rows[i]
var v := InspectorKit.vbox(3)
var f := InspectorKit.flow()
v.add_child(f)
var x := InspectorKit.xbutton("Remove this change")
x.pressed.connect(remove_row.bind(i))
if not m["ok"]:
var le := InspectorKit.line(str(m.get("src", "")), "@luck -= 1")
InspectorKit.code(le)
InspectorKit.tag(le, "%s.%d.src" % [_key, i])
le.custom_minimum_size = Vector2(200, 0)
var err := InspectorKit.error_label()
var check := func() -> void:
var e := Effects.validate(str(m.get("src", "")))
var msg := ""
if not e.is_empty():
msg = "This can't be used: %s" % e[0]["error"]
else:
msg = "The builder can't show this, so it stays as text. It works as written."
InspectorKit.show_error(err, msg)
err.add_theme_color_override("font_color", Style.DANGER_INK if not e.is_empty() else Style.MUTED)
InspectorKit.mark(le, e.is_empty())
le.text_changed.connect(func(s: String) -> void:
set_row_src(i, s)
check.call()
)
f.add_child(le)
f.add_child(x)
v.add_child(err)
check.call()
return v
var op := str(m["op"])
var dd := InspectorKit.dropdown(OP_LABELS, OPS.find(op))
dd.tooltip_text = "What to do"
dd.item_selected.connect(func(k: int) -> void: set_row_op(i, OPS[k]))
f.add_child(dd)
var picker := ValuePicker.new(main, str(m["var"]))
picker.allow_patterns = op == "reset"
if op == "append" or op == "remove":
picker.kinds = ["list", "text"]
picker.value_chosen.connect(func(n: String) -> void: set_row_var(i, n))
var amt_le: LineEdit = null
var err := InspectorKit.error_label()
if op != "reset":
var listy := op == "append" or op == "remove"
var shown := str(m["amount"]) if listy else InspectorKit.shown_token(str(m["amount"]))
amt_le = InspectorKit.amount(shown, "item" if listy else "1")
amt_le.tooltip_text = "A number, dice such as 1d6, or a value" if not listy else "The item's text"
InspectorKit.tag(amt_le, "%s.%d.amount" % [_key, i])
var le := amt_le
le.text_changed.connect(func(s: String) -> void:
set_row_amount(i, s)
_check_row(i, le, err)
)
match op:
"set":
f.add_child(picker)
f.add_child(InspectorKit.word("to"))
f.add_child(amt_le)
"add", "append":
f.add_child(amt_le)
f.add_child(InspectorKit.word("to"))
f.add_child(picker)
"subtract", "remove":
f.add_child(amt_le)
f.add_child(InspectorKit.word("from"))
f.add_child(picker)
"multiply", "divide":
f.add_child(picker)
f.add_child(InspectorKit.word("by"))
f.add_child(amt_le)
"reset":
f.add_child(picker)
f.add_child(x)
v.add_child(err)
_check_row(i, amt_le, err)
return v
func _check_row(i: int, amt_le: LineEdit, err: Label) -> void:
var m := rows[i]
var msg := ""
if str(m["var"]) == "":
msg = "Pick the value to change."
elif str(m["op"]) != "reset":
var a := str(m["amount"]).strip_edges()
if a == "":
msg = "Fill in the amount."
elif str(m["op"]) != "append" and str(m["op"]) != "remove":
msg = InspectorKit.expr_error(a, "The amount")
InspectorKit.show_error(err, msg)
if amt_le:
InspectorKit.mark(amt_le, msg == "" or str(m["var"]) == "")

View file

@ -1 +0,0 @@
uid://de1gy0tgy1m14

View file

@ -1,276 +0,0 @@
class_name InspectorKit
extends RefCounted
## Small styled controls and helpers shared by the Build inspector and its
## builders (docs/PLAIN.md §6): fields, dropdowns, link buttons, error lines,
## and the rules for turning what a person types into rule tokens.
const FIELD_BG := Color.WHITE
const VAR_BG := Color("#fdf6dc")
const VAR_BORDER := Color("#e3c97a")
const BOX_BG := Color("#f7f5ee")
const TAKEN_BG := Color("#fbf3d6")
## Meta key naming a control inside the inspector, so focus can come back to
## the same field after a rebuild.
const KEY := "insp_key"
static func _field_box(border: Color) -> StyleBoxFlat:
return Style.bordered(Style.box(FIELD_BG, 6, [8, 4, 8, 4]), 1, border)
## A one-line field. `min_w` 0 lets it fill the row.
static func line(text: String, placeholder: String = "", min_w: float = 0.0) -> LineEdit:
var le := LineEdit.new()
le.text = text
le.placeholder_text = placeholder
le.add_theme_stylebox_override("normal", _field_box(Style.RULE))
le.add_theme_stylebox_override("focus", _field_box(Style.COPPER))
le.add_theme_stylebox_override("read_only", _field_box(Style.RULE))
le.add_theme_color_override("font_color", Style.INK)
le.add_theme_color_override("caret_color", Style.INK)
le.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
le.add_theme_color_override("font_placeholder_color", Style.MUTED)
le.add_theme_font_override("font", Style.body())
le.add_theme_font_size_override("font_size", 15)
le.add_theme_constant_override("minimum_character_width", 0)
if min_w > 0.0:
le.custom_minimum_size = Vector2(min_w, 0)
else:
le.size_flags_horizontal = Control.SIZE_EXPAND_FILL
return le
## A short centred field for an amount ("1", "2d6", "Psionic"). It widens
## with its text up to `max_w`.
static func amount(text: String, placeholder: String = "") -> LineEdit:
var le := line(text, placeholder, 52.0)
le.alignment = HORIZONTAL_ALIGNMENT_CENTER
le.add_theme_font_override("font", Style.body_bold())
le.expand_to_text_length = true
return le
static func text_box(text: String, placeholder: String = "", min_h: float = 70.0) -> TextEdit:
var te := TextEdit.new()
te.text = text
te.placeholder_text = placeholder
te.custom_minimum_size = Vector2(0, min_h)
te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
te.scroll_fit_content_height = true
te.add_theme_stylebox_override("normal", Style.bordered(Style.box(FIELD_BG, 6, [8, 6, 8, 6]), 1, Style.RULE))
te.add_theme_stylebox_override("focus", Style.bordered(Style.box(FIELD_BG, 6, [8, 6, 8, 6]), 1, Style.COPPER))
te.add_theme_color_override("font_color", Style.INK)
te.add_theme_color_override("caret_color", Style.INK)
te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
te.add_theme_color_override("font_placeholder_color", Style.MUTED)
te.add_theme_color_override("background_color", Color(0, 0, 0, 0))
te.add_theme_font_override("font", Style.body())
te.add_theme_font_size_override("font_size", 15)
return te
## Monospaced rule text (Text mode fields).
static func code(c: Control) -> Control:
var f := SystemFont.new()
f.font_names = PackedStringArray(["IBM Plex Mono", "DejaVu Sans Mono", "monospace"])
c.add_theme_font_override("font", f)
c.add_theme_font_size_override("font_size", 14)
return c
## Red border (and ink) on a field whose text can't be used.
static func mark(c: Control, ok: bool) -> void:
if c is LineEdit:
c.add_theme_stylebox_override("normal", _field_box(Style.RULE if ok else Style.DANGER))
c.add_theme_stylebox_override("focus", _field_box(Style.COPPER if ok else Style.DANGER))
elif c is TextEdit:
var b := Style.bordered(Style.box(FIELD_BG, 6, [8, 6, 8, 6]), 1, Style.RULE if ok else Style.DANGER)
var f := Style.bordered(Style.box(FIELD_BG, 6, [8, 6, 8, 6]), 1, Style.COPPER if ok else Style.DANGER)
c.add_theme_stylebox_override("normal", b)
c.add_theme_stylebox_override("focus", f)
## A dropdown styled like the mockup's .dd chips.
static func dropdown(items: Array, selected: int) -> OptionButton:
var ob := OptionButton.new()
for i in items.size():
ob.add_item(str(items[i]), i)
ob.select(selected)
ob.fit_to_longest_item = false
var n := Style.bordered(Style.box(FIELD_BG, 6, [8, 3, 6, 3]), 1, Style.RULE)
var h := Style.bordered(Style.box(Style.HOVER_ROW, 6, [8, 3, 6, 3]), 1, Style.DASH)
Style.skin_button(ob, n, h, h, Style.INK)
ob.add_theme_font_override("font", Style.body_bold())
ob.add_theme_font_size_override("font_size", 15)
ob.add_theme_color_override("font_focus_color", Style.INK)
ob.add_theme_constant_override("arrow_margin", 6)
ModalCard.style_popup(ob.get_popup())
return ob
## Small caps heading ("WHEN THIS COMES UP").
static func flabel(text: String) -> Label:
return Style.make_label(text.to_upper(), Style.caps(), 12, Style.MUTED)
## A word inside a builder row ("to", "from", "Only if").
static func word(text: String, color: Color = Style.INK, bold: bool = false) -> Label:
var l := Style.make_label(text, Style.body_bold() if bold else Style.body(), 15, color)
l.size_flags_vertical = Control.SIZE_SHRINK_CENTER
return l
static func note(text: String, color: Color = Style.MUTED, size: int = 13) -> Label:
var l := Style.make_label(text, Style.body(), size, color)
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
l.size_flags_horizontal = Control.SIZE_EXPAND_FILL
l.custom_minimum_size = Vector2(60, 0)
return l
## An error line in plain words (hidden while empty).
static func error_label() -> Label:
var l := note("", Style.DANGER_INK, 13)
l.visible = false
return l
static func show_error(l: Label, msg: String) -> void:
l.text = msg
l.visible = msg != ""
## The × that removes a row.
static func xbutton(tip: String) -> Button:
var b := Button.new()
b.text = "×"
b.tooltip_text = tip
b.custom_minimum_size = Vector2(24, 24)
var n := Style.box(Color(0, 0, 0, 0), 5, [4, 0, 4, 0])
var h := Style.box(Style.WARN_BG, 5, [4, 0, 4, 0])
Style.skin_button(b, n, h, h, Style.MUTED, Style.DANGER_INK)
b.add_theme_font_size_override("font_size", 17)
b.size_flags_vertical = Control.SIZE_SHRINK_CENTER
return b
## A text link ("+ Add a change", "Edit as text").
static func link(text: String, tip: String = "") -> Button:
var b := Button.new()
b.text = text
b.tooltip_text = tip
b.flat = true
var n := Style.box(Color(0, 0, 0, 0), 4, [2, 1, 2, 1])
var h := Style.box(Color(Style.COPPER, 0.12), 4, [2, 1, 2, 1])
Style.skin_button(b, n, h, h, Style.COPPER_DARK)
b.add_theme_font_override("font", Style.body_bold())
b.add_theme_font_size_override("font_size", 14)
b.add_theme_color_override("font_disabled_color", Style.MUTED)
b.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN
return b
static func check_box(text: String, on: bool) -> CheckBox:
var cb := CheckBox.new()
cb.text = text
cb.button_pressed = on
cb.add_theme_font_override("font", Style.body_bold())
cb.add_theme_font_size_override("font_size", 15)
for c in ["font_color", "font_hover_color", "font_pressed_color", "font_hover_pressed_color", "font_focus_color"]:
cb.add_theme_color_override(c, Style.INK)
cb.add_theme_color_override("font_disabled_color", Style.MUTED)
return cb
## A wrapping row of builder parts.
static func flow() -> HFlowContainer:
var f := HFlowContainer.new()
f.add_theme_constant_override("h_separation", 6)
f.add_theme_constant_override("v_separation", 6)
f.size_flags_horizontal = Control.SIZE_EXPAND_FILL
return f
static func vbox(sep: int = 6) -> VBoxContainer:
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", sep)
v.size_flags_horizontal = Control.SIZE_EXPAND_FILL
return v
static func hbox(sep: int = 6) -> HBoxContainer:
var h := HBoxContainer.new()
h.add_theme_constant_override("separation", sep)
return h
## A heading over a block of fields.
static func field(heading: String, c: Control) -> VBoxContainer:
var v := vbox(5)
v.add_child(flabel(heading))
v.add_child(c)
return v
## Names a control so focus can return to it after the inspector rebuilds.
static func tag(c: Control, key: String) -> Control:
c.set_meta(KEY, key)
return c
static func find_tagged(root: Node, key: String) -> Control:
for c in root.get_children():
if c is Control and c.has_meta(KEY) and str(c.get_meta(KEY)) == key:
return c
var r := find_tagged(c, key)
if r:
return r
return null
# ---------- Typed text <-> rule tokens ----------
## The rule token for a value a person typed into a comparison or a list
## item: numbers, @names, quoted text, true/false and the `known` chain names
## stay as they are; anything else becomes quoted text ("Aslan").
static func value_token(typed: String, known: Array = []) -> String:
var s := typed.strip_edges()
if s == "":
return ""
if s.is_valid_float() or s.begins_with("@") or Builder.is_text_literal(s) or s == "true" or s == "false" or known.has(s):
return s
return Builder.quote(s)
## How a value token shows in a field: quoted text without its quotes.
static func shown_token(tok: String) -> String:
return Builder.unquote(tok) if Builder.is_text_literal(tok) else tok
## The expression for an amount a person typed: an expression stays as
## written; a single word or phrase that isn't one (and isn't a `known`
## name) becomes quoted text, so "Millbrook" sets text rather than reading a
## value called Millbrook.
static func amount_expr(typed: String, known: Array = []) -> String:
var s := typed.strip_edges()
if s == "":
return ""
if s.is_valid_float() or Builder.is_text_literal(s) or known.has(s):
return s
var toks := Builder.tokens(s)
if toks.size() == 1 and str(toks[0]["t"]) == "name" and not ["true", "false"].has(s):
return Builder.quote(s)
if toks.is_empty() or Expr.check(TemplateKit.probe(s)) != "":
# Words with spaces ("the old mill") read as text too.
if not s.contains("(") and not s.contains("@") and not s.contains("\""):
return Builder.quote(s)
return s
## "" when an expression a person typed is usable, else why not, in plain words.
static func expr_error(src: String, what: String = "This") -> String:
var s := TemplateKit.probe(src.strip_edges())
if s == "":
return ""
var err := Expr.check(s)
return "" if err == "" else "%s can't be worked out: %s" % [what, err]

View file

@ -1 +0,0 @@
uid://drpdy51bykcar

View file

@ -6,14 +6,11 @@ extends Control
enum Mode { PLAY, BUILD } enum Mode { PLAY, BUILD }
## The rules view changed ("plain" or "text"; see set_rules_view).
signal rules_view_changed(view: String)
const HISTORY_SIZE := 6 const HISTORY_SIZE := 6
const SAVE_DELAY := 0.6 const SAVE_DELAY := 0.6
const HINTS := { const HINTS := {
Mode.PLAY: "Click a die to roll. Shift-click skips straight to the result.", Mode.PLAY: "Click a die to roll. Shift-click skips straight to the result.",
Mode.BUILD: "Click a card, a result or a pipe to edit it in the inspector. Drag from a ● to another card to lay a pipe.", Mode.BUILD: "Type to edit. Drag from a ● to another table to lay a pipe. Click a pipe for its options.",
} }
var data: TowerBoard var data: TowerBoard
@ -33,8 +30,6 @@ var edit_rev := 0
var board: BoardView var board: BoardView
var tray: ResultTray var tray: ResultTray
## The Build-mode inspector docked right of the board (ui/inspector.gd).
var inspector: Inspector
var _token := 0 var _token := 0
var _pulse_tween: Tween var _pulse_tween: Tween
@ -145,20 +140,9 @@ func _build_ui() -> void:
root.add_theme_constant_override("separation", 0) root.add_theme_constant_override("separation", 0)
add_child(root) add_child(root)
root.add_child(_build_top_bar()) root.add_child(_build_top_bar())
var middle := HBoxContainer.new()
middle.add_theme_constant_override("separation", 0)
middle.size_flags_vertical = SIZE_EXPAND_FILL
root.add_child(middle)
board = BoardView.new() board = BoardView.new()
board.setup(self) board.setup(self)
board.size_flags_horizontal = SIZE_EXPAND_FILL root.add_child(board)
middle.add_child(board)
inspector = Inspector.new()
inspector.setup(self)
inspector.visible = false
if state and bool(state.get_setting("inspector_collapsed", false)):
inspector.set_collapsed(true)
middle.add_child(inspector)
_build_selection_bar() _build_selection_bar()
tray = ResultTray.new() tray = ResultTray.new()
tray.setup(self) tray.setup(self)
@ -183,7 +167,7 @@ func _build_top_bar() -> Control:
sb.border_color = Color(1, 1, 1, 0.07) sb.border_color = Color(1, 1, 1, 0.07)
bar.add_theme_stylebox_override("panel", sb) bar.add_theme_stylebox_override("panel", sb)
var h := HBoxContainer.new() var h := HBoxContainer.new()
h.add_theme_constant_override("separation", 10) h.add_theme_constant_override("separation", 16)
bar.add_child(h) bar.add_child(h)
var brand := HBoxContainer.new() var brand := HBoxContainer.new()
@ -247,8 +231,6 @@ func _build_top_bar() -> Control:
_endless_chip = _make_endless_chip() _endless_chip = _make_endless_chip()
h.add_child(_endless_chip) h.add_child(_endless_chip)
h.add_child(_make_rules_switch())
_search_button = _make_search_button() _search_button = _make_search_button()
h.add_child(_search_button) h.add_child(_search_button)
@ -382,12 +364,6 @@ func _rebuild_cards() -> void:
_rebuild_groups() _rebuild_groups()
_update_selection_bar() _update_selection_bar()
_update_collapse_all() _update_collapse_all()
# A board loaded or replaced starts with nothing in the inspector; an
# undo keeps the selection (the inspector follows the board).
if inspector and not _keep_history:
inspector.clear()
elif inspector:
inspector.sync()
func _refresh_lit() -> void: func _refresh_lit() -> void:
@ -395,8 +371,6 @@ func _refresh_lit() -> void:
for card in cards.values(): for card in cards.values():
(card as TableCard).refresh_lit() (card as TableCard).refresh_lit()
_refresh_group_lits() _refresh_group_lits()
if inspector:
inspector.sync()
func set_mode(m: Mode) -> void: func set_mode(m: Mode) -> void:
@ -411,15 +385,9 @@ func set_mode(m: Mode) -> void:
# the (empty) label still stretches to push the right-hand buttons over. # the (empty) label still stretches to push the right-hand buttons over.
_hint.text = HINTS[m] if m == Mode.PLAY else "" _hint.text = HINTS[m] if m == Mode.PLAY else ""
_hint.tooltip_text = HINTS[m] _hint.tooltip_text = HINTS[m]
_hint.custom_minimum_size.x = 60.0 if m == Mode.PLAY else 0.0
# Build's bar has no room for Collapse all; it's in Arrange ▾ there.
_collapse_all.visible = m != Mode.BUILD
_build_tools.visible = m == Mode.BUILD _build_tools.visible = m == Mode.BUILD
board.pipes.hover_key = "" board.pipes.hover_key = ""
clear_selection() clear_selection()
inspector.visible = m == Mode.BUILD
if m != Mode.BUILD:
inspector.clear()
for card in cards.values(): for card in cards.values():
(card as TableCard).rebuild() (card as TableCard).rebuild()
for n in _group_nodes.values(): for n in _group_nodes.values():
@ -462,8 +430,6 @@ func _board_changed() -> void:
_schedule_endless_check() _schedule_endless_check()
if mode == Mode.BUILD: if mode == Mode.BUILD:
refresh_live() refresh_live()
if inspector:
inspector.sync()
## True when an expanded group, or a table that isn't hidden in a collapsed ## True when an expanded group, or a table that isn't hidden in a collapsed
@ -513,17 +479,15 @@ func set_all_collapsed(collapsed: bool) -> void:
mark_dirty("", false) mark_dirty("", false)
## The "+ Card ▾" kinds: [label, kind, sub, default name]. ## The "+ Table ▾" kinds: [label, kind, sub, default name].
const ADD_KINDS := [ const ADD_KINDS := [
["Roll table", RollTable.KIND_ROLL, "", "New table"], ["Roll table", RollTable.KIND_ROLL, "", "New table"],
["Check card: roll against a target", RollTable.KIND_CHECK, "", "Check"],
["Choice: which option", RollTable.KIND_CHOICE, "pick", "New choice"], ["Choice: which option", RollTable.KIND_CHOICE, "pick", "New choice"],
["Choice: how many", RollTable.KIND_CHOICE, "number", "How many?"], ["Choice: how many", RollTable.KIND_CHOICE, "number", "How many?"],
["Choice: open ended", RollTable.KIND_CHOICE, "text", "What is it?"], ["Choice: open ended", RollTable.KIND_CHOICE, "text", "What is it?"],
["Loop", RollTable.KIND_LOOP, "times", "Repeat"], ["Loop", RollTable.KIND_LOOP, "times", "Repeat"],
["Router: if / else if / otherwise", RollTable.KIND_ROUTER, "", "Router"], ["Router: if / else if / otherwise", RollTable.KIND_ROUTER, "", "Router"],
["Variable", RollTable.KIND_VARIABLE, "number", "New variable"], ["Variable", RollTable.KIND_VARIABLE, "number", "New variable"],
["Collection (Skills, Contacts…)", RollTable.KIND_VARIABLE, RollTable.VAR_COLLECTION, "Skills"],
["Sheet", RollTable.KIND_SHEET, "", "Sheet"], ["Sheet", RollTable.KIND_SHEET, "", "Sheet"],
] ]
@ -532,7 +496,7 @@ var _add_menu: MenuButton
func _make_add_menu() -> MenuButton: func _make_add_menu() -> MenuButton:
var mb := MenuButton.new() var mb := MenuButton.new()
mb.text = "+ Card ▾" mb.text = "+ Table ▾"
mb.tooltip_text = "Add a roll table or a logic card" mb.tooltip_text = "Add a roll table or a logic card"
mb.flat = false mb.flat = false
var ref := Style.bar_button("", true) var ref := Style.bar_button("", true)
@ -583,19 +547,12 @@ func add_table(kind: String = RollTable.KIND_ROLL, sub: String = "") -> RollTabl
_begin_edit() _begin_edit()
var center := board.screen_to_world(board.size / 2.0) var center := board.screen_to_world(board.size / 2.0)
var name := "New table" var name := "New table"
var found := false
for k: Array in ADD_KINDS: for k: Array in ADD_KINDS:
if k[1] == kind and k[2] == sub: if k[1] == kind and (sub == "" or k[2] == sub or kind != RollTable.KIND_CHOICE):
name = str(k[3])
found = true
break
if not found:
for k: Array in ADD_KINDS:
if k[1] == kind and (sub == "" or kind != RollTable.KIND_CHOICE) and k[2] != RollTable.VAR_COLLECTION:
name = str(k[3]) name = str(k[3])
break break
var t := RollTable.create(kind, TowerBoard.new_id("t"), name, sub) var t := RollTable.create(kind, TowerBoard.new_id("t"), name, sub)
if kind == RollTable.KIND_ROLL or kind == RollTable.KIND_CHECK: if kind == RollTable.KIND_ROLL:
for e in t.entries: for e in t.entries:
e.id = TowerBoard.new_id("e") e.id = TowerBoard.new_id("e")
if kind == RollTable.KIND_VARIABLE: if kind == RollTable.KIND_VARIABLE:
@ -607,29 +564,6 @@ func add_table(kind: String = RollTable.KIND_ROLL, sub: String = "") -> RollTabl
card.setup(self, t) card.setup(self, t)
cards[t.id] = card cards[t.id] = card
_end_edit() _end_edit()
if mode == Mode.BUILD:
select_card(t.id)
return t
## Adds a variable card declaring @`var_name` (labelled `label`) beside the
## view's centre, for the value pickers' "+ New value…". An existing card
## for that name is returned as it is.
func add_variable_card(label: String, var_name: String, type: String = "number") -> RollTable:
var have := variable_card(var_name)
if have:
return have
_begin_edit()
var center := board.screen_to_world(board.size / 2.0)
var t := RollTable.create(RollTable.KIND_VARIABLE, TowerBoard.new_id("t"), label, type)
t.var_name = _free_var_name(var_name)
t.position = Vector2(maxf(20.0, roundf(center.x - 300.0)), maxf(20.0, roundf(center.y + 40.0)))
data.tables.append(t)
var card := TableCard.new()
board.cards.add_child(card)
card.setup(self, t)
cards[t.id] = card
_end_edit("Add value %s" % label)
return t return t
@ -1068,8 +1002,6 @@ func _frame_at(p: Vector2) -> TableGroup:
# ----- Card drags (TableCard calls these) ----- # ----- Card drags (TableCard calls these) -----
func begin_card_drag(card: TableCard) -> void: func begin_card_drag(card: TableCard) -> void:
if mode == Mode.BUILD and card and card.table:
select_card(card.table.id)
_begin_edit() _begin_edit()
_drag_set.clear() _drag_set.clear()
if mode == Mode.BUILD and selection.has(card.table.id) and selection.size() > 1: if mode == Mode.BUILD and selection.has(card.table.id) and selection.size() > 1:
@ -2513,13 +2445,8 @@ func details() -> DetailsPopup:
return _details_popup return _details_popup
## Build mode: a clicked pipe opens in the inspector. The old pop-up ## Build mode: the options for a clicked pipe (count, save as, remove).
## (PipePopover) is only a fallback for when there is no inspector.
func open_pipe_options(key: String, at: Vector2) -> void: func open_pipe_options(key: String, at: Vector2) -> void:
if inspector != null:
details().hide_for()
select_pipe(key)
return
if _pipe_popover == null: if _pipe_popover == null:
_pipe_popover = PipePopover.new() _pipe_popover = PipePopover.new()
add_child(_pipe_popover) add_child(_pipe_popover)
@ -2531,9 +2458,6 @@ func open_pipe_options(key: String, at: Vector2) -> void:
## The card's ⚙ button. Main.open_table_settings comes from the app-shell work; ## The card's ⚙ button. Main.open_table_settings comes from the app-shell work;
## until it exists this only says so. ## until it exists this only says so.
func request_table_settings(tid: String) -> void: func request_table_settings(tid: String) -> void:
if mode == Mode.BUILD and inspector != null:
select_card(tid)
return
if has_method("open_table_settings"): if has_method("open_table_settings"):
call("open_table_settings", tid) call("open_table_settings", tid)
else: else:
@ -2579,7 +2503,6 @@ func _run_cli_extras(args: PackedStringArray) -> void:
var pipe := _arg_value(args, "--pipe") var pipe := _arg_value(args, "--pipe")
if pipe != "": if pipe != "":
open_pipe_options(pipe, Vector2(size.x * 0.45, size.y * 0.3)) open_pipe_options(pipe, Vector2(size.x * 0.45, size.y * 0.3))
await _run_inspector_cli(args)
var hover := _arg_value(args, "--hover") var hover := _arg_value(args, "--hover")
if hover.contains(","): if hover.contains(","):
# Synthetic mouse move, to check hover pop-ups in screenshots. # Synthetic mouse move, to check hover pop-ups in screenshots.
@ -2920,7 +2843,6 @@ func _nav_mode_changed() -> void:
const PACK_GAP := 60.0 const PACK_GAP := 60.0
const ARRANGE_PACK := 0 const ARRANGE_PACK := 0
const ARRANGE_COLLAPSE := 1
func _make_arrange_menu() -> MenuButton: func _make_arrange_menu() -> MenuButton:
@ -2940,15 +2862,9 @@ func _make_arrange_menu() -> MenuButton:
ModalCard.style_popup(pm) ModalCard.style_popup(pm)
pm.add_item("Pack collapsed groups", ARRANGE_PACK) pm.add_item("Pack collapsed groups", ARRANGE_PACK)
pm.set_item_tooltip(0, "Move collapsed groups and the cards between them together, closing the gaps, in reading order") pm.set_item_tooltip(0, "Move collapsed groups and the cards between them together, closing the gaps, in reading order")
# Build mode's bar has no room for the Collapse all button, so it lives here.
pm.add_item("Collapse all", ARRANGE_COLLAPSE)
pm.about_to_popup.connect(func() -> void:
pm.set_item_text(pm.get_item_index(ARRANGE_COLLAPSE), "Collapse all" if _any_expanded() else "Expand all"))
pm.id_pressed.connect(func(id: int) -> void: pm.id_pressed.connect(func(id: int) -> void:
if id == ARRANGE_PACK: if id == ARRANGE_PACK:
pack_collapsed_groups() pack_collapsed_groups())
elif id == ARRANGE_COLLAPSE:
set_all_collapsed(_any_expanded()))
return mb return mb
@ -3131,7 +3047,6 @@ func _build_edit_timer() -> void:
func _on_focus_changed(c: Control) -> void: func _on_focus_changed(c: Control) -> void:
if _edit_pending and _edit_focus != 0 and (c == null or c.get_instance_id() != _edit_focus): if _edit_pending and _edit_focus != 0 and (c == null or c.get_instance_id() != _edit_focus):
_queue_commit() _queue_commit()
_inspect_focus(c)
## Picks this collection's history (making one) and takes the board as its ## Picks this collection's history (making one) and takes the board as its
@ -3243,8 +3158,6 @@ func _apply_history(e: Dictionary, verb: String) -> void:
_restoring = true _restoring = true
if _pipe_popover and _pipe_popover.visible: if _pipe_popover and _pipe_popover.visible:
_pipe_popover.hide() _pipe_popover.hide()
if inspector:
inspector.close_menus()
details().hide_for() details().hide_for()
board.pipes.hover_key = "" board.pipes.hover_key = ""
_drop_card = null _drop_card = null
@ -3457,223 +3370,3 @@ func _schedule_endless_check() -> void:
_endless_timer.timeout.connect(_update_endless_chip) _endless_timer.timeout.connect(_update_endless_chip)
add_child(_endless_timer) add_child(_endless_timer)
_endless_timer.start() _endless_timer.start()
# ---------- Inspector and rules view (docs/PLAIN.md §5–6) ----------
# The inspector edits the selected card, result or pipe (Build mode). The
# display side calls select_card / select_result / select_pipe /
# clear_inspector; Main also selects from the board: a card's title (drag
# start), focus entering a result's field on a card, a clicked pipe, the ⚙.
## When there's no `state` (--sample), the rules view lives here.
var _rules_view_mem := "plain"
var _rules_buttons: Array[Button] = []
## "plain" (Describe's phrases) or "text" (the stored rule text).
func rules_view() -> String:
return state.rules_view() if state else _rules_view_mem
func rules_plain() -> bool:
return rules_view() == "plain"
## Shows rules as "plain" words or as "text"; saved as a setting. Emits
## rules_view_changed when it changes.
func set_rules_view(v: String) -> void:
if v != "plain" and v != "text":
return
if v == rules_view():
_sync_rules_switch()
return
if state:
state.set_rules_view(v)
state.save()
_rules_view_mem = v
_sync_rules_switch()
if inspector:
inspector.rebuild()
rules_view_changed.emit(v)
func _sync_rules_switch() -> void:
if _rules_buttons.size() == 2:
_rules_buttons[0].set_pressed_no_signal(rules_plain())
_rules_buttons[1].set_pressed_no_signal(not rules_plain())
## The top bar's compact "Plain | Text" rules switch.
func _make_rules_switch() -> Control:
var seg := PanelContainer.new()
seg.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.28), 9, [3, 3, 3, 3]))
seg.size_flags_vertical = SIZE_SHRINK_CENTER
seg.tooltip_text = "Show rules in plain words, or as the rule text they're stored as"
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 0)
seg.add_child(row)
var group := ButtonGroup.new()
_rules_buttons.clear()
for pair in [["Plain", "plain"], ["Text", "text"]]:
var b := _seg_button(str(pair[0]), group)
b.add_theme_font_size_override("font_size", 14)
for n in ["normal", "hover", "pressed", "hover_pressed"]:
var sb := b.get_theme_stylebox(n) as StyleBoxFlat
if sb:
sb.content_margin_left = 10
sb.content_margin_right = 10
sb.content_margin_top = 4
sb.content_margin_bottom = 4
b.tooltip_text = "Rules: show them in plain words" if pair[1] == "plain" else "Rules: show them as rule text (@luck -= 1)"
b.focus_mode = Control.FOCUS_NONE
var v: String = pair[1]
b.pressed.connect(func() -> void: set_rules_view(v))
row.add_child(b)
_rules_buttons.append(b)
_sync_rules_switch()
return seg
func select_card(table_id: String) -> void:
if inspector == null or data.get_table(table_id) == null:
return
inspector.select({"kind": "card", "tid": table_id})
func select_result(table_id: String, entry_id: String) -> void:
var t := data.get_table(table_id)
if inspector == null or t == null or t.find_entry(entry_id) == null:
return
inspector.select({"kind": "result", "tid": table_id, "eid": entry_id})
## `key` is a pipe key, "tid:eid>to" (Roller.pipe_key).
func select_pipe(key: String) -> void:
var from := key.get_slice(">", 0)
var tid := from.get_slice(":", 0)
var eid := from.get_slice(":", 1)
var to := key.get_slice(">", 1)
var t := data.get_table(tid)
var e := t.find_entry(eid) if t else null
if inspector == null or e == null or not e.pipes.has(to):
return
inspector.select({"kind": "pipe", "tid": tid, "eid": eid, "to": to})
func clear_inspector() -> void:
if inspector:
inspector.clear()
## What the inspector shows: {kind: "card" | "result" | "pipe", tid, eid?, to?} or {}.
func inspector_selection() -> Dictionary:
return inspector.selection.duplicate() if inspector else {}
## After the inspector changed a card: refreshes it (every card when a
## variable's name or label changed, since other cards show it).
func inspector_edited(tid: String, all_cards: bool = false) -> void:
_ref_cache.clear()
if all_cards:
for c in cards.values():
(c as TableCard).rebuild()
else:
var card := card_for(tid)
if card:
card.rebuild()
## Focus entering a field on a card in Build selects that result (or the card).
func _inspect_focus(c: Control) -> void:
if mode != Mode.BUILD or inspector == null or c == null or inspector.is_ancestor_of(c):
return
var n: Node = c
while n != null and not (n is TableCard):
n = n.get_parent()
var card := n as TableCard
if card == null or card.table == null:
return
for eid: String in card.rows:
var row: Node = card.rows[eid]
if is_instance_valid(row) and row.is_ancestor_of(c):
var s := inspector.selection
if str(s.get("tid", "")) != card.table.id or str(s.get("eid", "")) != eid or str(s.get("kind", "")) == "card":
select_result(card.table.id, eid)
return
if str(inspector.selection.get("tid", "")) != card.table.id:
select_card(card.table.id)
## Sets a collection member's saved value (@<stem>_<item>), keeping numbers
## as numbers. Members are local values like the Variables panel's.
func set_collection_member(t: RollTable, item: String, value: String) -> void:
var n := "%s_%s" % [t.var_name, item]
persistent_vars[n] = {"value": Expr.to_value(value) if Expr.is_number(value) else value, "source": t.id}
_variables_changed()
func remove_collection_member(t: RollTable, item: String) -> void:
if persistent_vars.erase("%s_%s" % [t.var_name, item]):
_variables_changed()
# --inspect=<table id>[:<entry id>][><target id>] select that card, result or pipe
# --rules=text show rules as text
# --pick-open open the inspector's first value picker
# --vars=name=value,… set board values (e.g. collection members)
# --light=<pipe key>,… light pipes and their results, as if rolled
# --window=<w>x<h> resize the window first (screenshots)
# --inspect-scroll=<px> scroll the inspector down
func _run_inspector_cli(args: PackedStringArray) -> void:
var win := _arg_value(args, "--window")
if win.contains("x"):
get_window().size = Vector2i(win.get_slice("x", 0).to_int(), win.get_slice("x", 1).to_int())
for i in 3:
await get_tree().process_frame
var rv := _arg_value(args, "--rules")
if rv != "":
set_rules_view(rv)
var vars := _arg_value(args, "--vars")
if vars != "":
for pair in vars.split(",", false):
var v := pair.get_slice("=", 1)
persistent_vars[pair.get_slice("=", 0)] = {"value": Expr.to_value(v) if Expr.is_number(v) else v, "source": ""}
_variables_changed()
var light := _arg_value(args, "--light")
if light != "":
for k in light.split(",", false):
lit_pipes[k] = true
lit_entries[k.get_slice(">", 0)] = true
_refresh_lit()
var sel := _arg_value(args, "--inspect")
if sel == "":
return
if mode != Mode.BUILD:
set_mode(Mode.BUILD)
if sel.contains(">"):
select_pipe(sel)
elif sel.contains(":"):
select_result(sel.get_slice(":", 0), sel.get_slice(":", 1))
else:
select_card(sel)
var scroll := _arg_value(args, "--inspect-scroll")
if scroll != "":
for i in 3:
await get_tree().process_frame
inspector._scroll.scroll_vertical = scroll.to_int()
if args.has("--pick-open"):
for i in 3:
await get_tree().process_frame
var p := _first_picker(inspector)
if p:
p.open_menu()
func _first_picker(n: Node) -> ValuePicker:
for c in n.get_children():
if c is ValuePicker and (c as ValuePicker).is_visible_in_tree():
return c
var r := _first_picker(c)
if r:
return r
return null

View file

@ -7,10 +7,8 @@ extends Control
## the text, so they can't be clicked or removed here. ## the text, so they can't be clicked or removed here.
## ##
## Conditional pipes (an "Only if" condition, or "otherwise") have a small ## Conditional pipes (an "Only if" condition, or "otherwise") have a small
## diamond at their source end, and pipes with options a label, so the ## diamond at their source end and a label ("if @str >= 8", "otherwise"), so
## branches of an entry read at a glance. Labels read in plain words ## the branches of an entry read at a glance.
## (Describe.pipe: "Tier 3 · only if Luck is 2 or more", "otherwise") or as
## the stored text ("if @luck >= 2"), following RulesView.plain(main).
## ##
## Pipes to or from tables hidden in a collapsed group attach to that group's ## Pipes to or from tables hidden in a collapsed group attach to that group's
## card instead (GroupCard.inlet_point / anchor_for). They keep their keys, so ## card instead (GroupCard.inlet_point / anchor_for). They keep their keys, so
@ -62,7 +60,7 @@ func _init() -> void:
func _process(_delta: float) -> void: func _process(_delta: float) -> void:
if main == null or main.board == null: if main == null or main.board == null:
return return
var state := [main.board.geometry_rev, hover_key, select_key, pulse_key, pulse_t, main.board.cards.far, RulesView.plain(main)] var state := [main.board.geometry_rev, hover_key, select_key, pulse_key, pulse_t, main.board.cards.far]
if state != _drawn_state: if state != _drawn_state:
_drawn_state = state _drawn_state = state
queue_redraw() queue_redraw()
@ -168,7 +166,6 @@ func _draw() -> void:
var diamonds: Array = [] # [point, lit, otherwise] var diamonds: Array = [] # [point, lit, otherwise]
var drawn := {} # endpoints of rerouted pipes already drawn (they overlap) var drawn := {} # endpoints of rerouted pipes already drawn (they overlap)
var build := main.mode == Main.Mode.BUILD var build := main.mode == Main.Mode.BUILD
var plain := RulesView.plain(main)
# Tables hidden in a collapsed group -> that group's card. Their pipes leave # Tables hidden in a collapsed group -> that group's card. Their pipes leave
# from the group card's right edge and arrive at its inlet. # from the group card's right edge and arrive at its inlet.
var hidden := main.hidden_groups() var hidden := main.hidden_groups()
@ -214,8 +211,8 @@ func _draw() -> void:
diamonds.append([pts, lit, e.is_otherwise(to)]) diamonds.append([pts, lit, e.is_otherwise(to)])
if lit: if lit:
(lit_refs if is_ref else lit_list).append(pts) (lit_refs if is_ref else lit_list).append(pts)
if not is_ref and not rerouted: if not is_ref and not rerouted and e.is_conditional(to):
var lt := RulesView.pipe_label(e, to, main.data, plain) var lt := _pipe_tag(e, to)
if lt != "": if lt != "":
labels.append([pts, lt, true]) labels.append([pts, lt, true])
continue continue
@ -231,7 +228,7 @@ func _draw() -> void:
else: else:
_batch_pipe(pts, build and (key == hover_key or key == select_key)) _batch_pipe(pts, build and (key == hover_key or key == select_key))
if not is_ref and not rerouted: if not is_ref and not rerouted:
var tag := RulesView.pipe_label(e, to, main.data, plain) var tag := _pipe_tag(e, to)
if tag != "": if tag != "":
labels.append([pts, tag, false]) labels.append([pts, tag, false])
# Lit pipes go on top so the path of the last roll reads clearly. # Lit pipes go on top so the path of the last roll reads clearly.
@ -241,9 +238,8 @@ func _draw() -> void:
_draw_pipe(pts, true, false) _draw_pipe(pts, true, false)
for d in diamonds: for d in diamonds:
_draw_diamond(d[0], d[1], d[2]) _draw_diamond(d[0], d[1], d[2])
var placed: Array[Rect2] = []
for l in labels: for l in labels:
_draw_tag(l[0], l[1], l[2], placed) _draw_tag(l[0], l[1], l[2])
if pulse_key != "" and _paths.has(pulse_key): if pulse_key != "" and _paths.has(pulse_key):
var p := point_along(_paths[pulse_key], pulse_t) var p := point_along(_paths[pulse_key], pulse_t)
var r := 0.75 if Roller.is_ref_key(pulse_key) else 1.0 var r := 0.75 if Roller.is_ref_key(pulse_key) else 1.0
@ -252,13 +248,9 @@ func _draw() -> void:
draw_circle(p, 7.0 * r, Style.PULSE) draw_circle(p, 7.0 * r, Style.PULSE)
## The text-mode label: "tier=3 if @str >= 8 ×2 → foe" / "otherwise" for a ## "if @str >= 8 ×2 → foe" / "otherwise" for a pipe with options, or "".
## pipe with options, or "".
static func _pipe_tag(e: TableEntry, to: String) -> String: static func _pipe_tag(e: TableEntry, to: String) -> String:
var parts := PackedStringArray() var parts := PackedStringArray()
var wv := e.with_for(to)
for nm: String in wv:
parts.append("%s=%s" % [nm, RulesView.cut(str(wv[nm]), 12)])
var w := e.when_for(to) var w := e.when_for(to)
if w != "": if w != "":
parts.append("if " + (w if w.length() <= 24 else w.substr(0, 23) + "…")) parts.append("if " + (w if w.length() <= 24 else w.substr(0, 23) + "…"))
@ -274,30 +266,12 @@ static func _pipe_tag(e: TableEntry, to: String) -> String:
return " ".join(parts) return " ".join(parts)
## A label on a pipe, at its middle, or a little along it when that spot func _draw_tag(pts: PackedVector2Array, text: String, lit: bool = false) -> void:
## overlaps a label already drawn (`placed`, which it adds to).
func _draw_tag(pts: PackedVector2Array, text: String, lit: bool = false, placed: Array[Rect2] = []) -> void:
var font := Style.body_bold(true) var font := Style.body_bold(true)
var fs := 12 var fs := 12
var w := font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x var w := font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
# Labels sit behind the cards, so a long one is cut to the gap between var mid := point_along(pts, 0.5)
# the cards it joins (the whole rule shows in the row's hover summary). var r := Rect2(mid - Vector2(w / 2.0 + 6.0, 10.0), Vector2(w + 12.0, 19.0))
var room := maxf(80.0, absf(pts[pts.size() - 1].x - pts[0].x) - 30.0) if pts.size() > 1 else 200.0
while w + 12.0 > room and text.length() > 6:
text = text.substr(0, text.length() - 2).strip_edges() + "…"
w = font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
var r := Rect2()
for t: float in [0.5, 0.62, 0.38, 0.74, 0.26]:
var mid := point_along(pts, t)
r = Rect2(mid - Vector2(w / 2.0 + 6.0, 10.0), Vector2(w + 12.0, 19.0))
var clear := true
for q in placed:
if q.grow(2.0).intersects(r):
clear = false
break
if clear:
break
placed.append(r)
draw_style_box(_lit_label_box if lit else _label_box, r) draw_style_box(_lit_label_box if lit else _label_box, r)
draw_string(font, Vector2(r.position.x + 6.0, r.position.y + 14.0), text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, Style.INK if lit else Style.COPPER_DARK) draw_string(font, Vector2(r.position.x + 6.0, r.position.y + 14.0), text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, Style.INK if lit else Style.COPPER_DARK)

View file

@ -3,14 +3,6 @@ extends PanelContainer
## The strip along the bottom: the current roll as a chain of result chips ## The strip along the bottom: the current roll as a chain of result chips
## joined by brass pipe pieces, a Copy menu, and on the right either the ## joined by brass pipe pieces, a Copy menu, and on the right either the
## earlier rolls (default) or the Variables tab. ## earlier rolls (default) or the Variables tab.
##
## Captions and effect lines read in plain words ("Loot · Tier 1 · rolled 3",
## "Luck 2 → 1") or closer to the rule text, following RulesView.plain(main);
## the tray re-renders on Main's rules_view_changed. A chip whose step has
## why-trace facts gets a "Why this?" button that opens a WhyPopover; hovering
## the chip shows the same reasons. Screenshot flag: --why[=<step index>]
## opens the pop-over for that step (default: the last one with reasons)
## after a roll.
enum Side { EARLIER, VARIABLES } enum Side { EARLIER, VARIABLES }
@ -45,10 +37,6 @@ const HEADLINE_MAX_H := 220.0
## True when "+N earlier steps" has been opened for the current roll. ## True when "+N earlier steps" has been opened for the current roll.
var expanded := false var expanded := false
var _scroll_to_end := false var _scroll_to_end := false
var _why: WhyPopover
## The "Why this?" buttons of the chips shown, by step index (tests).
var why_buttons: Dictionary = {}
var _why_flag_done := false
## A long chain shows only its last steps; the rest sit behind a toggle. ## A long chain shows only its last steps; the rest sit behind a toggle.
const TAIL := 12 const TAIL := 12
@ -171,14 +159,6 @@ func setup(p_main: Main) -> void:
_vars.setup(main) _vars.setup(main)
right.add_child(_vars) right.add_child(_vars)
set_side(Side.EARLIER) set_side(Side.EARLIER)
_why = WhyPopover.new()
add_child(_why)
RulesView.watch(main, _on_rules_view_changed)
func _on_rules_view_changed(_v: Variant = null) -> void:
_why.close()
render()
func _tab(text: String) -> Button: func _tab(text: String) -> Button:
@ -243,9 +223,6 @@ func render() -> void:
for c in _flow.get_children(): for c in _flow.get_children():
_flow.remove_child(c) _flow.remove_child(c)
c.queue_free() c.queue_free()
why_buttons.clear()
if _why != null:
_why.close()
_empty.visible = current.is_empty() _empty.visible = current.is_empty()
_render_status(current, steps) _render_status(current, steps)
if current.is_empty(): if current.is_empty():
@ -266,7 +243,7 @@ func render() -> void:
var step: Dictionary = steps[i] var step: Dictionary = steps[i]
if i > first: if i > first:
_flow.add_child(_link(step.get("inline", false))) _flow.add_child(_link(step.get("inline", false)))
var chip := _chip(step, done and i == steps.size() - 1, steps, i) var chip := _chip(step, done and i == steps.size() - 1)
_flow.add_child(chip) _flow.add_child(chip)
if i >= fresh_from and not current.get("fast", false): if i >= fresh_from and not current.get("fast", false):
chip.modulate.a = 0.3 chip.modulate.a = 0.3
@ -300,50 +277,6 @@ func render() -> void:
_vars.render() _vars.render()
_scroll_to_end = not expanded _scroll_to_end = not expanded
_fit_scroll.call_deferred() _fit_scroll.call_deferred()
if not _why_flag_done and current.get("done", false):
_open_why_from_flag.call_deferred()
## --why[=<step index>]: opens the Why pop-over once after a roll (screenshots).
func _open_why_from_flag() -> void:
for a in OS.get_cmdline_user_args():
if a == "--why" or a.begins_with("--why="):
_why_flag_done = true
await get_tree().create_timer(0.4).timeout
if not main.current.get("done", false):
_why_flag_done = false # a new roll began; wait for it to end
return
var at := -1
if a == "--why":
for k: int in why_buttons:
at = maxi(at, k)
else:
at = a.get_slice("=", 1).to_int()
if why_buttons.has(at):
(why_buttons[at] as Button).emit_signal("pressed")
return
## Opens (or, from the same button, closes) the Why pop-over for steps[index].
func open_why(index: int, from: Control = null) -> void:
if _why.visible and from != null and _why.opener == from:
_why.close()
return
var steps: Array = main.current.get("steps", [])
if index < 0 or index >= steps.size():
return
main.details().hide_for()
var at := Rect2(global_position + Vector2(20, 20), Vector2.ZERO)
var chip: Control = null
if from != null:
# Above the whole chip, so it never hides the step it explains.
chip = from.get_parent().get_parent() as Control
at = chip.get_global_rect() if chip != null else from.get_global_rect()
_why.open(steps, index, main.data, RulesView.plain(main), at, from, chip)
func why_popover() -> WhyPopover:
return _why
## Index of the first chip shown for a chain of `count` steps: only the last ## Index of the first chip shown for a chain of `count` steps: only the last
@ -482,30 +415,10 @@ func _asking_chip(title: String) -> Control:
## The muted line above a chip's text: table name and how it got its result. ## The muted line above a chip's text: table name and how it got its result.
## With `plain`, rules read in plain words ("Loot · Tier 1 · rolled 4 on 1D + static func caption_for(step: Dictionary) -> String:
## Tier", "Force the gate · rolled 7, +1 → 8"), labelled from `board`.
static func caption_for(step: Dictionary, board: TowerBoard = null, plain: bool = false) -> String:
var caption := Formatter.strip_tags(str(step["table"])) var caption := Formatter.strip_tags(str(step["table"]))
var num: String = str(step.get("num", "")) var num: String = str(step.get("num", ""))
var ins: Variant = step.get("inputs")
if ins is Dictionary:
for nm: Variant in ins:
if plain:
caption += " · %s %s" % [Describe.label(str(nm), board), Expr.format_value(ins[nm])]
else:
caption += " · %s=%s" % [nm, Expr.format_value(ins[nm])]
match str(step.get("kind", "")): match str(step.get("kind", "")):
RollTable.KIND_CHECK:
var c: Variant = step.get("check")
if c is Dictionary:
var mod := int(c.get("mod", 0))
var ms := ""
if mod != 0:
ms = ("+%d" % mod) if mod > 0 else (Describe.MINUS + str(-mod))
if plain:
caption += " · rolled %s%s → %s" % [Expr.format_value(c.get("nat")), (", " + ms) if ms != "" else "", Expr.format_value(c.get("total"))]
else:
caption += " · %s%s = %s vs %s" % [Expr.format_value(c.get("nat")), ms.replace(Describe.MINUS, "-"), Expr.format_value(c.get("total")), Expr.format_value(c.get("target"))]
RollTable.KIND_CHOICE: RollTable.KIND_CHOICE:
if step.get("cancelled", false): if step.get("cancelled", false):
pass pass
@ -526,32 +439,18 @@ static func caption_for(step: Dictionary, board: TowerBoard = null, plain: bool
caption += " · sheet" caption += " · sheet"
RollTable.KIND_ROUTER: RollTable.KIND_ROUTER:
if step.has("case"): if step.has("case"):
var said := false
if plain and board != null:
var rt := board.get_table(str(step.get("table_id", "")))
var k := int(step["case"])
if rt != null and k >= 0 and k < rt.entries.size():
caption += " · " + RulesView.cut(RulesView.case_label(rt.entries[k], board, true), 44)
said = true
if not said:
caption += " · case %d" % (int(step["case"]) + 1) caption += " · case %d" % (int(step["case"]) + 1)
_: _:
if num != "": if num != "":
var dl := str(step.get("dice", "d%d" % int(step.get("die", 0)))) caption += " · rolled %s on %s" % [num, step.get("dice", "d%d" % int(step.get("die", 0)))]
if plain and dl.contains(" "):
dl = RulesView.cut(Describe.dice(dl, board), 30)
caption += " · rolled %s on %s" % [num, dl]
if step.get("reshuffled", false): if step.get("reshuffled", false):
caption += " · deck reshuffled" caption += " · deck reshuffled"
if str(step.get("save_as", "")) != "": if str(step.get("save_as", "")) != "":
if plain:
caption += " · saved as %s" % Describe.label(str(step["save_as"]), board)
else:
caption += " · saved as {%s}" % step["save_as"] caption += " · saved as {%s}" % step["save_as"]
return caption return caption
func _chip(step: Dictionary, last: bool, steps: Array = [], index: int = -1) -> Control: func _chip(step: Dictionary, last: bool) -> Control:
var inline: bool = step.get("inline", false) var inline: bool = step.get("inline", false)
var p := PanelContainer.new() var p := PanelContainer.new()
var sb := Style.box(Style.LIT if last else Style.CARD, 9, [10, 5, 10, 6] if inline else [12, 7, 12, 8]) var sb := Style.box(Style.LIT if last else Style.CARD, 9, [10, 5, 10, 6] if inline else [12, 7, 12, 8])
@ -569,9 +468,7 @@ func _chip(step: Dictionary, last: bool, steps: Array = [], index: int = -1) ->
var v := VBoxContainer.new() var v := VBoxContainer.new()
v.add_theme_constant_override("separation", 1) v.add_theme_constant_override("separation", 1)
p.add_child(v) p.add_child(v)
var plain := RulesView.plain(main) var caption := caption_for(step)
var caption := caption_for(step, main.data, plain)
var has_why := index >= 0 and WhyPopover.has_why(steps, index)
var has_details := main.details().step_has_details(step) var has_details := main.details().step_has_details(step)
if has_details: if has_details:
caption += " " + RichText.INFO_MARK caption += " " + RichText.INFO_MARK
@ -592,68 +489,12 @@ func _chip(step: Dictionary, last: bool, steps: Array = [], index: int = -1) ->
v.add_child(body) v.add_child(body)
var fx: Array = step.get("effects", []) var fx: Array = step.get("effects", [])
if not fx.is_empty(): if not fx.is_empty():
v.add_child(_effect_lines(effect_lines_for(step, main.data, plain))) v.add_child(_effect_lines(fx))
if has_why: if has_details:
var wb := _why_button() p.mouse_entered.connect(func() -> void: main.details().show_step(p, step))
wb.pressed.connect(func() -> void: open_why(index, wb))
why_buttons[index] = wb
v.add_child(wb)
if has_details or has_why:
p.mouse_entered.connect(func() -> void:
if not _why.visible:
main.details().show_step(p, step, steps, index))
return p return p
## The small "Why this?" pill under a chip.
func _why_button() -> Button:
var b := Button.new()
b.text = "Why this?"
b.tooltip_text = "What decided this step"
b.size_flags_horizontal = SIZE_SHRINK_BEGIN
b.focus_mode = Control.FOCUS_NONE
var n := Style.bordered(Style.box(Color.WHITE, 10, [9, 1, 9, 2]), 1, Style.RULE)
var h := Style.bordered(Style.box(Style.LIT, 10, [9, 1, 9, 2]), 1, Style.BRASS_DARK)
Style.skin_button(b, n, h, h, Style.COPPER_DARK, Style.INK)
b.add_theme_font_override("font", Style.body_bold())
b.add_theme_font_size_override("font_size", 12)
return b
## A step's effect lines for its chip: in plain words, one per value that
## changed ("Luck 2 → 1", "Town = Millbrook", "Cleared all Skills (3)") from
## its why facts, then any errors from its log; else the log as it is.
static func effect_lines_for(step: Dictionary, board: TowerBoard, plain: bool) -> Array:
var fx: Array = step.get("effects", [])
if not plain or not (step.get("why") is Array):
return fx
var out: Array = []
for f: Variant in step["why"]:
if f is Dictionary and str(f.get("type", "")) == "effect":
out.append({"text": effect_fact_line(f, board)})
if out.is_empty():
return fx
for l: Variant in fx:
if l is Dictionary and (l as Dictionary).get("error", false):
out.append(l)
return out
## "Luck 2 → 1", "Town = Millbrook", "Loot cleared", "Cleared all Skills (3)".
static func effect_fact_line(f: Dictionary, board: TowerBoard) -> String:
var lab := Describe.label(str(f.get("var", "")), board)
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 after == null:
return "%s cleared" % lab
var a := Expr.format_value(after)
if before == null or Expr.format_value(before) == "":
return "%s = %s" % [lab, a if a != "" else "(none)"]
return "%s %s → %s" % [lab, Expr.format_value(before), a if a != "" else "(none)"]
## The effect log under a chip: a few compact lines, errors in red. ## The effect log under a chip: a few compact lines, errors in red.
func _effect_lines(fx: Array) -> Control: func _effect_lines(fx: Array) -> Control:
var box := VBoxContainer.new() var box := VBoxContainer.new()

View file

@ -1,147 +0,0 @@
class_name RulesView
extends RefCounted
## The display side of docs/PLAIN.md §5: whether rules show in plain words
## (Describe) or as their stored text, and short display helpers that pick
## between the two.
##
## The switch itself lives in Main (the Build inspector work): when Main has
## rules_plain() that decides, else its StateStore's "rules_view" setting, else
## an in-memory default (plain, or text with the --rules=text screenshot flag).
## Displays refresh on Main's `rules_view_changed` signal when it has one
## (watch()).
## Used when Main has neither rules_plain() nor a StateStore (--sample, tests).
static var fallback_plain := true
static var _args_read := false
## Longest pipe label drawn on the board before it's cut with "…".
const PIPE_CHARS := 46
## True when rules should read in plain words.
static func plain(main: Object) -> bool:
if main != null:
if main.has_method("rules_plain"):
return bool(main.call("rules_plain"))
var st: Variant = main.get("state")
if st is StateStore:
return (st as StateStore).rules_plain()
if not _args_read:
_args_read = true
if OS.get_cmdline_user_args().has("--rules=text"):
fallback_plain = false
return fallback_plain
## Calls `callable` whenever Main's rules view changes (when Main has the
## signal). Safe to call more than once with the same callable.
static func watch(main: Object, callable: Callable) -> void:
if main == null or not main.has_signal("rules_view_changed"):
return
if not main.is_connected("rules_view_changed", callable):
main.connect("rules_view_changed", callable)
## An effects field as one short line: "Luck −1 · Gold + 2D" (plain) or
## "@luck -= 1 · @gold += 2d6" (text). At most `most` statements, then "+N".
static func effects_line(text: String, board: TowerBoard, table: RollTable, is_plain: bool, most: int = 2) -> String:
var list: Array = Describe.effects(text, board, table) if is_plain else Array(Effects.split(text))
var parts := PackedStringArray()
for k in mini(most, list.size()):
parts.append(str(list[k]))
if list.size() > most:
parts.append("+%d" % (list.size() - most))
return " · ".join(parts)
## A condition in plain words or as written.
static func condition(expr: String, board: TowerBoard, is_plain: bool) -> String:
return Describe.condition(expr, board) if is_plain else expr.strip_edges()
## A router case: "if Strength is 10 or more" / "if @str >= 10", or
## "Otherwise".
static func case_label(e: TableEntry, board: TowerBoard, is_plain: bool) -> String:
var w := e.when.strip_edges()
if w == "":
return "Otherwise"
return "if " + condition(w, board, is_plain)
## A loop's rule: "repeat while Health is more than 0", "repeat until Done is
## set", "× Terms" (plain); "while @hp > 0", "× @terms" (text).
static func loop_rule(t: RollTable, board: TowerBoard, is_plain: bool) -> String:
if not is_plain:
return TableCard.loop_rule(t)
var e := t.loop_expr.strip_edges()
if e == "":
return "× ?" if t.loop_mode == "times" else "repeat %s ?" % t.loop_mode
match t.loop_mode:
"while":
return "repeat while " + Describe.condition(e, board)
"until":
return "repeat until " + Describe.condition(e, board)
return "× " + Describe.dice(e, board)
## A pick card's option source: "Options: your Skills, level 1 or more" or
## "Options from @skill_* · where option_value >= 1".
static func options_line(t: RollTable, board: TowerBoard, is_plain: bool) -> String:
if not is_plain:
return TableCard.options_line(t)
var d := Describe.options(t, board)
return "Options: " + (d if d != "" else t.options_from.strip_edges())
## A pick option's show_if: "only if Hit points is at most 6".
static func show_if_line(e: TableEntry, board: TowerBoard, is_plain: bool) -> String:
return "only if " + condition(e.show_if, board, is_plain)
## A dice expression: "2D + Luck" or "2d6 + @luck".
static func dice(expr: String, board: TowerBoard, is_plain: bool) -> String:
return Describe.dice(expr, board) if is_plain else expr.strip_edges()
## A check card's rule: "Roll 2D + Strength modifier, need 8 or more" or
## "2d6 + dm(@str) vs 8+".
static func check_line(t: RollTable, board: TowerBoard, is_plain: bool) -> String:
if is_plain:
return Describe.check(t, board)
var roll := t.check_dice.strip_edges()
if t.check_mod.strip_edges() != "":
var m := t.check_mod.strip_edges()
roll += (" " + m) if m.begins_with("-") else " + " + m
return "%s vs %s%s" % [roll, t.check_target.strip_edges(), "-" if t.check_cmp == "le" else "+"]
## The two outlet labels of a check card ([success, failure]): "8+" and "≤7"
## for a number target, else "✓" and "✗".
static func check_outlets(t: RollTable) -> Array[String]:
var tg := t.check_target.strip_edges()
if not tg.is_valid_int():
return ["✓", "✗"]
var n := tg.to_int()
if t.check_cmp == "le":
return ["≤%d" % n, "%d+" % (n + 1)]
return ["%d+" % n, "≤%d" % (n - 1)]
## A pipe's label: Describe.pipe (plain) or PipeLayer's text tag, cut to
## PIPE_CHARS.
static func pipe_label(e: TableEntry, to: String, board: TowerBoard, is_plain: bool) -> String:
var s := Describe.pipe(e, to, board) if is_plain else PipeLayer._pipe_tag(e, to)
return cut(s, PIPE_CHARS)
## A value's name: "Strength" or "@str".
static func value_name(name: String, board: TowerBoard, is_plain: bool) -> String:
return Describe.label(name, board) if is_plain else name
## `s`, or its first `most` characters and "…".
static func cut(s: String, most: int) -> String:
if s.length() <= most:
return s
return s.substr(0, most - 1).strip_edges() + "…"

View file

@ -1 +0,0 @@
uid://baaog01nm2ofe

View file

@ -22,9 +22,6 @@ const DANGER := Color("#e0574a")
const DANGER_INK := Color("#a33a2c") const DANGER_INK := Color("#a33a2c")
const WARN_BG := Color("#f4dacb") const WARN_BG := Color("#f4dacb")
const WARN_INK := Color("#8a2f1d") const WARN_INK := Color("#8a2f1d")
## A check card's Success and Failure outlets.
const OK_INK := Color("#2f6b3f")
const NO_INK := Color("#8a2f1d")
const DASH := Color("#bdb6a2") const DASH := Color("#bdb6a2")
const PULSE := Color("#fff6d2") const PULSE := Color("#fff6d2")
@ -160,33 +157,6 @@ static func bar_button(text: String, primary: bool = false) -> Button:
return b return b
## The Plain words / Text switch's look (docs/PLAIN.md §5; the switch itself
## is Main's): two segment buttons on the felt, the chosen one card-coloured.
## Adds them to `into` and returns [plain_button, text_button]; `on_change`
## gets true for Plain words.
static func rules_switch(into: HBoxContainer, is_plain: bool, on_change: Callable) -> Array[Button]:
var group := ButtonGroup.new()
var out: Array[Button] = []
for k in 2:
var b := Button.new()
b.text = "Plain words" if k == 0 else "Text"
b.toggle_mode = true
b.button_group = group
b.button_pressed = (k == 0) == is_plain
b.tooltip_text = "Show rules in plain words" if k == 0 else "Show rules as their stored text"
var n := box(Color(0, 0, 0, 0), 7, [11, 4, 11, 5])
var h := box(Color(1, 1, 1, 0.08), 7, [11, 4, 11, 5])
var on := box(CARD, 7, [11, 4, 11, 5])
skin_button(b, n, h, on, ON_FELT_MUTED, ON_FELT, INK)
b.add_theme_font_override("font", body_bold())
b.add_theme_font_size_override("font_size", 13)
var want := k == 0
b.pressed.connect(func() -> void: on_change.call(want))
into.add_child(b)
out.append(b)
return out
# ---------- Themes ---------- # ---------- Themes ----------
static func app_theme() -> Theme: static func app_theme() -> Theme:

View file

@ -15,22 +15,7 @@ extends PanelContainer
## A pick card whose options come from variables (docs/LOGIC.md §2a) says ## A pick card whose options come from variables (docs/LOGIC.md §2a) says
## "Options from @skill_* · where …" (in Play with how many are available ## "Options from @skill_* · where …" (in Play with how many are available
## now) and has a Chosen row first; any pick option can have a Show only if ## now) and has a Chosen row first; any pick option can have a Show only if
## condition, shown under its row ("only if …"). ## condition, edited under its row (the "if" toggle) in Build.
##
## Rules read in plain words (docs/PLAIN.md §6, Describe) or as their stored
## text, following RulesView.plain(main); cards rebuild on Main's
## rules_view_changed. Build mode only edits result text and the card's name
## inline; everything else (effects, conditions, details, card fields) is
## edited in Main's inspector, so rows show plain chips instead. Clicking a
## result row in Build calls main.select_result(table id, entry id) when Main
## has it; the selected row gets a copper bar on its left, from
## main.inspector_selection() ({"table_id", "entry_id"}) at rebuild time or
## set_selected_entry(entry id), which the inspector can call on any card.
##
## Check cards have a "2D" badge, their rule as a sentence and two outlet rows,
## Success and Failure. Collection cards list their members with live values
## (and "+ Add" in Build, which selects the card for the inspector). A card
## with inputs shows them in a dashed box under the header.
const WIDTH := 256.0 const WIDTH := 256.0
## Build mode has more controls per row, so cards are a little wider there. ## Build mode has more controls per row, so cards are a little wider there.
@ -68,10 +53,11 @@ var _style_selected: StyleBoxFlat
var _selected := false var _selected := false
var _deck_row: Control var _deck_row: Control
var _deck_label: Label var _deck_label: Label
## Unused since the inspector took over the inline editors; kept because ## Entry ids whose details editor is open (Build mode).
## Main's screenshot flags (--edit-details, --edit-effects) still set them.
var _open_details: Dictionary = {} var _open_details: Dictionary = {}
## Entry ids whose effects editor is open (Build mode).
var _open_effects: Dictionary = {} var _open_effects: Dictionary = {}
## Entry ids whose Show only if editor is open (Build mode, pick choices).
var _open_show_if: Dictionary = {} var _open_show_if: Dictionary = {}
## Play mode: "3 available now" on a dynamic pick card. ## Play mode: "3 available now" on a dynamic pick card.
var _options_label: Label var _options_label: Label
@ -82,13 +68,6 @@ var _var_value: Label
var _var_hint: Label var _var_hint: Label
var _sheet_label: RichTextLabel var _sheet_label: RichTextLabel
var _live_cache: Dictionary = {} var _live_cache: Dictionary = {}
## Rules in plain words (read from RulesView at each rebuild).
var _plain := true
## The result picked in the inspector (copper bar), or "".
var _selected_eid := ""
## Collection cards: the member list, refilled by refresh_live().
var _members_box: VBoxContainer
var _members_cache := ""
func setup(p_main: Main, p_table: RollTable) -> void: func setup(p_main: Main, p_table: RollTable) -> void:
@ -126,20 +105,8 @@ func setup(p_main: Main, p_table: RollTable) -> void:
for c in [Color(0, 0, 0, 0), Style.FLICK, Style.LIT]: for c in [Color(0, 0, 0, 0), Style.FLICK, Style.LIT]:
_row_styles.append(Style.box(c, 0, [12, 6, 22, 6])) _row_styles.append(Style.box(c, 0, [12, 6, 22, 6]))
# The same, with the copper bar of the inspector's selected result.
for c in [Color(0, 0, 0, 0), Style.FLICK, Style.LIT]:
var sel := Style.box(c, 0, [12, 6, 22, 6])
sel.border_width_left = 3
sel.border_color = Style.COPPER
sel.anti_aliasing = false
_row_styles.append(sel)
minimum_size_changed.connect(func() -> void: _shrink.call_deferred()) minimum_size_changed.connect(func() -> void: _shrink.call_deferred())
RulesView.watch(main, _on_rules_view_changed)
rebuild()
func _on_rules_view_changed(_v: Variant = null) -> void:
rebuild() rebuild()
@ -160,19 +127,7 @@ func rebuild() -> void:
_var_hint = null _var_hint = null
_sheet_label = null _sheet_label = null
_options_label = null _options_label = null
_members_box = null
_members_cache = ""
_live_cache.clear() _live_cache.clear()
_plain = RulesView.plain(main)
if main.has_method("inspector_selection"):
var sel: Variant = main.call("inspector_selection")
_selected_eid = ""
# The inspector reports {kind, tid, eid}; older callers used {table_id, entry_id}.
if sel is Dictionary:
var d := sel as Dictionary
var tid := str(d.get("tid", d.get("table_id", "")))
if tid == table.id and str(d.get("kind", "result")) == "result":
_selected_eid = str(d.get("eid", d.get("entry_id", "")))
var build := main.mode == Main.Mode.BUILD var build := main.mode == Main.Mode.BUILD
custom_minimum_size = Vector2(card_width(), 0) custom_minimum_size = Vector2(card_width(), 0)
@ -182,11 +137,16 @@ func rebuild() -> void:
var col := _vbox(0) var col := _vbox(0)
add_child(col) add_child(col)
col.add_child(_make_header(build, ranged)) col.add_child(_make_header(build, ranged))
if not table.inputs.is_empty() and table.kind != RollTable.KIND_VARIABLE: if build and _table_details_open:
col.add_child(_make_inputs_box()) var ted := _details_editor(table.details, "Details for this table (BBCode)", 12.0,
func(s: String) -> void:
table.details = s
main.mark_dirty())
ted.add_theme_constant_override("margin_top", 8)
col.add_child(ted)
if table.kind == RollTable.KIND_VARIABLE: if table.kind == RollTable.KIND_VARIABLE:
col.add_child(_make_collection_body(build) if table.is_collection() else _make_variable_body(build)) col.add_child(_make_variable_body(build))
_warn_panel = _make_warning() _warn_panel = _make_warning()
col.add_child(_warn_panel) col.add_child(_warn_panel)
_update_warning() _update_warning()
@ -224,11 +184,18 @@ func rebuild() -> void:
_list_box.add_child(_make_sheet_row(e, build)) _list_box.add_child(_make_sheet_row(e, build))
elif table.kind == RollTable.KIND_ROUTER and build: elif table.kind == RollTable.KIND_ROUTER and build:
_list_box.add_child(_make_case_row(e, i, numw)) _list_box.add_child(_make_case_row(e, i, numw))
elif table.kind == RollTable.KIND_CHECK:
_list_box.add_child(_make_check_row(e, i, build, numw))
else: else:
_list_box.add_child(_make_row(e, i, build, ranged, numw)) _list_box.add_child(_make_row(e, i, build, ranged, numw))
_set_row_state(e.id, RowState.LIT if lit else RowState.NORMAL) _set_row_state(e.id, RowState.LIT if lit else RowState.NORMAL)
if build and _open_show_if.has(e.id) and _is_pick():
_list_box.add_child(_show_if_editor(e, 12.0 + numw + 4.0))
if build and _open_effects.has(e.id):
_list_box.add_child(_effects_editor(e, 12.0 + numw + 4.0))
if build and _open_details.has(e.id):
_list_box.add_child(_details_editor(e.details, "Details for this result (BBCode)", 12.0 + numw + 4.0,
func(s: String) -> void:
e.details = s
main.mark_dirty()))
if collapsed: if collapsed:
_list_box.add_child(_make_more_row(numw)) _list_box.add_child(_make_more_row(numw))
@ -383,10 +350,7 @@ func _subtitle() -> String:
RollTable.KIND_ROLL: RollTable.KIND_ROLL:
if table.is_ranged(): if table.is_ranged():
var n := "%d ranges" % table.entries.size() var n := "%d ranges" % table.entries.size()
if table.is_expr_dice(): return "%s · %s" % [table.dice_label(), n] if table.is_expr_dice() else n
var dl := ("Roll " + Describe.dice(table.dice, main.data)) if _plain else table.dice_label()
return "%s · %s" % [dl, n]
return n
if table.collapsed: if table.collapsed:
return "%d results" % table.entries.size() return "%d results" % table.entries.size()
RollTable.KIND_CHOICE: RollTable.KIND_CHOICE:
@ -394,8 +358,6 @@ func _subtitle() -> String:
return "%d options" % table.entries.size() return "%d options" % table.entries.size()
RollTable.KIND_ROUTER: RollTable.KIND_ROUTER:
return "if / else if / otherwise · %d %s" % [table.entries.size(), "case" if table.entries.size() == 1 else "cases"] return "if / else if / otherwise · %d %s" % [table.entries.size(), "case" if table.entries.size() == 1 else "cases"]
RollTable.KIND_CHECK:
return "Check card"
return "" return ""
@ -438,10 +400,6 @@ func _make_go_button() -> Button:
b.add_theme_font_override("font", Style.body_bold(true)) b.add_theme_font_override("font", Style.body_bold(true))
b.add_theme_font_size_override("font_size", 14) b.add_theme_font_size_override("font_size", 14)
b.tooltip_text = "Print this sheet in the tray" b.tooltip_text = "Print this sheet in the tray"
RollTable.KIND_CHECK:
b.text = check_badge(table)
b.custom_minimum_size = Vector2(38, 0)
b.tooltip_text = "Roll the check: %s\nShift-click to skip the animation" % RulesView.check_line(table, main.data, _plain)
_: _:
left = 34 left = 34
var label := "d%d" % table.die_size() var label := "d%d" % table.die_size()
@ -481,16 +439,16 @@ func _make_kind_header(_build: bool) -> Control:
var kinds := {"pick": "Pick one", "number": "A number", "text": "Your words"} var kinds := {"pick": "Pick one", "number": "A number", "text": "Your words"}
var info := str(kinds.get(table.choice, "")) var info := str(kinds.get(table.choice, ""))
if table.choice == "number": if table.choice == "number":
info += " · %s to %s" % [RulesView.dice(table.min_expr, main.data, _plain), RulesView.dice(table.max_expr, main.data, _plain)] info += " · %s to %s" % [table.min_expr, table.max_expr]
if table.save_as != "": if table.save_as != "":
info += " · saves %s" % RulesView.value_name(table.save_as, main.data, _plain) info += " · saves %s" % table.save_as
var l := Style.make_label(info, Style.body(true), 12, Style.MUTED) var l := Style.make_label(info, Style.body(true), 12, Style.MUTED)
l.mouse_filter = MOUSE_FILTER_IGNORE l.mouse_filter = MOUSE_FILTER_IGNORE
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
v.add_child(l) v.add_child(l)
if table.is_dynamic(): if table.is_dynamic():
var bad := not Roller.lint_options(table).is_empty() var bad := not Roller.lint_options(table).is_empty()
var ol := Style.make_label(RulesView.options_line(table, main.data, _plain), Style.body_bold(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK) var ol := Style.make_label(options_line(table), Style.body_bold(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK)
ol.mouse_filter = MOUSE_FILTER_PASS ol.mouse_filter = MOUSE_FILTER_PASS
ol.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART ol.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
ol.tooltip_text = "One option per %s; the Chosen row runs for whichever is picked (option, option_label and option_value hold it)" % table.options_description() ol.tooltip_text = "One option per %s; the Chosen row runs for whichever is picked (option, option_label and option_value hold it)" % table.options_description()
@ -506,15 +464,10 @@ func _make_kind_header(_build: bool) -> Control:
chip.size_flags_horizontal = SIZE_SHRINK_BEGIN chip.size_flags_horizontal = SIZE_SHRINK_BEGIN
chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(Color(Style.BRASS, 0.16), 6, [8, 1, 8, 2]), 1, Color(Style.BRASS_DARK, 0.35))) chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(Color(Style.BRASS, 0.16), 6, [8, 1, 8, 2]), 1, Color(Style.BRASS_DARK, 0.35)))
var err := Expr.check(table.loop_expr) if table.loop_expr.strip_edges() != "" else "No rule yet" var err := Expr.check(table.loop_expr) if table.loop_expr.strip_edges() != "" else "No rule yet"
var rule := RulesView.loop_rule(table, main.data, _plain) var l := Style.make_label(loop_rule(table), Style.display(true), 16, Style.DANGER_INK if err != "" else Style.COPPER_DARK)
var l := Style.make_label(rule, Style.display(true), 16, Style.DANGER_INK if err != "" else Style.COPPER_DARK)
l.mouse_filter = MOUSE_FILTER_IGNORE l.mouse_filter = MOUSE_FILTER_IGNORE
if rule.length() > 26:
# A long plain rule wraps across the card instead of widening it.
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
chip.size_flags_horizontal = SIZE_FILL
chip.add_child(l) chip.add_child(l)
chip.tooltip_text = err if err != "" else (loop_rule(table) if _plain else "") chip.tooltip_text = err
return chip return chip
RollTable.KIND_ROUTER: RollTable.KIND_ROUTER:
if not _build: if not _build:
@ -525,104 +478,12 @@ func _make_kind_header(_build: bool) -> Control:
return rl return rl
RollTable.KIND_VARIABLE: RollTable.KIND_VARIABLE:
var txt := "@%s · %s" % [table.var_name, table.var_type] var txt := "@%s · %s" % [table.var_name, table.var_type]
if table.is_collection():
txt = "Collection · kept between rolls" if _plain else "@%s_* (board values)" % table.var_name
elif _plain:
txt = "%s · kept between rolls" % table.var_type.capitalize()
var l := Style.make_label(txt, Style.body(true), 12, Style.MUTED) var l := Style.make_label(txt, Style.body(true), 12, Style.MUTED)
l.mouse_filter = MOUSE_FILTER_IGNORE l.mouse_filter = MOUSE_FILTER_IGNORE
l.tooltip_text = "@" + table.var_name if _plain and not table.is_collection() else ""
if l.tooltip_text != "":
l.mouse_filter = MOUSE_FILTER_PASS
return l return l
RollTable.KIND_CHECK:
var cl := RichText.label(check_sentence(table, main.data, _plain), 14, Style.INK, true)
cl.mouse_filter = MOUSE_FILTER_IGNORE
return cl
return null return null
## The check card's "2D" badge (its dice in plain words, "Roll" when long).
static func check_badge(t: RollTable) -> String:
var d := Describe.dice(t.check_dice, null)
return d if d.length() <= 5 else "Roll"
## The check card's sentence under its header, as BBCode: "Roll 2D +
## Strength modifier, need [b]8 or more[/b]" (plain) or "[code]2d6 + dm(@str)
## vs 8+[/code]" style text.
static func check_sentence(t: RollTable, board: TowerBoard, plain: bool) -> String:
var s := RulesView.check_line(t, board, plain)
if not plain:
return "[color=#%s]%s[/color]" % [Style.COPPER_DARK.to_html(false), RichText.plain(s)]
var at := s.rfind(", need ")
if at < 0:
return RichText.plain(s)
return "%s, need [b]%s[/b]" % [RichText.plain(s.substr(0, at)), RichText.plain(s.substr(at + 7))]
## A dashed box under the header naming the card's inputs: "Input Tier ·
## starts at 1" (plain) or "input tier · default 1" (text), one line each.
func _make_inputs_box() -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 10)
wrap.add_theme_constant_override("margin_right", 10)
wrap.add_theme_constant_override("margin_top", 8)
var p := PanelContainer.new()
p.mouse_filter = MOUSE_FILTER_PASS
p.add_theme_stylebox_override("panel", DashedBox.new())
p.tooltip_text = "Values a pipe into this card can pass (\"with\"); a roll that starts here uses the starting values"
wrap.add_child(p)
var v := _vbox(2)
p.add_child(v)
for inp: Dictionary in table.inputs:
var line := RichText.label(input_line(inp, main.data, _plain), 13, Style.MUTED, true)
line.mouse_filter = MOUSE_FILTER_IGNORE
line.set_meta("input_line", true)
v.add_child(line)
wrap.set_meta("inputs_box", true)
return wrap
## One input as BBCode: "Input [b]Tier[/b] · starts at [b]1[/b]".
static func input_line(inp: Dictionary, board: TowerBoard, plain: bool) -> String:
var nm := str(inp.get("name", ""))
var def := str(inp.get("default", "")).strip_edges()
var ink := Style.INK.to_html(false)
if not plain:
return "input [color=#%s]%s[/color] · default [color=#%s]%s[/color]" % [ink, RichText.plain(nm), ink, RichText.plain(def if def != "" else "0")]
var lab := str(inp.get("label", "")).strip_edges()
if lab == "":
lab = Describe.label(nm, board)
var shown := Describe.dice(def, board) if def != "" else "0"
return "Input [color=#%s][b]%s[/b][/color] · starts at [color=#%s][b]%s[/b][/color]" % [ink, RichText.plain(lab), ink, RichText.plain(shown)]
## A dashed rounded outline (the inputs box), since StyleBoxFlat has no
## dashes.
class DashedBox extends StyleBox:
func _init() -> void:
content_margin_left = 9
content_margin_right = 9
content_margin_top = 6
content_margin_bottom = 6
func _draw(to_canvas_item: RID, rect: Rect2) -> void:
var r := rect.grow(-0.5)
var pts := PackedVector2Array([r.position, Vector2(r.end.x, r.position.y), r.end, Vector2(r.position.x, r.end.y), r.position])
var col := Style.DASH
for i in 4:
var a := pts[i]
var b := pts[i + 1]
var seg_len := a.distance_to(b)
var d := 0.0
while d < seg_len:
var e := minf(d + 5.0, seg_len)
RenderingServer.canvas_item_add_line(to_canvas_item, a.lerp(b, d / seg_len), a.lerp(b, e / seg_len), col, 1.2, true)
d += 9.0
## A fork: one stem splitting into two branches, each ending in a dot (the ## A fork: one stem splitting into two branches, each ending in a dot (the
## router card's go button). `r` is about half the icon's height. ## router card's go button). `r` is about half the icon's height.
static func draw_fork(ci: CanvasItem, c: Vector2, r: float, color: Color, width: float = 2.0) -> void: static func draw_fork(ci: CanvasItem, c: Vector2, r: float, color: Color, width: float = 2.0) -> void:
@ -749,55 +610,23 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
var text: RichTextLabel = null var text: RichTextLabel = null
if build: if build:
h.add_theme_constant_override("separation", 4) h.add_theme_constant_override("separation", 4)
var col := _vbox(2)
col.size_flags_horizontal = SIZE_EXPAND_FILL
col.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(col)
if table.kind == RollTable.KIND_CHOICE and table.choice != "pick": if table.kind == RollTable.KIND_CHOICE and table.choice != "pick":
var al := Style.make_label("Answer", Style.body_italic(true), 15, Style.MUTED) var al := Style.make_label("Answer", Style.body_italic(true), 15, Style.MUTED)
al.size_flags_horizontal = SIZE_EXPAND_FILL al.size_flags_horizontal = SIZE_EXPAND_FILL
al.size_flags_vertical = SIZE_SHRINK_CENTER al.size_flags_vertical = SIZE_SHRINK_CENTER
al.mouse_filter = MOUSE_FILTER_PASS
al.tooltip_text = "Its effects and pipes run after the player answers ({answer} holds the answer)" al.tooltip_text = "Its effects and pipes run after the player answers ({answer} holds the answer)"
col.add_child(al) h.add_child(al)
else: else:
var cbox: VBoxContainer = null
if chosen: if chosen:
# A caption over the text field, so the field keeps its width. # A caption over the text field, so the field keeps its width.
cbox = _vbox(0)
cbox.size_flags_horizontal = SIZE_EXPAND_FILL
var cl := Style.make_label("Chosen · runs for the picked option", Style.body_italic(true), 11, Style.COPPER_DARK) var cl := Style.make_label("Chosen · runs for the picked option", Style.body_italic(true), 11, Style.COPPER_DARK)
cl.mouse_filter = MOUSE_FILTER_PASS cl.mouse_filter = MOUSE_FILTER_PASS
cl.tooltip_text = "Runs for whichever option from %s is picked: option, option_label and option_value hold it" % table.options_from.strip_edges() cl.tooltip_text = "Runs for whichever option from %s is picked: option, option_label and option_value hold it" % table.options_from.strip_edges()
col.add_child(cl) cbox.add_child(cl)
col.add_child(_text_edit(e, index, chosen)) h.add_child(cbox)
_add_rule_chips(col, e)
if not ranged and not fixed:
h.add_child(_weight_edit(e))
if not fixed and not chosen:
h.add_child(_mini_button("×", "Delete this result", true, func() -> void: main.delete_entry(table.id, e.id)))
_hook_select(row, e.id)
else:
var col := _vbox(3)
col.size_flags_horizontal = SIZE_EXPAND_FILL
col.size_flags_vertical = SIZE_SHRINK_CENTER
text = RichText.label(_row_text(e), 16, Style.INK, true)
text.size_flags_horizontal = SIZE_EXPAND_FILL
RichText.hook_hover(text, main)
col.add_child(text)
_add_rule_chips(col, e)
h.add_child(col)
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
if ranged and table.has_chances():
var pct := Style.make_label("%d%%" % roundi(table.chance(e) * 100.0), Style.body(true), 12, Style.MUTED)
pct.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(pct)
rows[e.id] = row
_row_parts[e.id] = {"num": num, "text": text, "entry": e, "index": index}
return row
## Build mode: the inline result-text field of a row. Focusing it selects the
## result for the inspector.
func _text_edit(e: TableEntry, index: int, chosen: bool) -> LineEdit:
var edit := LineEdit.new() var edit := LineEdit.new()
edit.text = e.text edit.text = e.text
if chosen: if chosen:
@ -810,73 +639,66 @@ func _text_edit(e: TableEntry, index: int, chosen: bool) -> LineEdit:
if table.kind == RollTable.KIND_LOOP: if table.kind == RollTable.KIND_LOOP:
edit.placeholder_text = LOOP_ROWS[clampi(index, 0, 1)] edit.placeholder_text = LOOP_ROWS[clampi(index, 0, 1)]
edit.tooltip_text = "%s: shown each pass ({i} is the pass number)" % LOOP_ROWS[0] if index == 0 else "%s: runs once when the loop ends" % LOOP_ROWS[1] edit.tooltip_text = "%s: shown each pass ({i} is the pass number)" % LOOP_ROWS[0] if index == 0 else "%s: runs once when the loop ends" % LOOP_ROWS[1]
elif table.kind == RollTable.KIND_ROUTER:
edit.placeholder_text = "Result text"
edit.text_changed.connect(func(s: String) -> void: edit.text_changed.connect(func(s: String) -> void:
e.text = s e.text = s
main.mark_dirty() main.mark_dirty()
) )
edit.focus_entered.connect(func() -> void: _select_entry(e.id)) if cbox != null:
return edit cbox.add_child(edit)
else:
h.add_child(edit)
## The plain chips under a row's text: a pick option's "only if …" and the if not ranged and not fixed:
## entry's effects ("Luck −1"). Used in Play and Build alike. h.add_child(_weight_edit(e))
func _add_rule_chips(col: VBoxContainer, e: TableEntry) -> void: if _is_pick():
var sbad := e.show_if.strip_edges() != "" and Expr.check(TemplateKit.probe(e.show_if.strip_edges())) != ""
var sb := _toggle_button("if", "Show only if: hide this option unless a condition is true when the card is reached",
_open_show_if, e.id, e.show_if.strip_edges() != "", sbad)
sb.add_theme_font_size_override("font_size", 11)
h.add_child(sb)
h.add_child(_toggle_button("ƒ", "Effects: statements such as @hp -= 1 that run when this comes up",
_open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(TemplateKit.probe(e.effects)).is_empty()))
h.add_child(_toggle_button("i", "Details shown when hovering this result",
_open_details, e.id, e.details.strip_edges() != "", false))
if not fixed and not chosen:
var x := Button.new()
x.text = "×"
x.tooltip_text = "Delete this result"
x.custom_minimum_size = Vector2(22, 22)
x.size_flags_vertical = SIZE_SHRINK_CENTER
x.add_theme_font_size_override("font_size", 18)
Style.skin_button(x, Style.box(Color(0, 0, 0, 0), 5), Style.box(Color("#e6dfcd"), 5), Style.box(Color("#e6dfcd"), 5), Style.MUTED, Style.DANGER_INK)
x.pressed.connect(func() -> void: main.delete_entry(table.id, e.id))
h.add_child(x)
else:
var col := _vbox(3)
col.size_flags_horizontal = SIZE_EXPAND_FILL
col.size_flags_vertical = SIZE_SHRINK_CENTER
text = RichText.label(_row_text(e), 16, Style.INK, true)
text.size_flags_horizontal = SIZE_EXPAND_FILL
RichText.hook_hover(text, main)
col.add_child(text)
if _is_pick() and e.show_if.strip_edges() != "": if _is_pick() and e.show_if.strip_edges() != "":
var bad := Expr.check(TemplateKit.probe(e.show_if.strip_edges())) != "" var si := Style.make_label("only if " + e.show_if.strip_edges(), Style.body_bold(true), 12, Style.COPPER_DARK)
var si := Style.make_label(RulesView.show_if_line(e, main.data, _plain), Style.body_bold(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK)
si.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART si.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
si.mouse_filter = MOUSE_FILTER_PASS si.mouse_filter = MOUSE_FILTER_IGNORE
si.tooltip_text = ("only if " + e.show_if.strip_edges()) if _plain else ""
si.set_meta("show_if_line", true)
col.add_child(si) col.add_child(si)
if e.effects.strip_edges() != "": if e.effects.strip_edges() != "":
col.add_child(_effects_chip(e)) col.add_child(_effects_chip(e))
h.add_child(col)
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
if ranged and table.has_chances():
var pct := Style.make_label("%d%%" % roundi(table.chance(e) * 100.0), Style.body(true), 12, Style.MUTED)
pct.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(pct)
rows[e.id] = row
_row_parts[e.id] = {"num": num, "text": text, "entry": e, "index": index}
return row
## Build mode: a click on a row (outside its fields) selects the result for ## Build mode: one router case. The first line is its condition (empty means
## the inspector. ## Otherwise), validated as you type, with move up / down and delete; the
func _hook_select(row: Control, eid: String) -> void: ## second is its result text with the effects and details toggles.
row.gui_input.connect(func(ev: InputEvent) -> void:
var mb := ev as InputEventMouseButton
if mb and mb.button_index == MOUSE_BUTTON_LEFT and mb.pressed:
_select_entry(eid)
)
## Selects a result for the inspector: main.select_result(table id, entry id)
## when Main has it, and the copper bar on this row (cleared on other cards).
func _select_entry(eid: String) -> void:
if main.mode != Main.Mode.BUILD:
return
if main.has_method("select_result"):
main.call("select_result", table.id, eid)
for c: Variant in main.cards.values():
if c is TableCard and c != self:
(c as TableCard).set_selected_entry("")
set_selected_entry(eid)
## Shows the copper selection bar on one result row ("" for none). The
## inspector may call this on every card when its selection changes.
func set_selected_entry(eid: String) -> void:
if _selected_eid == eid:
return
var old := _selected_eid
_selected_eid = eid
for k: String in [old, eid]:
if k != "" and rows.has(k):
_set_row_state(k, RowState.LIT if main.is_entry_lit(table.id, k) else RowState.NORMAL)
func selected_entry() -> String:
return _selected_eid
## Build mode: one router case. The first line is its condition, in plain
## words or as written (edited in the inspector), with move up / down and
## delete; the second is its result text, then its effects chip.
func _make_case_row(e: TableEntry, index: int, numw: float) -> Control: func _make_case_row(e: TableEntry, index: int, numw: float) -> Control:
var row := PanelContainer.new() var row := PanelContainer.new()
row.mouse_filter = MOUSE_FILTER_PASS row.mouse_filter = MOUSE_FILTER_PASS
@ -894,82 +716,63 @@ func _make_case_row(e: TableEntry, index: int, numw: float) -> Control:
var top := _hbox(4) var top := _hbox(4)
v.add_child(top) v.add_child(top)
var w := e.when.strip_edges() var if_label := Style.make_label("if", Style.body_bold(true), 14, Style.COPPER_DARK)
var bad := w != "" and Expr.check(TemplateKit.probe(w)) != "" if_label.size_flags_vertical = SIZE_SHRINK_CENTER
var cond := Style.make_label(RulesView.case_label(e, main.data, _plain), Style.body_bold(true), 14, Style.DANGER_INK if bad else Style.COPPER_DARK) top.add_child(if_label)
cond.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART var cond := LineEdit.new()
cond.text = e.when
cond.placeholder_text = "Otherwise"
cond.size_flags_horizontal = SIZE_EXPAND_FILL cond.size_flags_horizontal = SIZE_EXPAND_FILL
cond.size_flags_vertical = SIZE_SHRINK_CENTER cond.size_flags_vertical = SIZE_SHRINK_CENTER
cond.mouse_filter = MOUSE_FILTER_PASS cond.custom_minimum_size = Vector2(40, 0)
cond.tooltip_text = ("⚠ " + Expr.check(TemplateKit.probe(w))) if bad else (("if " + w) if _plain and w != "" else "Cases are checked top to bottom; the first true one is chosen") cond.add_theme_font_override("font", Style.body_bold(true))
cond.set_meta("case_line", true) cond.add_theme_font_size_override("font_size", 14)
cond.add_theme_color_override("font_color", Style.COPPER_DARK)
var ok_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Color(Style.BRASS_DARK, 0.4))
var focus_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.COPPER)
var bad_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.DANGER_INK)
var check := func() -> void:
var src := TemplateKit.probe(cond.text.strip_edges())
var err := Expr.check(src) if src != "" else ""
cond.add_theme_stylebox_override("normal", bad_box if err != "" else ok_box)
cond.add_theme_stylebox_override("focus", bad_box if err != "" else focus_box)
cond.tooltip_text = ("⚠ " + err) if err != "" else "This case is chosen when this is true (cases are checked top to bottom). Leave it empty for Otherwise."
if_label.text = "if" if cond.text.strip_edges() != "" else "else"
cond.text_changed.connect(func(t: String) -> void:
e.when = t.strip_edges()
check.call()
_update_warning()
main.mark_dirty()
)
check.call()
top.add_child(cond) top.add_child(cond)
top.add_child(_mini_button("↑", "Move this case up", index > 0, func() -> void: _move_case(index, -1))) top.add_child(_mini_button("↑", "Move this case up", index > 0, func() -> void: _move_case(index, -1)))
top.add_child(_mini_button("↓", "Move this case down", index < table.entries.size() - 1, func() -> void: _move_case(index, 1))) top.add_child(_mini_button("↓", "Move this case down", index < table.entries.size() - 1, func() -> void: _move_case(index, 1)))
top.add_child(_mini_button("×", "Delete this case", true, func() -> void: main.delete_entry(table.id, e.id))) top.add_child(_mini_button("×", "Delete this case", true, func() -> void: main.delete_entry(table.id, e.id)))
v.add_child(_text_edit(e, index, false)) var bottom := _hbox(4)
_add_rule_chips(v, e) v.add_child(bottom)
_hook_select(row, e.id) var edit := LineEdit.new()
edit.text = e.text
edit.placeholder_text = "Result text"
edit.size_flags_horizontal = SIZE_EXPAND_FILL
edit.size_flags_vertical = SIZE_SHRINK_CENTER
edit.custom_minimum_size = Vector2(40, 0)
edit.add_theme_font_size_override("font_size", 15)
edit.text_changed.connect(func(t: String) -> void:
e.text = t
main.mark_dirty()
)
bottom.add_child(edit)
bottom.add_child(_toggle_button("ƒ", "Effects: statements such as @hp -= 1 that run when this case is chosen",
_open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(TemplateKit.probe(e.effects)).is_empty()))
bottom.add_child(_toggle_button("i", "Details shown when hovering this case",
_open_details, e.id, e.details.strip_edges() != "", false))
rows[e.id] = row rows[e.id] = row
_row_parts[e.id] = {"num": num, "text": null, "entry": e, "index": index} _row_parts[e.id] = {"num": num, "text": null, "entry": e, "index": index}
return row return row
## One outlet of a check card: "8+ Success · the bars give" / "≤7 Failure",
## with the outlet named in green or red. Build edits the text after the name.
func _make_check_row(e: TableEntry, index: int, build: bool, numw: float) -> Control:
var row := PanelContainer.new()
row.mouse_filter = MOUSE_FILTER_PASS
row.custom_minimum_size = Vector2(0, 36)
var h := _hbox(8)
row.add_child(h)
var outs := RulesView.check_outlets(table)
var num := Style.make_label(outs[index] if index < 2 else str(index + 1), Style.display(true), 16, Style.MUTED)
num.custom_minimum_size = Vector2(maxf(numw, 34.0), 0)
num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
num.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(num)
var col := _vbox(2)
col.size_flags_horizontal = SIZE_EXPAND_FILL
col.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(col)
var text: RichTextLabel = null
if build:
var line := _hbox(6)
col.add_child(line)
var nm := Style.make_label(check_outlet_name(index), Style.body_bold(true), 15, check_outlet_color(index))
nm.size_flags_vertical = SIZE_SHRINK_CENTER
line.add_child(nm)
var edit := _text_edit(e, index, false)
# The outlet name is already shown, so a result text that just repeats
# it ("Success") shows as an empty field with a hint instead.
if e.text.strip_edges() == check_outlet_name(index):
edit.text = ""
edit.placeholder_text = "What happens on a %s (optional)" % check_outlet_name(index).to_lower()
line.add_child(edit)
_add_rule_chips(col, e)
_hook_select(row, e.id)
else:
text = RichText.label(_row_text(e), 16, Style.INK, true)
text.size_flags_horizontal = SIZE_EXPAND_FILL
RichText.hook_hover(text, main)
col.add_child(text)
_add_rule_chips(col, e)
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
rows[e.id] = row
_row_parts[e.id] = {"num": num, "text": text, "entry": e, "index": index}
return row
static func check_outlet_name(index: int) -> String:
return "Success" if index == 0 else ("Failure" if index == 1 else "Result %d" % (index + 1))
static func check_outlet_color(index: int) -> Color:
return Style.OK_INK if index == 0 else Style.NO_INK
func _mini_button(glyph: String, tip: String, enabled: bool, on_press: Callable) -> Button: func _mini_button(glyph: String, tip: String, enabled: bool, on_press: Callable) -> Button:
var b := Button.new() var b := Button.new()
b.text = glyph b.text = glyph
@ -1011,15 +814,40 @@ func add_case() -> void:
const LOOP_ROWS := ["Each time", "Afterwards"] const LOOP_ROWS := ["Each time", "Afterwards"]
## Longest effects summary shown on a chip. ## Longest effects summary shown on a Play-mode chip.
const CHIP_CHARS := 30 const CHIP_CHARS := 30
const PLAIN_CHIP_CHARS := 38
## A small round toggle in a Build row ("i" details, "ƒ" effects). `open` is
## the dictionary of entry ids whose editor is shown.
func _toggle_button(glyph: String, tip: String, open: Dictionary, eid: String, has: bool, bad: bool) -> Button:
var b := Button.new()
b.text = glyph
b.toggle_mode = true
b.button_pressed = open.has(eid)
b.tooltip_text = tip
b.custom_minimum_size = Vector2(22, 22)
b.size_flags_vertical = SIZE_SHRINK_CENTER
b.add_theme_font_override("font", Style.body_bold(true))
b.add_theme_font_size_override("font_size", 13)
var ring := Style.DANGER_INK if bad else (Style.COPPER if has else Style.DASH)
var inn := Style.bordered(Style.box(Color(0, 0, 0, 0), 11), 1, ring)
var inh := Style.bordered(Style.box(Color("#e6dfcd"), 11), 1, Style.COPPER)
var inp := Style.bordered(Style.box(Style.LIT, 11), 1, Style.COPPER)
Style.skin_button(b, inn, inh, inp, ring if (has or bad) else Style.MUTED, Style.INK)
b.toggled.connect(func(on: bool) -> void:
if on:
open[eid] = true
else:
open.erase(eid)
rebuild()
)
return b
## Play-mode text of a row: the last rolled (expanded) text when the row is ## Play-mode text of a row: the last rolled (expanded) text when the row is
## lit, otherwise the entry as written with its references shown readably. ## lit, otherwise the entry as written with its references shown readably.
## Loop rows read "Each time · …"; a number/text choice's row is its answer; ## Loop rows read "Each time · …"; a number/text choice's row is its answer.
## a router case leads with its condition, a check outlet with its name.
func _row_text(e: TableEntry) -> String: func _row_text(e: TableEntry) -> String:
var rolled := main.lit_text(table.id, e.id) var rolled := main.lit_text(table.id, e.id)
var s := RichText.decorate(rolled) if rolled != "" else RichText.preview(e.text, main.data) var s := RichText.decorate(rolled) if rolled != "" else RichText.preview(e.text, main.data)
@ -1034,19 +862,12 @@ func _row_text(e: TableEntry) -> String:
s = "[color=#%s]%s ·[/color] %s" % [muted, cap, s] s = "[color=#%s]%s ·[/color] %s" % [muted, cap, s]
elif table.kind == RollTable.KIND_ROUTER: elif table.kind == RollTable.KIND_ROUTER:
var bad := e.when.strip_edges() != "" and Expr.check(e.when.strip_edges()) != "" var bad := e.when.strip_edges() != "" and Expr.check(e.when.strip_edges()) != ""
var label := RulesView.case_label(e, main.data, _plain) var cond := "[color=#%s][b]%s[/b][/color]" % [(Style.DANGER_INK if bad else Style.COPPER_DARK).to_html(false), RichText.plain(case_label(e))]
var cond := "[color=#%s][b]%s[/b][/color]" % [(Style.DANGER_INK if bad else Style.COPPER_DARK).to_html(false), RichText.plain(label)]
var plain_text := Formatter.strip_tags(e.text).strip_edges() var plain_text := Formatter.strip_tags(e.text).strip_edges()
if plain_text == "" or plain_text == case_label(e) or plain_text == label or plain_text == "if …" or (plain_text == "Otherwise" and e.when.strip_edges() == ""): if plain_text == "" or plain_text == case_label(e) or plain_text == "if …" or (plain_text == "Otherwise" and e.when.strip_edges() == ""):
s = cond s = cond
else: else:
s = "%s\n%s" % [cond, s] s = "%s\n%s" % [cond, s]
elif table.kind == RollTable.KIND_CHECK:
var index := table.entries.find(e)
var nm := check_outlet_name(index)
var head := "[color=#%s][b]%s[/b][/color]" % [check_outlet_color(index).to_html(false), nm]
var own := Formatter.strip_tags(rolled if rolled != "" else e.text).strip_edges()
s = head if own == "" or own == nm else "%s · %s" % [head, s]
elif table.is_dynamic() and table.entries.find(e) == 0: elif table.is_dynamic() and table.entries.find(e) == 0:
var own := Formatter.strip_tags(e.text).strip_edges() var own := Formatter.strip_tags(e.text).strip_edges()
if rolled != "": if rolled != "":
@ -1065,9 +886,7 @@ func _row_text(e: TableEntry) -> String:
return s return s
## A subtle brass chip summarising an entry's effects: "Luck −1 · Gold + 2D" ## Play mode: a subtle brass chip summarising an entry's effects ("STR = 2d6").
## in plain words, "@luck -= 1 · @gold += 2d6" as text. Its tooltip has the
## other form, every statement on its own line.
func _effects_chip(e: TableEntry) -> Control: func _effects_chip(e: TableEntry) -> Control:
var bad := not Effects.validate(TemplateKit.probe(e.effects)).is_empty() var bad := not Effects.validate(TemplateKit.probe(e.effects)).is_empty()
var chip := PanelContainer.new() var chip := PanelContainer.new()
@ -1076,22 +895,19 @@ func _effects_chip(e: TableEntry) -> Control:
var bg := Color(Style.DANGER_INK, 0.1) if bad else Color(Style.BRASS, 0.2) var bg := Color(Style.DANGER_INK, 0.1) if bad else Color(Style.BRASS, 0.2)
var line := Color(Style.DANGER_INK, 0.4) if bad else Color(Style.BRASS_DARK, 0.3) var line := Color(Style.DANGER_INK, 0.4) if bad else Color(Style.BRASS_DARK, 0.3)
chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(bg, 5, [6, 0, 6, 1]), 1, line)) chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(bg, 5, [6, 0, 6, 1]), 1, line))
var summary := RulesView.effects_line(e.effects, main.data, table, _plain) var summary := effect_summary(e.effects, main.data)
# Cut long summaries by hand: a clipped Label would collapse to nothing. # Cut long summaries by hand: a clipped Label would collapse to nothing.
summary = RulesView.cut(summary, PLAIN_CHIP_CHARS if _plain else CHIP_CHARS) if summary.length() > CHIP_CHARS:
var l := Style.make_label(summary, Style.body_bold(true) if _plain else Style.body(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK) summary = summary.substr(0, CHIP_CHARS - 1).strip_edges() + "…"
var l := Style.make_label(summary, Style.body(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK)
l.mouse_filter = MOUSE_FILTER_IGNORE l.mouse_filter = MOUSE_FILTER_IGNORE
chip.add_child(l) chip.add_child(l)
chip.set_meta("effects_chip", summary)
if _plain:
chip.tooltip_text = "\n".join(Effects.split(e.effects)) chip.tooltip_text = "\n".join(Effects.split(e.effects))
else:
chip.tooltip_text = "\n".join(Describe.effects(e.effects, main.data, table))
return chip return chip
## A short summary of effect text as written: the first two statements, with ## A short summary of effect text: the first two statements, with declared
## declared variables by their card's name ("STR = 2d6 · Terms += 1 · +3"). ## variables by their card's name ("STR = 2d6 · Terms += 1 · +3").
static func effect_summary(text: String, board: TowerBoard) -> String: static func effect_summary(text: String, board: TowerBoard) -> String:
var list := Effects.split(text) var list := Effects.split(text)
var parts := PackedStringArray() var parts := PackedStringArray()
@ -1116,6 +932,94 @@ static func effect_summary(text: String, board: TowerBoard) -> String:
return " · ".join(parts) return " · ".join(parts)
## Build mode: the Show only if editor under a pick option, validated as you
## type (like a router case's condition).
func _show_if_editor(e: TableEntry, left: float) -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", int(left))
wrap.add_theme_constant_override("margin_right", 12)
wrap.add_theme_constant_override("margin_top", 2)
wrap.add_theme_constant_override("margin_bottom", 6)
var h := _hbox(6)
wrap.add_child(h)
var lbl := Style.make_label("Show only if", Style.body_bold(true), 12, Style.COPPER_DARK)
lbl.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(lbl)
var le := LineEdit.new()
le.text = e.show_if
le.placeholder_text = "always" if not _is_chosen_row(table.entries.find(e)) else "always (hides every option from variables when false)"
le.size_flags_horizontal = SIZE_EXPAND_FILL
le.custom_minimum_size = Vector2(40, 0)
le.add_theme_font_override("font", Style.body_bold(true))
le.add_theme_font_size_override("font_size", 13)
le.add_theme_color_override("font_color", Style.COPPER_DARK)
var ok_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Color(Style.BRASS_DARK, 0.4))
var focus_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.COPPER)
var bad_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.DANGER_INK)
var check := func() -> void:
var src := TemplateKit.probe(le.text.strip_edges())
var err := Expr.check(src) if src != "" else ""
le.add_theme_stylebox_override("normal", bad_box if err != "" else ok_box)
le.add_theme_stylebox_override("focus", bad_box if err != "" else focus_box)
le.tooltip_text = ("⚠ " + err) if err != "" else "Checked when the card is reached: when it's false this option isn't offered, not even to Random. e.g. @commissioned, @last_career != \"Army\""
le.text_changed.connect(func(t: String) -> void:
e.show_if = t.strip_edges()
check.call()
main.mark_dirty()
)
check.call()
h.add_child(le)
return wrap
## Build mode: the effects editor under a row, validated as you type.
func _effects_editor(e: TableEntry, left: float) -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", int(left))
wrap.add_theme_constant_override("margin_right", 12)
wrap.add_theme_constant_override("margin_top", 2)
wrap.add_theme_constant_override("margin_bottom", 6)
var v := _vbox(3)
wrap.add_child(v)
var te := TextEdit.new()
te.text = e.effects
te.placeholder_text = "@hp -= 1\n@gold += 2d6\nreset @loot"
te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
te.custom_minimum_size = Vector2(0, 58)
te.scroll_fit_content_height = true
te.add_theme_font_override("font", Style.body(true))
te.add_theme_font_size_override("font_size", 13)
te.add_theme_color_override("font_color", Style.INK)
te.add_theme_color_override("font_placeholder_color", Style.MUTED)
te.add_theme_color_override("caret_color", Style.INK)
te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
var ok_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 4, 7, 4]), 1, Color(Style.BRASS_DARK, 0.4))
var focus_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 4, 7, 4]), 1, Style.COPPER)
var bad_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 4, 7, 4]), 1, Style.DANGER_INK)
v.add_child(te)
var msg := Style.make_label("", Style.body(true), 12, Style.DANGER_INK)
msg.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
v.add_child(msg)
var check := func() -> void:
var problems := Effects.validate(TemplateKit.probe(te.text))
var lines := PackedStringArray()
for p: Dictionary in problems:
lines.append("⚠ %s: %s" % [p["src"], p["error"]])
msg.text = "\n".join(lines)
msg.visible = not lines.is_empty()
te.add_theme_stylebox_override("normal", bad_box if not lines.is_empty() else ok_box)
te.add_theme_stylebox_override("focus", bad_box if not lines.is_empty() else focus_box)
te.text_changed.connect(func() -> void:
e.effects = te.text
check.call()
main.mark_dirty()
)
check.call()
return wrap
## A sheet card's one row: the rendered template in Play, its editor in Build. ## A sheet card's one row: the rendered template in Play, its editor in Build.
func _make_sheet_row(e: TableEntry, build: bool) -> Control: func _make_sheet_row(e: TableEntry, build: bool) -> Control:
var row := PanelContainer.new() var row := PanelContainer.new()
@ -1143,16 +1047,16 @@ func _make_sheet_row(e: TableEntry, build: bool) -> Control:
e.text = te.text e.text = te.text
main.mark_dirty() main.mark_dirty()
) )
te.focus_entered.connect(func() -> void: _select_entry(e.id))
v.add_child(te) v.add_child(te)
var tools := _vbox(2) var tools := _hbox(4)
if e.effects.strip_edges() != "": tools.add_child(_toggle_button("ƒ", "Effects that run when the chain reaches this sheet",
tools.add_child(_effects_chip(e)) _open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(TemplateKit.probe(e.effects)).is_empty()))
tools.add_child(_toggle_button("i", "Details shown when hovering the sheet",
_open_details, e.id, e.details.strip_edges() != "", false))
var pv := Style.make_label("Preview on the board in Play", Style.body_italic(true), 12, Style.MUTED) var pv := Style.make_label("Preview on the board in Play", Style.body_italic(true), 12, Style.MUTED)
pv.size_flags_vertical = SIZE_SHRINK_CENTER pv.size_flags_vertical = SIZE_SHRINK_CENTER
tools.add_child(pv) tools.add_child(pv)
v.add_child(tools) v.add_child(tools)
_hook_select(row, e.id)
_sheet_label = null _sheet_label = null
else: else:
_sheet_label = RichText.label("", 15, Style.INK, true) _sheet_label = RichText.label("", 15, Style.INK, true)
@ -1186,8 +1090,7 @@ func _make_variable_body(build: bool) -> Control:
v.add_child(_var_hint) v.add_child(_var_hint)
if build: if build:
var h := _hbox(8) var h := _hbox(8)
var init := RulesView.dice(table.initial, main.data, _plain) if table.initial.strip_edges() != "" else "" var start := Style.make_label("Starts at %s" % (table.initial if table.initial.strip_edges() != "" else ("0" if table.var_type == "number" else "nothing")),
var start := Style.make_label("Starts at %s" % (init if init != "" else ("0" if table.var_type == "number" else "nothing")),
Style.body(true), 12, Style.MUTED) Style.body(true), 12, Style.MUTED)
start.size_flags_horizontal = SIZE_EXPAND_FILL start.size_flags_horizontal = SIZE_EXPAND_FILL
start.size_flags_vertical = SIZE_SHRINK_CENTER start.size_flags_vertical = SIZE_SHRINK_CENTER
@ -1206,96 +1109,10 @@ func _make_variable_body(build: bool) -> Control:
return wrap return wrap
## A collection card's body: its members with their live values (refilled by
## refresh_live()), and in Build "+ Add …", which selects the card so the
## inspector can add a member.
func _make_collection_body(build: bool) -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 12)
wrap.add_theme_constant_override("margin_right", 14)
wrap.add_theme_constant_override("margin_top", 6)
wrap.add_theme_constant_override("margin_bottom", 10)
var v := _vbox(6)
wrap.add_child(v)
_members_box = _vbox(0)
v.add_child(_members_box)
if build:
var add := _footer_button("+ Add " + Describe._singular(Formatter.strip_tags(table.name).strip_edges().to_lower()), Style.INK)
add.size_flags_horizontal = SIZE_FILL
add.tooltip_text = "Add a member in the inspector"
add.set_meta("collection_add", true)
add.pressed.connect(func() -> void:
if main.has_method("select_card"):
main.call("select_card", table.id)
else:
main.request_table_settings(table.id)
)
v.add_child(add)
return wrap
## A collection's members: [{name ("@skill_pilot"), label ("Pilot"), value
## (Variant or null when not set)}], set members first, then members only
## named by the board's rules, each sorted by label.
static func collection_members(t: RollTable, board: TowerBoard, vars: Dictionary) -> Array[Dictionary]:
var out: Array[Dictionary] = []
if t == null or not t.is_collection() or t.var_name == "":
return out
var seen := {}
for v: Dictionary in RollContext.vars_with_prefix(vars, t.var_name + "_"):
var nm := "@" + str(v["name"])
seen[nm] = true
out.append({"name": nm, "label": Describe.label(nm, board), "value": v["value"]})
var named: Array[Dictionary] = []
for kv: Dictionary in Builder.known_values(board):
if str(kv.get("collection", "")) == "@%s_*" % t.var_name and not seen.has(str(kv["name"])):
seen[str(kv["name"])] = true
named.append({"name": str(kv["name"]), "label": str(kv["label"]), "value": null})
var by_label := func(a: Dictionary, b: Dictionary) -> bool: return str(a["label"]).naturalnocasecmp_to(str(b["label"])) < 0
out.sort_custom(by_label)
named.sort_custom(by_label)
out.append_array(named)
return out
func _refresh_members() -> void:
var list := collection_members(table, main.data, main.persistent_vars)
var key := var_to_str(list) + str(_plain)
if key == _members_cache:
return
_members_cache = key
for c in _members_box.get_children():
_members_box.remove_child(c)
c.queue_free()
if list.is_empty():
var none := Style.make_label("No members yet", Style.body_italic(true), 14, Style.MUTED)
none.mouse_filter = MOUSE_FILTER_IGNORE
_members_box.add_child(none)
return
for m: Dictionary in list:
var h := _hbox(8)
h.custom_minimum_size = Vector2(0, 28)
h.set_meta("member", str(m["name"]))
var nl := Style.make_label(str(m["label"]) if _plain else str(m["name"]), Style.body(true), 15, Style.INK)
nl.size_flags_horizontal = SIZE_EXPAND_FILL
nl.size_flags_vertical = SIZE_SHRINK_CENTER
nl.mouse_filter = MOUSE_FILTER_IGNORE
h.add_child(nl)
var val: Variant = m["value"]
var vl := Style.make_label("—" if val == null else Expr.format_value(val), Style.display(true), 17, Style.INK if val != null else Style.MUTED)
vl.size_flags_vertical = SIZE_SHRINK_CENTER
vl.mouse_filter = MOUSE_FILTER_IGNORE
h.add_child(vl)
_members_box.add_child(h)
## Re-renders the live parts (a variable's value, a sheet, a choice's ## Re-renders the live parts (a variable's value, a sheet, a choice's
## question) from the current variables. Only touches labels whose text ## question) from the current variables. Only touches labels whose text
## changed. Main calls it after rolls and edits, never per frame. ## changed. Main calls it after rolls and edits, never per frame.
func refresh_live() -> void: func refresh_live() -> void:
if is_instance_valid(_members_box):
_refresh_members()
if is_instance_valid(_var_value): if is_instance_valid(_var_value):
var d := Roller.variable_display(main.data, main.persistent_vars, table) var d := Roller.variable_display(main.data, main.persistent_vars, table)
var shown := str(d["text"]) if str(d["text"]) != "" else "—" var shown := str(d["text"]) if str(d["text"]) != "" else "—"
@ -1360,6 +1177,33 @@ func _weight_edit(e: TableEntry) -> LineEdit:
return edit return edit
## A multi-line details editor (BBCode), shown under a row or the header.
func _details_editor(initial: String, placeholder: String, left: float, on_change: Callable) -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", int(left))
wrap.add_theme_constant_override("margin_right", 12)
wrap.add_theme_constant_override("margin_top", 2)
wrap.add_theme_constant_override("margin_bottom", 6)
var te := TextEdit.new()
te.text = initial
te.placeholder_text = placeholder
te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
te.custom_minimum_size = Vector2(0, 66)
te.scroll_fit_content_height = true
te.add_theme_font_override("font", Style.body(true))
te.add_theme_font_size_override("font_size", 13)
te.add_theme_color_override("font_color", Style.INK)
te.add_theme_color_override("font_placeholder_color", Style.MUTED)
te.add_theme_color_override("caret_color", Style.INK)
te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
te.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.RULE))
te.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.COPPER))
te.text_changed.connect(func() -> void: on_change.call(te.text))
wrap.add_child(te)
return wrap
func _range_edit(e: TableEntry, is_lo: bool) -> LineEdit: func _range_edit(e: TableEntry, is_lo: bool) -> LineEdit:
var edit := LineEdit.new() var edit := LineEdit.new()
edit.text = str(e.range_lo if is_lo else e.range_hi) edit.text = str(e.range_lo if is_lo else e.range_hi)
@ -1473,6 +1317,15 @@ func _make_footer(ranged: bool) -> Control:
addc.tooltip_text = "Add a case before Otherwise" addc.tooltip_text = "Add a case before Otherwise"
addc.pressed.connect(add_case) addc.pressed.connect(add_case)
h.add_child(addc) h.add_child(addc)
var det := _footer_button("Details", Style.INK)
det.tooltip_text = "Details shown when hovering the table's name"
if table.details.strip_edges() != "":
det.add_theme_color_override("font_color", Style.COPPER)
det.pressed.connect(func() -> void:
_table_details_open = not _table_details_open
rebuild()
)
h.add_child(det)
var spacer := Control.new() var spacer := Control.new()
spacer.size_flags_horizontal = SIZE_EXPAND_FILL spacer.size_flags_horizontal = SIZE_EXPAND_FILL
spacer.mouse_filter = MOUSE_FILTER_IGNORE spacer.mouse_filter = MOUSE_FILTER_IGNORE
@ -1510,8 +1363,7 @@ func _skin_scrollbar(bar: VScrollBar) -> void:
func _set_row_state(eid: String, state: RowState) -> void: func _set_row_state(eid: String, state: RowState) -> void:
if not rows.has(eid): if not rows.has(eid):
return return
var k := int(state) + (3 if eid == _selected_eid else 0) (rows[eid] as PanelContainer).add_theme_stylebox_override("panel", _row_styles[state])
(rows[eid] as PanelContainer).add_theme_stylebox_override("panel", _row_styles[k])
var parts: Dictionary = _row_parts[eid] var parts: Dictionary = _row_parts[eid]
var num: Label = parts["num"] var num: Label = parts["num"]
if num: if num:

View file

@ -6,9 +6,6 @@ extends RefCounted
## entries that lead further. Used by the choice pop-up's preview panel; the ## entries that lead further. Used by the choice pop-up's preview panel; the
## board's hover pop-ups can use it too. ## board's hover pop-ups can use it too.
## ##
## Rules (conditions, effects, option sources, loop rules, a check's rule)
## read in plain words unless opts "plain" is false (docs/PLAIN.md §6).
##
## Usage: TablePreview.build(board, table_id, {"count": "2"}) -> Control. ## Usage: TablePreview.build(board, table_id, {"count": "2"}) -> Control.
## Nothing in it takes the mouse, so it never gets in the way of what is ## Nothing in it takes the mouse, so it never gets in the way of what is
## underneath. ## underneath.
@ -20,10 +17,8 @@ const NEXT_HINT := "→ Next table"
## `opts`: count (String, e.g. "2" or "@terms": shown as "×2" when not "1"), ## `opts`: count (String, e.g. "2" or "@terms": shown as "×2" when not "1"),
## max_rows (int), width (float, minimum width of the block), ## max_rows (int), width (float, minimum width of the block),
## heading (String shown in place of the kind line, optional), plain (bool, ## heading (String shown in place of the kind line, optional).
## default RulesView.plain(null): plain words unless the text view is on).
static func build(board: TowerBoard, table_id: String, opts: Dictionary = {}) -> Control: static func build(board: TowerBoard, table_id: String, opts: Dictionary = {}) -> Control:
var plain := bool(opts.get("plain", RulesView.plain(null)))
var box := VBoxContainer.new() var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 4) box.add_theme_constant_override("separation", 4)
box.mouse_filter = Control.MOUSE_FILTER_IGNORE box.mouse_filter = Control.MOUSE_FILTER_IGNORE
@ -44,7 +39,7 @@ static func build(board: TowerBoard, table_id: String, opts: Dictionary = {}) ->
head.add_child(name) head.add_child(name)
var count := str(opts.get("count", "1")).strip_edges() var count := str(opts.get("count", "1")).strip_edges()
if count != "" and count != "1": if count != "" and count != "1":
head.add_child(_label("×" + (RulesView.cut(Describe.dice(count, board), 18) if plain else count), 15, Style.COPPER, true)) head.add_child(_label("×" + count, 15, Style.COPPER, true))
box.add_child(head) box.add_child(head)
box.add_child(_label(str(opts["heading"]) if opts.has("heading") else kind_line(t), 12, Style.MUTED, false)) box.add_child(_label(str(opts["heading"]) if opts.has("heading") else kind_line(t), 12, Style.MUTED, false))
@ -54,7 +49,7 @@ static func build(board: TowerBoard, table_id: String, opts: Dictionary = {}) ->
d.mouse_filter = Control.MOUSE_FILTER_IGNORE d.mouse_filter = Control.MOUSE_FILTER_IGNORE
box.add_child(d) box.add_child(d)
var extra := summary_line(t, board, plain) var extra := summary_line(t)
if extra != "": if extra != "":
box.add_child(_label(extra, 13, Style.INK, false, true)) box.add_child(_label(extra, 13, Style.INK, false, true))
@ -74,7 +69,7 @@ static func build(board: TowerBoard, table_id: String, opts: Dictionary = {}) ->
for i in t.entries.size(): for i in t.entries.size():
if shown >= cap: if shown >= cap:
break break
list.add_child(_row(t, t.entries[i], i, board, plain)) list.add_child(_row(t, t.entries[i], i))
shown += 1 shown += 1
if list.get_child_count() > 0: if list.get_child_count() > 0:
box.add_child(list) box.add_child(list)
@ -91,24 +86,17 @@ static func kind_line(t: RollTable) -> String:
RollTable.KIND_LOOP: RollTable.KIND_LOOP:
return "Loop card" return "Loop card"
RollTable.KIND_VARIABLE: RollTable.KIND_VARIABLE:
return "Collection card" if t.is_collection() else "Variable card" return "Variable card"
RollTable.KIND_SHEET: RollTable.KIND_SHEET:
return "Sheet card" return "Sheet card"
RollTable.KIND_ROUTER: RollTable.KIND_ROUTER:
return "Router · if / else if / otherwise" return "Router · if / else if / otherwise"
RollTable.KIND_CHECK:
return "Check card · " + t.check_dice.strip_edges()
var s := "Roll table · " + t.dice_label() var s := "Roll table · " + t.dice_label()
return s + " · deck" if t.card_mode else s return s + " · deck" if t.card_mode else s
## The kind-specific line: a choice card's question, a loop's rule, ... With ## The kind-specific line: a choice card's question, a loop's rule, ...
## `plain`, rules read in plain words (labelled from `board`). static func summary_line(t: RollTable) -> String:
static func summary_line(t: RollTable, board: TowerBoard = null, plain: bool = false) -> String:
if plain:
var s := _plain_summary(t, board)
if s != "":
return s
match t.kind: match t.kind:
RollTable.KIND_CHOICE: RollTable.KIND_CHOICE:
var q := Formatter.strip_tags(t.prompt).strip_edges() var q := Formatter.strip_tags(t.prompt).strip_edges()
@ -136,40 +124,7 @@ static func summary_line(t: RollTable, board: TowerBoard = null, plain: bool = f
return "" return ""
static func _plain_summary(t: RollTable, board: TowerBoard) -> String: static func _row(t: RollTable, e: TableEntry, index: int) -> Control:
match t.kind:
RollTable.KIND_CHOICE:
var q := Formatter.strip_tags(t.prompt).strip_edges()
var ask := "Asks: " + q if q != "" else "Asks the player"
match t.choice:
"number":
return "%s (a whole number from %s to %s)" % [ask, Describe.dice(t.min_expr, board), Describe.dice(t.max_expr, board)]
"text":
return ask + " (free text)"
if t.is_dynamic():
return "%s\n%s" % [ask, RulesView.options_line(t, board, true)]
return ask
RollTable.KIND_LOOP:
return _cap(RulesView.loop_rule(t, board, true))
RollTable.KIND_VARIABLE:
if t.is_collection():
return "Holds your %s" % Formatter.strip_tags(t.name).strip_edges()
return "Holds %s (%s), kept between rolls" % [Describe.label("@" + t.var_name, board), t.var_type]
RollTable.KIND_CHECK:
return Describe.check(t, board)
RollTable.KIND_ROLL:
if t.is_expr_dice():
return "Roll " + Describe.dice(t.dice, board)
return ""
static func _cap(s: String) -> String:
if s.begins_with("×"):
return "Repeats " + s
return s.substr(0, 1).to_upper() + s.substr(1)
static func _row(t: RollTable, e: TableEntry, index: int, board: TowerBoard = null, plain: bool = false) -> Control:
var row := HBoxContainer.new() var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 8) row.add_theme_constant_override("separation", 8)
row.mouse_filter = Control.MOUSE_FILTER_IGNORE row.mouse_filter = Control.MOUSE_FILTER_IGNORE
@ -182,29 +137,22 @@ static func _row(t: RollTable, e: TableEntry, index: int, board: TowerBoard = nu
col.size_flags_horizontal = Control.SIZE_EXPAND_FILL col.size_flags_horizontal = Control.SIZE_EXPAND_FILL
col.mouse_filter = Control.MOUSE_FILTER_IGNORE col.mouse_filter = Control.MOUSE_FILTER_IGNORE
if t.kind == RollTable.KIND_ROUTER: if t.kind == RollTable.KIND_ROUTER:
var cond := _label(RulesView.case_label(e, board, plain), 12, Style.COPPER_DARK, true, true) var cond := _label(TableCard.case_label(e), 12, Style.COPPER_DARK, true, true)
cond.max_lines_visible = 2 cond.max_lines_visible = 2
cond.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS cond.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
col.add_child(cond) col.add_child(cond)
if t.kind == RollTable.KIND_CHOICE and t.choice == "pick" and e.show_if.strip_edges() != "": if t.kind == RollTable.KIND_CHOICE and t.choice == "pick" and e.show_if.strip_edges() != "":
var si := _label(RulesView.show_if_line(e, board, plain), 12, Style.COPPER_DARK, true, true) var si := _label("only if " + e.show_if.strip_edges(), 12, Style.COPPER_DARK, true, true)
si.max_lines_visible = 2 si.max_lines_visible = 2
si.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS si.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
col.add_child(si) col.add_child(si)
var tx := Formatter.strip_tags(e.text).strip_edges() var tx := Formatter.strip_tags(e.text).strip_edges()
if t.is_dynamic() and index == 0 and (tx == "" or tx == Roller.CHOSEN): if t.is_dynamic() and index == 0 and (tx == "" or tx == Roller.CHOSEN):
tx = "The picked option" tx = "The picked option"
if t.kind == RollTable.KIND_CHECK and (tx == "" or tx == TableCard.check_outlet_name(index)):
tx = TableCard.check_outlet_name(index)
var text := _label(tx if tx != "" else "(empty)", 13, Style.INK, false, true) var text := _label(tx if tx != "" else "(empty)", 13, Style.INK, false, true)
text.max_lines_visible = 2 text.max_lines_visible = 2
text.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS text.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
col.add_child(text) col.add_child(text)
if e.effects.strip_edges() != "":
var fx := _label(RulesView.effects_line(e.effects, board, t, plain), 11, Style.COPPER_DARK, true, true)
fx.max_lines_visible = 1
fx.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
col.add_child(fx)
if not e.pipes.is_empty(): if not e.pipes.is_empty():
col.add_child(_label(NEXT_HINT, 11, Style.COPPER, false)) col.add_child(_label(NEXT_HINT, 11, Style.COPPER, false))
row.add_child(col) row.add_child(col)
@ -231,9 +179,6 @@ static func row_label(t: RollTable, e: TableEntry, index: int) -> String:
return "Each" if index == 0 else "After" return "Each" if index == 0 else "After"
RollTable.KIND_ROUTER: RollTable.KIND_ROUTER:
return str(index + 1) return str(index + 1)
RollTable.KIND_CHECK:
var outs := RulesView.check_outlets(t)
return outs[index] if index < 2 else str(index + 1)
return t.num_label(e, index) return t.num_label(e, index)

View file

@ -370,7 +370,7 @@ func _build_kind() -> void:
_var_name.text_changed.connect(func(_t: String) -> void: _refresh()) _var_name.text_changed.connect(func(_t: String) -> void: _refresh())
box.add_child(field("Variable name (used as @name)", _var_name)) box.add_child(field("Variable name (used as @name)", _var_name))
box.add_child(section("Type")) box.add_child(section("Type"))
box.add_child(segmented(["Number", "Text", "List", "Collection"], RollTable.VAR_TYPES.find(_var_type), func(i: int) -> void: box.add_child(segmented(["Number", "Text", "List"], RollTable.VAR_TYPES.find(_var_type), func(i: int) -> void:
_var_type = RollTable.VAR_TYPES[i] _var_type = RollTable.VAR_TYPES[i]
_refresh() _refresh()
)) ))

View file

@ -1,317 +0,0 @@
class_name ValuePicker
extends Button
## A dropdown of the values a board uses (Builder.known_values), with search,
## grouped as variables, collections, other values and roll values. Each item
## shows its label and kind. "+ New value…" asks for a name and adds it,
## making a variable card when "Show on the board" is ticked.
## Used by the inspector's effect, condition, modifier and options builders.
signal value_chosen(name: String)
const GROUPS := ["", "Variables", "Collections", "Other values", "Roll values"]
const KIND_WORDS := {"number": "number", "text": "text", "list": "list", "collection": "collection"}
var main: Main
## The chosen value's name ("@luck", "@skill_*", "tier"), or "".
var value := ""
## Kinds offered ([] for all): "number", "text", "list", "collection".
var kinds: Array = []
## Extra items listed first: Array of {name, label, kind?}.
var extras: Array = []
## Collection patterns (@skill_*) are only offered when true.
var allow_patterns := false
var allow_new := true
var placeholder := "choose a value"
var _popup: PopupPanel
var _search: LineEdit
var _list: VBoxContainer
var _scroll: ScrollContainer
var _new_button: Button
## Names currently listed (after the search), in order.
var _shown: Array[String] = []
func _init(p_main: Main = null, p_value: String = "") -> void:
main = p_main
value = p_value
var n := Style.bordered(Style.box(InspectorKit.VAR_BG, 6, [8, 3, 8, 3]), 1, InspectorKit.VAR_BORDER)
var h := Style.bordered(Style.box(InspectorKit.VAR_BG.darkened(0.04), 6, [8, 3, 8, 3]), 1, Style.COPPER)
Style.skin_button(self, n, h, h, Style.INK)
add_theme_font_override("font", Style.body_bold())
add_theme_font_size_override("font_size", 15)
add_theme_color_override("font_focus_color", Style.INK)
size_flags_vertical = Control.SIZE_SHRINK_CENTER
pressed.connect(open_menu)
_refresh_text()
func set_value(n: String) -> void:
value = n
_refresh_text()
func _refresh_text() -> void:
if value == "":
text = placeholder + " ▾"
add_theme_color_override("font_color", Style.MUTED)
else:
text = label_of(value) + " ▾"
add_theme_color_override("font_color", Style.INK)
tooltip_text = value if value != "" else "Pick a value"
custom_minimum_size = Vector2(0, 0)
func label_of(n: String) -> String:
for x: Dictionary in extras:
if str(x["name"]) == n:
return str(x["label"])
return Describe.label(n, main.data if main else null)
## Every value offered, before the search: Array of {name, label, kind, group}.
func items() -> Array:
var out: Array = []
var seen := {}
for x: Dictionary in extras:
out.append({"name": x["name"], "label": x["label"], "kind": str(x.get("kind", "")), "group": ""})
seen[x["name"]] = true
var board: TowerBoard = main.data if main else null
var known: Array = Builder.known_values(board) if board else []
# Members of a collection that only exist as saved values (not yet named
# in any rule) are offered too.
if main:
var stems: Array = []
for t in board.tables:
if t.is_collection() and t.var_name != "":
stems.append(t)
var names: Array = main.persistent_vars.keys()
names.sort()
for n: String in names:
for t: RollTable in stems:
if n.begins_with(t.var_name + "_") and n.length() > t.var_name.length() + 1:
known.append({"name": "@" + n, "label": Describe.label("@" + n, board), "kind": "number",
"source": "member", "collection": "@%s_*" % t.var_name})
break
for k: Dictionary in known:
var n := str(k["name"])
if seen.has(n):
continue
var kind := str(k["kind"])
if n.ends_with("*") and not allow_patterns:
continue
if not kinds.is_empty() and not kinds.has(kind):
continue
seen[n] = true
var g := "Other values"
match str(k["source"]):
"variable":
g = "Variables"
"collection":
g = "Collections"
"chain":
g = "Roll values"
"input":
g = "Roll values"
if k.has("collection"):
g = "Collections"
out.append({"name": n, "label": str(k["label"]), "kind": kind, "group": g})
var ordered: Array = []
for g: String in GROUPS:
for it: Dictionary in out:
if it["group"] == g:
ordered.append(it)
return ordered
## Items matching `query` (label or name, any case).
func filtered(query: String) -> Array:
var q := query.strip_edges().to_lower()
var out: Array = []
for it: Dictionary in items():
if q == "" or str(it["label"]).to_lower().contains(q) or str(it["name"]).to_lower().contains(q):
out.append(it)
return out
## Names listed in the open menu.
func shown_names() -> Array[String]:
return _shown
func open_menu() -> void:
if _popup == null:
_build_popup()
_search.text = ""
_fill("")
var r := get_global_rect()
_popup.reset_size()
var view := get_viewport_rect().size
var p := Vector2(r.position.x, r.end.y + 4)
var sz := Vector2(260, 0)
p.x = clampf(p.x, 8.0, view.x - sz.x - 12.0)
if p.y + 340.0 > view.y:
p.y = maxf(8.0, r.position.y - 344.0)
_popup.popup(Rect2i(Vector2i(p), Vector2i(260, 0)))
_search.grab_focus.call_deferred()
func is_menu_open() -> bool:
return _popup != null and _popup.visible
func close_menu() -> void:
if _popup:
_popup.hide()
func _build_popup() -> void:
_popup = PopupPanel.new()
_popup.theme = Style.card_theme()
var sb := Style.bordered(Style.box(Style.CARD, 8, [6, 6, 6, 6]), 1, Style.DASH)
sb.shadow_color = Color(0, 0, 0, 0.3)
sb.shadow_size = 12
sb.shadow_offset = Vector2(0, 5)
_popup.add_theme_stylebox_override("panel", sb)
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", 4)
v.custom_minimum_size = Vector2(248, 0)
_popup.add_child(v)
_search = InspectorKit.line("", "Search values")
_search.text_changed.connect(_fill)
_search.text_submitted.connect(func(s: String) -> void:
if not _shown.is_empty():
choose(_shown[0])
elif allow_new and s.strip_edges() != "":
_ask_new(s.strip_edges())
)
v.add_child(_search)
_scroll = ScrollContainer.new()
_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
_scroll.custom_minimum_size = Vector2(0, 40)
v.add_child(_scroll)
_list = VBoxContainer.new()
_list.add_theme_constant_override("separation", 0)
_list.size_flags_horizontal = Control.SIZE_EXPAND_FILL
_scroll.add_child(_list)
_new_button = _row_button("+ New value…", "", true)
_new_button.pressed.connect(func() -> void: _ask_new(_search.text.strip_edges()))
v.add_child(_new_button)
add_child(_popup)
func _fill(query: String) -> void:
for c in _list.get_children():
_list.remove_child(c)
c.queue_free()
_shown.clear()
var last_group := "-"
for it: Dictionary in filtered(query):
if it["group"] != last_group:
last_group = str(it["group"])
if last_group != "":
var h := InspectorKit.flabel(last_group)
h.add_theme_constant_override("line_spacing", 0)
var m := MarginContainer.new()
m.add_theme_constant_override("margin_left", 6)
m.add_theme_constant_override("margin_top", 6)
m.add_child(h)
_list.add_child(m)
_list.add_child(_item_button(it))
_shown.append(str(it["name"]))
var q := query.strip_edges()
_new_button.visible = allow_new
_new_button.text = "+ New value…" if q == "" else "+ New value “%s”…" % q
if _shown.is_empty():
_list.add_child(InspectorKit.note("Nothing matches.", Style.MUTED, 14))
_scroll.custom_minimum_size.y = clampf(_list.get_combined_minimum_size().y, 40.0, 300.0)
if _popup.visible:
_popup.reset_size()
func _item_button(it: Dictionary) -> Button:
var kind := str(it.get("kind", ""))
var b := _row_button(str(it["label"]), KIND_WORDS.get(kind, kind), false)
if str(it["name"]) == value:
b.add_theme_stylebox_override("normal", Style.box(Style.LIT, 5, [8, 4, 8, 4]))
b.tooltip_text = str(it["name"])
var n := str(it["name"])
b.pressed.connect(func() -> void: choose(n))
return b
func _row_button(label: String, right: String, accent: bool) -> Button:
var b := Button.new()
b.alignment = HORIZONTAL_ALIGNMENT_LEFT
b.text = label
b.clip_text = true
var n := Style.box(Color(0, 0, 0, 0), 5, [8, 4, 8, 4])
var h := Style.box(Style.HOVER_ROW, 5, [8, 4, 8, 4])
Style.skin_button(b, n, h, h, Style.COPPER_DARK if accent else Style.INK)
b.add_theme_font_override("font", Style.body_bold() if accent else Style.body())
b.add_theme_font_size_override("font_size", 15)
b.focus_mode = Control.FOCUS_NONE
if right != "":
var k := Style.make_label(right, Style.body(), 12, Style.MUTED)
k.set_anchors_and_offsets_preset(Control.PRESET_CENTER_RIGHT)
k.offset_left = -80
k.offset_right = -8
k.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
k.mouse_filter = Control.MOUSE_FILTER_IGNORE
b.add_child(k)
return b
## Picks `n` (as if clicked).
func choose(n: String) -> void:
close_menu()
set_value(n)
value_chosen.emit(n)
func _ask_new(initial: String) -> void:
close_menu()
var d := ModalCard.new("New value", 420.0)
var le := LineEdit.new()
le.text = initial
le.placeholder_text = "e.g. Luck"
ModalCard.style_line_edit(le)
d.body.add_child(ModalCard.field("Name", le))
var cb := InspectorKit.check_box("Show on the board", true)
cb.tooltip_text = "Adds a variable card, so the value has a label and a starting value, and shows while you play"
d.body.add_child(cb)
var hint := ModalCard.note("")
d.body.add_child(hint)
var upd := func(_s: String = "") -> void:
var nm := JsonIO.slug(le.text.strip_edges(), "")
hint.text = "In rules: @%s" % nm if nm != "" else "Give it a name."
le.text_changed.connect(upd)
upd.call()
var accept := func() -> void:
if le.text.strip_edges() == "":
return
d.close()
create_value(le.text.strip_edges(), cb.button_pressed)
le.text_submitted.connect(func(_t: String) -> void: accept.call())
d.add_button("Cancel", "plain", d.close)
d.add_button("Add", "primary", accept)
d.ready.connect(func() -> void:
le.grab_focus()
le.select_all()
)
if main:
main.add_child(d)
## Adds a value named `label_text` ("Luck" -> @luck) and picks it. With
## `on_board`, a variable card declares it (Main.add_variable_card).
## Returns the value's name.
func create_value(label_text: String, on_board: bool) -> String:
var nm := JsonIO.slug(label_text.strip_edges(), "value")
if on_board and main:
var t := main.add_variable_card(label_text.strip_edges(), nm)
nm = t.var_name
var full := "@" + nm
set_value(full)
value_chosen.emit(full)
return full

View file

@ -1 +0,0 @@
uid://2e7nrxufi5y

View file

@ -1,197 +0,0 @@
class_name WhyPopover
extends PanelContainer
## "Why this?" (docs/PLAIN.md §4.4, §6): a card-styled pop-over listing why a
## step of the last roll came out the way it did, one Describe.why() sentence
## per trace fact.
##
## A step's own facts (its inputs, roll or check, router cases, effects) come
## with the facts its parent step recorded about the pipe that led here: the
## "only if" / "otherwise" choices aimed at this card, and the parent's
## effects on the values those conditions read. Steps from old history
## records have no facts, so they get no button (has_why() is false).
##
## Opened by ResultTray's "Why this?" buttons; it sits above the button, closes
## on Esc, on a click outside it, or on the button again. The same lines show
## in hover pop-ups (DetailsPopup.why_bbcode()).
const WIDTH := 460.0
var _title: Label
var _list: RichTextLabel
## The control that opened it (a second press on it closes).
var opener: Control
## Lines shown, for tests.
var lines: PackedStringArray = []
func _init() -> void:
top_level = true
z_index = 90
mouse_filter = MOUSE_FILTER_STOP
var sb := Style.box(Style.CARD, 9, [14, 10, 14, 12])
Style.bordered(sb, 2, Style.BRASS)
sb.shadow_color = Color(0, 0, 0, 0.4)
sb.shadow_size = 16
sb.shadow_offset = Vector2(0, 6)
add_theme_stylebox_override("panel", sb)
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", 6)
v.mouse_filter = MOUSE_FILTER_IGNORE
add_child(v)
v.minimum_size_changed.connect(func() -> void: _place.call_deferred())
_title = Style.make_label("", Style.caps(), 12, Style.MUTED)
_title.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
_title.custom_minimum_size = Vector2(WIDTH, 0)
_title.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(_title)
_list = RichText.label("", 15, Style.INK, false)
_list.custom_minimum_size = Vector2(WIDTH, 0)
_list.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(_list)
hide()
## Shows the reasons for steps[index] above (or below) `at` (a global rect),
## or above `anchor` while it's on screen (it follows it as it moves).
func open(steps: Array, index: int, board: TowerBoard, plain: bool, at: Rect2, from: Control = null, anchor: Control = null) -> void:
opener = from
_anchor = anchor
lines = why_lines(steps, index, board, plain)
_title.text = title_for(steps[index]).to_upper()
_list.text = bbcode_list(lines)
_at = at
show()
_place()
# The list's height is known only after layout, so place it again then.
_place.call_deferred()
var _at := Rect2()
var _anchor: Control
func _place() -> void:
if not visible:
return
reset_size()
if _anchor != null and is_instance_valid(_anchor) and _anchor.is_visible_in_tree():
_at = _anchor.get_global_rect()
var view := get_viewport_rect().size
var p := Vector2(_at.position.x, _at.position.y - size.y - 8.0)
if p.y < 8.0:
p.y = _at.end.y + 8.0
p.x = clampf(p.x, 8.0, maxf(8.0, view.x - size.x - 8.0))
global_position = p
## Keeps it placed while its text settles (a RichTextLabel learns its height
## a frame or two after it's filled).
func _process(_delta: float) -> void:
if visible:
_place()
func close() -> void:
opener = null
_anchor = null
hide()
func _input(ev: InputEvent) -> void:
if not visible:
return
var k := ev as InputEventKey
if k and k.pressed and k.keycode == KEY_ESCAPE:
close()
get_viewport().set_input_as_handled()
return
var mb := ev as InputEventMouseButton
if mb and mb.pressed and not get_global_rect().has_point(mb.global_position):
if opener != null and is_instance_valid(opener) and opener.get_global_rect().has_point(mb.global_position):
return # the button toggles it itself
close()
# ---------- Content (static, testable) ----------
## "Why Loot · A curio"
static func title_for(step: Dictionary) -> String:
var t := Formatter.strip_tags(str(step.get("table", ""))).strip_edges()
var s := Formatter.strip_tags(str(step.get("text", ""))).strip_edges().replace("\n", " ")
if s.length() > 48:
s = s.substr(0, 47).strip_edges() + "…"
return "Why %s · %s" % [t, s] if s != "" else "Why " + t
## True when steps[index] has something to explain.
static func has_why(steps: Array, index: int) -> bool:
return not facts_for(steps, index).is_empty()
## The facts that explain steps[index]: [[fact, prefix], ...]. The parent's
## facts come first (pipe choices aimed at this step's card, and its effects
## on the values they read, prefixed with the parent's text), then the step's
## own.
static func facts_for(steps: Array, index: int) -> Array:
var out: Array = []
if index < 0 or index >= steps.size():
return out
var step: Dictionary = steps[index]
var tid := str(step.get("table_id", ""))
var d := int(step.get("depth", 0))
var parent: Dictionary = {}
if d > 0:
for k in range(index - 1, -1, -1):
var s: Dictionary = steps[k]
if int(s.get("depth", 0)) == d - 1:
parent = s
break
if not parent.is_empty() and parent.get("why") is Array:
var pipe_facts: Array = []
var read := {}
for f: Variant in parent["why"]:
if not (f is Dictionary):
continue
var ty := str(f.get("type", ""))
if (ty == "when" or ty == "otherwise") and str(f.get("to", "")) == tid:
pipe_facts.append(f)
if f.get("values") is Dictionary:
for nm: Variant in f["values"]:
read[str(nm)] = true
if not pipe_facts.is_empty():
var who := Formatter.strip_tags(str(parent.get("text", ""))).strip_edges().replace("\n", " ")
if who.length() > 40:
who = who.substr(0, 39).strip_edges() + "…"
for f: Variant in parent["why"]:
if f is Dictionary and str(f.get("type", "")) == "effect" and read.has(str(f.get("var", ""))):
out.append([f, who])
for f: Variant in pipe_facts:
out.append([f, ""])
if step.get("why") is Array:
for f: Variant in step["why"]:
if f is Dictionary:
out.append([f, ""])
return out
## One sentence per fact, ending in a full stop.
static func why_lines(steps: Array, index: int, board: TowerBoard, plain: bool) -> PackedStringArray:
var out := PackedStringArray()
for pair: Array in facts_for(steps, index):
var s := Describe.why(pair[0], board, plain).strip_edges()
if s == "":
continue
if str(pair[1]) != "":
s = "%s: %s" % [pair[1], s]
if plain and not (s.ends_with(".") or s.ends_with("…")):
s += "."
out.append(s)
return out
## The lines as a BBCode bullet list (text escaped).
static func bbcode_list(ls: PackedStringArray) -> String:
var parts := PackedStringArray()
for l in ls:
parts.append("• " + RichText.plain(l))
return "\n".join(parts)

View file

@ -1 +0,0 @@
uid://d178csgl7nfsc