Dynamic pick options, show_if and indirect @[expr] names

Pick choice cards can take their options from variables (options_from:
@prefix_* or a @list, filtered by options_where with option, option_label
and option_value bound). A Chosen entry runs for whichever dynamic option
is picked; fixed entries stay as extras, listed first. Random weighs each
dynamic option as the Chosen entry and fixed ones by weight. Any pick
option can have show_if, which hides it from the pop-up and from Random;
with nothing offered the node stops with "No options available".

@[expr] reads or writes the variable named by expr in expressions,
effects (including reset) and text ({@[expr]}); bad computed names are
effect errors. JSON round trip, lint_options in lint_pipes, choice
pop-up value badges and previews, card and settings UI, docs, demo board
(Spend a find) and tests/test_options.gd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
RobinFiredrake 2026-11-08 18:55:38 -06:00
parent 0367d36647
commit 86d1b214c3
17 changed files with 1557 additions and 31 deletions

View file

@ -41,6 +41,12 @@ godot --path .
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 (+ Table ▾) lists cases
("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
(`@skill_*` gives one option per set skill, `@contacts` one per list item), filtered with
**Only where** (`option_value >= 1`); its **Chosen** row runs for whichever is picked, with
`option` holding the name, so `@[option] += 1` raises it. Fixed options can stay alongside,
and any option can have a **Show only if** condition (the **if** toggle on its row) that
hides it from the pop-up and from Random.
- **Collections:** the switcher in the top bar holds separate sets of tables. Build mode's
**Board ▾** menu imports and exports TableTower JSON, JSON Canvas, Mermaid, DOT and GraphML.
- **Ranged tables** (like *Wilderness Travel*) roll a d100 where each range's size sets its

View file

@ -9,6 +9,8 @@ extends RefCounted
## @age *= 2 multiply (/= divides, rounding down)
## reset @name back to the variable card's starting value, or deleted
## reset @skill_* every variable with that prefix
## @[expr] += 1 the variable named by expr (indirect), e.g.
## @[option] += 1, reset @["skill_" + option]
##
## A target without "@" is a chain variable. Unset counts as 0 (or "" when the
## value added is text). run() never stops on a bad statement: it logs an error
@ -51,6 +53,9 @@ static func split(text: String) -> Array[String]:
static func parse_statement(src: String) -> Dictionary:
_compile()
var s := src.strip_edges()
var ind := _parse_indirect(s)
if not ind.is_empty():
return ind
var m := _reset_re.search(s)
if m != null:
var target := "@" + m.get_string(1).to_lower() + m.get_string(2)
@ -69,6 +74,55 @@ static func parse_statement(src: String) -> Dictionary:
return {"src": s, "op": m.get_string(2), "target": t, "expr": expr}
## An indirect statement ("@[expr] op value" or "reset @[expr]"), parsed into
## the same shape with "target_expr" (the expression naming the variable) and
## target "@[expr]"; {} when `s` isn't one.
static func _parse_indirect(s: String) -> Dictionary:
var at := -1
var is_reset := false
if s.begins_with("@["):
at = 1
elif s.to_lower().begins_with("reset") and s.substr(5).strip_edges().begins_with("@["):
is_reset = true
at = s.find("@[") + 1
if at < 0:
return {}
var close := Expr.bracket_end(s, at)
if close < 0:
return {"src": s, "error": "@[ is missing its closing ]"}
var inner := s.substr(at + 1, close - at - 1).strip_edges()
if inner == "":
return {"src": s, "error": "Write an expression inside @[ ], e.g. @[option]"}
var target := s.substr(at - 1, close - at + 2)
var rest := s.substr(close + 1).strip_edges()
if is_reset:
if rest != "":
return {"src": s, "error": "Write reset @[expr]"}
return {"src": s, "op": "reset", "target": target, "target_expr": inner, "expr": ""}
for op: String in ["+=", "-=", "*=", "/=", "="]:
if rest.begins_with(op) and not (op == "=" and rest.begins_with("==")):
var expr := rest.substr(op.length()).strip_edges()
if expr == "":
return {"src": s, "error": "Nothing after %s" % op}
return {"src": s, "op": op, "target": target, "target_expr": inner, "expr": expr}
return {"src": s, "error": "Not a statement; try @[name] = value"}
## The real target of a statement: its "target", or for an indirect one
## "@name" from its expression. {"target", "error"}: the error is set when
## the expression fails or doesn't give a valid name.
static func resolve_target(st: Dictionary, ctx: RollContext) -> Dictionary:
if not st.has("target_expr"):
return {"target": st["target"], "error": ""}
var r := Expr.evaluate(str(st["target_expr"]), ctx)
if r["error"] != "":
return {"target": "", "error": str(r["error"])}
var nm := Expr.indirect_name(r["value"])
if nm["error"] != "":
return {"target": "", "error": str(nm["error"])}
return {"target": "@" + str(nm["name"]), "error": ""}
## Problems in effect text for the Build-mode editor: Array of {index (0-based
## statement number), src, error}. Empty when everything parses.
static func validate(text: String) -> Array[Dictionary]:
@ -77,6 +131,8 @@ static func validate(text: String) -> Array[Dictionary]:
for k in list.size():
var st := parse_statement(list[k])
var err := str(st.get("error", ""))
if err == "" and st.has("target_expr"):
err = Expr.check(st["target_expr"])
if err == "" and st["op"] != "reset":
err = Expr.check(st["expr"])
if err != "":
@ -96,6 +152,12 @@ static func run(text: String, ctx: RollContext, source_id: String = "") -> Array
if st.has("error"):
log.append({"text": "%s: %s" % [src, st["error"]], "error": true})
continue
if st.has("target_expr"):
var rt := resolve_target(st, ctx)
if rt["error"] != "":
log.append({"text": "%s: %s" % [src, rt["error"]], "error": true})
continue
st["target"] = rt["target"]
if st["op"] == "reset":
log.append(_reset(st["target"], ctx))
else:

View file

@ -6,6 +6,8 @@ extends RefCounted
## name a chain variable (answer, i, or anything saved with -> name)
## 2d6 d20 3D D3 dice, rolled fresh every time (a missing count is 1, missing
## sides are 6)
## @[expr] the board variable named by expr (indirect), e.g.
## @[option] or @["skill_" + option]
## a = b a lone "=" means equals
## dm(x) has(list, item) count(prefix), plus Expression's built-ins
## (min max clamp abs floor ceil round ...)
@ -25,6 +27,7 @@ const _KEYWORDS := ["and", "or", "not", "in", "true", "false", "null", "if", "el
## text_side: Array[bool] per input (an unset value reads as ""), error: String}
static var _cache: Dictionary = {}
static var _dice_re: RegEx = null
static var _name_re: RegEx = null
## Evaluates `src` against a roll context. `ctx` may be null (variables then
@ -198,6 +201,45 @@ static func has_item(list: Variant, item: Variant) -> bool:
return false
## The board variable name an indirect @[expr] computed: {"name": String
## (no "@"), "error": String}. Names are lowercase letters, digits and "_"
## (a leading "@" is dropped and capitals are lowered).
static func indirect_name(v: Variant) -> Dictionary:
var s := format_value(v).strip_edges().trim_prefix("@").to_lower()
if s == "":
return {"name": "", "error": "@[…] gave an empty variable name"}
if _name_re == null:
_name_re = RegEx.create_from_string("^[a-z_][a-z0-9_]*$")
if _name_re.search(s) == null:
return {"name": "", "error": "@[…] gave \"%s\", which isn't a variable name (lowercase letters, digits and _)" % format_value(v)}
return {"name": s, "error": ""}
## Index of the "]" that closes the "[" at `open` in `s`, skipping quoted text
## and nested brackets; -1 when there isn't one.
static func bracket_end(s: String, open: int) -> int:
var depth := 0
var quote := ""
var k := open
while k < s.length():
var c := s[k]
if quote != "":
if c == "\\":
k += 1
elif c == quote:
quote = ""
elif c == "\"" or c == "'":
quote = c
elif c == "[":
depth += 1
elif c == "]":
depth -= 1
if depth == 0:
return k
k += 1
return -1
## Rolls NdM with `rng` (a fresh one when null).
static func roll_dice(n: int, sides: int, rng: RandomNumberGenerator) -> int:
if rng == null:
@ -248,6 +290,10 @@ static func _rewrite(src: String) -> Dictionary:
var vars: Array = []
var text_side: Array = []
var slot := {} # "@name" / "name" -> input index
# Open brackets: true for an indirect @[ (closes with ")"), false for a
# plain "[".
var brackets: Array[bool] = []
var n_ind := 0
# Tokens as [kind, text]: kind "str", "var", "op", "other" (for text_side).
var toks: Array = []
var i := 0
@ -267,6 +313,33 @@ static func _rewrite(src: String) -> Dictionary:
toks.append(["str", lit])
i = j + 1
continue
if c == "@" and i + 1 < n and src[i + 1] == "[":
# @[expr]: an indirect variable, read through _iv() (or _ivt() when
# it sits beside text, so unset reads as "").
out += "\u0001%d\u0001" % n_ind
toks.append(["ivo", n_ind])
brackets.append(true)
n_ind += 1
i += 2
continue
if c == "[":
brackets.append(false)
elif c == "]" and not brackets.is_empty():
if brackets.pop_back():
var id := -1
var depth := 0
for t in range(toks.size() - 1, -1, -1):
if toks[t][0] == "ivc":
depth += 1
elif toks[t][0] == "ivo":
if depth == 0:
id = toks[t][1]
break
depth -= 1
out += ")"
toks.append(["ivc", id])
i += 1
continue
if c == "@":
var j := i + 1
while j < n and _is_word(src[j]):
@ -351,6 +424,22 @@ static func _rewrite(src: String) -> Dictionary:
toks.append(["op", c])
out += c
i += 1
if brackets.has(true):
return {"text": "", "inputs": [], "vars": [], "text_side": [], "error": "@[ is missing its closing ]"}
# An indirect @[…] beside a text literal (or `in`) reads as "" when unset.
var beside := func(u: int) -> bool:
return u >= 0 and u < toks.size() and (toks[u][0] == "str" or (toks[u][0] == "op" and toks[u][1] == "in"))
for t in toks.size():
if toks[t][0] != "ivo":
continue
var id: int = toks[t][1]
var close := t
for u in range(t + 1, toks.size()):
if toks[u][0] == "ivc" and toks[u][1] == id:
close = u
break
var text_side_ind: bool = beside.call(t - 1) or beside.call(t - 2) or beside.call(close + 1) or beside.call(close + 2)
out = out.replace("\u0001%d\u0001" % id, "_ivt(" if text_side_ind else "_iv(")
# A variable directly beside a text literal (or `in`) reads as "" when unset.
for t in toks.size():
if toks[t][0] != "var":
@ -404,6 +493,23 @@ class _Base:
func has(list: Variant, item: Variant) -> bool:
return Expr.has_item(list, item)
func _iv(name: Variant) -> Variant:
return _indirect(name, 0)
func _ivt(name: Variant) -> Variant:
return _indirect(name, "")
func _indirect(name: Variant, unset: Variant) -> Variant:
var r := Expr.indirect_name(name)
if r["error"] != "":
if error == "":
error = r["error"]
return unset
if ctx == null:
return unset
var v: Variant = ctx.get_value("@" + str(r["name"]))
return unset if v == null else Expr.to_value(v)
func count(prefix: Variant) -> int:
if ctx == null:
return 0

View file

@ -55,6 +55,15 @@ var choice: String = "pick"
var prompt: String = ""
## Choice cards: variable the answer is saved under ("@name" or a chain name).
var save_as: String = ""
## Pick choices: options from variables (docs/LOGIC.md §2a). "@prefix_*"
## gives one option per set variable with that prefix, "@list" one option per
## item of a list variable. "" for a fixed list. When it's set, entries[0] is
## the Chosen entry (it happens for whichever dynamic option is picked) and
## any other entries are fixed extras.
var options_from: String = ""
## Pick choices with options_from: an expression each candidate must pass,
## with the chain variables option, option_label and option_value bound.
var options_where: String = ""
## Number choices: bounds, as expressions.
var min_expr: String = "0"
var max_expr: String = "99"
@ -123,6 +132,51 @@ static func create(p_kind: String, p_id: String, p_name: String, sub: String = "
return t
## True for a pick choice whose options come from variables (options_from).
func is_dynamic() -> bool:
return kind == KIND_CHOICE and choice == "pick" and options_from.strip_edges() != ""
## Index of the first fixed option on a pick choice: 1 when entries[0] is the
## Chosen entry of a dynamic card, else 0.
func fixed_start() -> int:
return 1 if is_dynamic() else 0
## Parses an options_from pattern: {"kind": "prefix" | "list" | "", "name":
## the prefix or list variable name without "@" and "*", "error": String}.
## "@skill_*" is a prefix, "@contacts" a list variable.
static func parse_options_from(src: String) -> Dictionary:
var s := src.strip_edges()
if s == "":
return {"kind": "", "name": "", "error": ""}
if not s.begins_with("@"):
return {"kind": "", "name": "", "error": "Write @prefix_* (each set variable with that prefix) or @list (each item of a list variable)"}
var prefix := s.ends_with("*")
var name := s.substr(1, s.length() - (2 if prefix else 1)).to_lower()
if name == "":
return {"kind": "", "name": "", "error": "Give a name after @, e.g. @skill_* or @contacts"}
if RegEx.create_from_string("^[a-z_][a-z0-9_]*$").search(name) == null:
return {"kind": "", "name": "", "error": "\"%s\" isn't a variable name (lowercase letters, digits and _)" % s}
return {"kind": "prefix" if prefix else "list", "name": name, "error": ""}
## "each @skill_* that's set, where option_value >= 1" (for previews and cards).
func options_description() -> String:
var p := parse_options_from(options_from)
var s := ""
match str(p["kind"]):
"prefix":
s = "each @%s* that's set" % p["name"]
"list":
s = "each item of @%s" % p["name"]
_:
s = options_from.strip_edges()
if options_where.strip_edges() != "":
s += ", where " + options_where.strip_edges()
return s
## Router cards: index of the first case that is an Otherwise case (empty
## `when`), or -1.
func otherwise_index() -> int:
@ -388,6 +442,10 @@ func to_dict() -> Dictionary:
d["prompt"] = prompt
if save_as != "":
d["save_as"] = save_as
if options_from.strip_edges() != "":
d["options_from"] = options_from.strip_edges()
if options_where.strip_edges() != "":
d["options_where"] = options_where.strip_edges()
if min_expr != "0":
d["min"] = min_expr
if max_expr != "99":
@ -426,6 +484,8 @@ static func from_dict(d: Dictionary) -> RollTable:
t.choice = c if CHOICES.has(c) else "pick"
t.prompt = str(d.get("prompt", ""))
t.save_as = str(d.get("save_as", ""))
t.options_from = str(d.get("options_from", "")).strip_edges() if d.get("options_from") != null else ""
t.options_where = expr_text(d.get("options_where", ""), "").strip_edges()
t.min_expr = expr_text(d.get("min", "0"), "0")
t.max_expr = expr_text(d.get("max", "99"), "99")
var lm := str(d.get("loop", "times"))

View file

@ -17,6 +17,7 @@ extends RefCounted
## effects: Array of {"text": String, "error": true?}, the effect log
## answer: the player's answer on a number/text choice (int or String)
## picked: true when the player picked a pick option; random: true for Random
## option: on a pick node for a dynamic option (options_from), its label
## passes: int, on a loop's header node ("Repeated N times"); its children
## are one node per pass ("pass": i, "value": i) and then the Afterwards
## node ("after": true)
@ -37,6 +38,7 @@ const MAX_DEPTH := RollContext.DEFAULT_MAX_DEPTH
const MAX_ACTIONS := RollContext.DEFAULT_MAX_ACTIONS
const CANCELLED := "Cancelled"
const NO_CASE := "No case matched"
const NO_OPTIONS := "No options available"
enum { OP_ROLL, OP_PIPE, OP_LOOP }
@ -284,6 +286,12 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr
c["inline"] = true
kids.append(c)
node["summary"] = ex["text"]
# The Chosen entry of a dynamic pick reads as the option's label unless
# it has text of its own.
if node.has("option"):
var plain := Formatter.strip_tags(e.text).strip_edges()
if plain == "" or plain == CHOSEN:
node["summary"] = Formatter.escape_literal(str(node["option"]))
if ctx.halted != "":
return
var save := str(f.get("save", ""))
@ -293,7 +301,10 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr
# A picked option is saved under the choice's save_as before the pipe
# snapshot, so its own pipe conditions can read it.
if t.kind == RollTable.KIND_CHOICE and t.save_as != "" and not node.has("answer"):
ctx.save(t.save_as, Formatter.strip_tags(str(node["summary"])).strip_edges(), t.id)
if node.has("option"):
ctx.save(t.save_as, str(node["option"]), t.id)
else:
ctx.save(t.save_as, Formatter.strip_tags(str(node["summary"])).strip_edges(), t.id)
if e.pipes.is_empty():
return
var log: Array = []
@ -468,13 +479,38 @@ static func _do_loop(f: Dictionary, ctx: RollContext, stack: Array) -> void:
## The prompt request for a choice card (docs/LOGIC.md §8):
## {table_id, kind ("pick" | "number" | "text"), title, prompt (BBCode,
## rendered), options: [{index, text, details}], min, max, default}.
## rendered), options: [{index, entry, text, details, weight, ...}], min, max,
## default, log (error lines from show_if and options_where), hidden (how many
## fixed options show_if hid)}.
## A pick's options are its fixed options whose show_if holds (index = entry
## = the entry's index), then, on a dynamic card (options_from), one option
## per candidate variable or list item (index = entries.size() + j, entry =
## 0, the Chosen entry, plus "dynamic": true, "option", "label", "value" and
## "value_text"). The reply is an option's index, or -1 for Random.
static func request_for(t: RollTable, ctx: RollContext) -> Dictionary:
var options: Array = []
var log: Array = []
var hidden := 0
if t.choice == "pick":
for k in t.entries.size():
var ranged := t.is_ranged()
for k in range(t.fixed_start(), t.entries.size()):
var e := t.entries[k]
options.append({"index": k, "text": TextExpander.render(e.text, ctx), "details": e.details})
if not option_shown(e, ctx, log):
hidden += 1
continue
options.append({"index": k, "entry": k, "text": TextExpander.render(e.text, ctx), "details": e.details,
"weight": e.span() if ranged else maxi(0, e.weight)})
if t.is_dynamic() and not t.entries.is_empty() and option_shown(t.entries[0], ctx, log):
var chosen := t.entries[0]
var cands := dynamic_options(t, ctx, log)
for j in cands.size():
var c: Dictionary = cands[j]
var vt := Expr.format_value(c["value"]) if str(c["kind"]) == "prefix" else ""
var label := str(c["label"])
var shown := label if vt == "" else "%s %s" % [label, vt]
options.append({"index": t.entries.size() + j, "entry": 0, "text": Formatter.escape_literal(shown),
"details": chosen.details, "weight": maxi(0, chosen.weight), "dynamic": true,
"option": c["option"], "label": label, "value": c["value"], "value_text": vt})
var lo := Expr.eval_int(t.min_expr, ctx, 0)
var hi := maxi(lo, Expr.eval_int(t.max_expr, ctx, 99))
var def: Variant = -1
@ -483,7 +519,86 @@ static func request_for(t: RollTable, ctx: RollContext) -> Dictionary:
elif t.choice == "text":
def = ""
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}
"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
## error counts as false and adds a line to `log`.
static func option_shown(e: TableEntry, ctx: RollContext, log: Array = []) -> bool:
var w := e.show_if.strip_edges()
if w == "":
return true
var r := Expr.evaluate(w, ctx)
if r["error"] != "":
log.append({"text": "Show only if %s: %s" % [w, r["error"]], "error": true})
return false
return Expr.truthy(r["value"])
## The candidates of a dynamic pick card (options_from, filtered by
## options_where), in order: Array of {kind ("prefix" | "list"), option (the
## variable name without "@", or the list item), label, value}. A prefix
## gives one per set variable, sorted by label ("Pilot"); a list gives one
## per item, in list order (label and value are the item). A filter error
## counts as false and adds one line to `log`.
static func dynamic_options(t: RollTable, ctx: RollContext, log: Array = []) -> Array:
var out: Array = []
var src := RollTable.parse_options_from(t.options_from)
if str(src["error"]) != "":
log.append({"text": "Options from %s: %s" % [t.options_from.strip_edges(), src["error"]], "error": true})
return out
var name := str(src["name"])
var cands: Array = []
match str(src["kind"]):
"prefix":
for v in ctx.list_vars(name):
cands.append({"kind": "prefix", "option": v["name"], "label": v["label"], "value": v["value"]})
"list":
var cur: Variant = ctx.get_value("@" + name)
for item in Expr.list_items(cur if cur != null else ""):
cands.append({"kind": "list", "option": item, "label": item, "value": item})
var where := t.options_where.strip_edges()
if where == "":
return cands
var saved := {}
for k in OPTION_VARS:
if ctx.chain_vars.has(k):
saved[k] = ctx.chain_vars[k]
var failed := false
for c: Dictionary in cands:
_bind_option(ctx, c)
var r := Expr.evaluate(where, ctx)
if r["error"] != "":
if not failed:
failed = true
log.append({"text": "Only where %s: %s" % [where, r["error"]], "error": true})
elif Expr.truthy(r["value"]):
out.append(c)
for k in OPTION_VARS:
if saved.has(k):
ctx.chain_vars[k] = saved[k]
else:
ctx.chain_vars.erase(k)
return out
## How many options a pick card offers right now (show_if and options_from
## included); for the card's live count.
static func available_count(t: RollTable, ctx: RollContext) -> int:
return (request_for(t, ctx)["options"] as Array).size()
## The chain variables a dynamic option sets.
const OPTION_VARS: Array[String] = ["option", "option_label", "option_value"]
## The default text of a dynamic card's Chosen entry: the result then reads as
## the picked option's label.
const CHOSEN := "Chosen"
static func _bind_option(ctx: RollContext, c: Dictionary) -> void:
ctx.chain_vars["option"] = c["option"]
ctx.chain_vars["option_label"] = c["label"]
ctx.chain_vars["option_value"] = Expr.normalize(c["value"])
## The headless answer to a request: Random for a pick, min for a number, ""
@ -506,6 +621,12 @@ static func ask(ctx: RollContext, req: Dictionary) -> Variant:
static func _do_choice(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
var req := request_for(t, ctx)
var opts: Array = req["options"]
if t.choice == "pick" and opts.is_empty():
var none := _stop(t, NO_OPTIONS, {"kind": RollTable.KIND_CHOICE})
_log(none, req["log"])
_attach(f, none, ctx)
return
var reply: Variant = await ask(ctx, req)
if reply == null:
_attach(f, _stop(t, CANCELLED, {"kind": RollTable.KIND_CHOICE, "cancelled": true}), ctx)
@ -525,26 +646,71 @@ static func _do_choice(t: RollTable, f: Dictionary, ctx: RollContext, stack: Arr
await _answered(t, f, ctx, stack, s, Formatter.close_open_tags(s))
_:
var idx := int(reply) if (reply is int or reply is float) else -1
var opt: Dictionary = {}
for o: Dictionary in opts:
if int(o["index"]) == idx:
opt = o
break
var node: Dictionary
if idx >= 0 and idx < t.entries.size():
node = {"table": t, "index": idx, "entry": t.entries[idx], "children": [], "summary": "", "picked": true}
if t.card_mode:
var decks: Dictionary = ctx.get_meta("decks", {})
if not decks.has(t.id):
decks[t.id] = DeckState.new()
var deck: DeckState = decks[t.id]
var eid := t.entries[idx].id
deck.drawn[eid] = int(deck.drawn.get(eid, 0)) + 1
else:
if not opt.is_empty():
node = _option_node(t, opt, ctx)
node["picked"] = true
elif not t.is_dynamic() and int(req["hidden"]) == 0:
# A plain fixed list: Random rolls the card the usual way
# (weights, ranges, card mode).
node = _pick_node(t, ctx)
node["random"] = true
else:
var k := _pick_option(opts, ctx.rng)
if k < 0:
node = _stop(t, "No result can come up")
else:
node = _option_node(t, opts[k], ctx)
node["random"] = true
node["kind"] = RollTable.KIND_CHOICE
_log(node, req["log"])
_attach(f, node, ctx)
if node.has("stop"):
return
await _enter(node, f, ctx, stack)
## The node for a pick option from a request: a fixed entry (a card-mode deck
## counts the draw), or the Chosen entry for a dynamic option, which binds
## option, option_label and option_value first.
static func _option_node(t: RollTable, o: Dictionary, ctx: RollContext) -> Dictionary:
var ei := int(o.get("entry", o["index"]))
var node := {"table": t, "index": ei, "entry": t.entries[ei], "children": [], "summary": ""}
if o.get("dynamic", false):
_bind_option(ctx, {"option": o["option"], "label": o["label"], "value": o["value"]})
node["option"] = str(o["label"])
elif t.card_mode:
var decks: Dictionary = ctx.get_meta("decks", {})
if not decks.has(t.id):
decks[t.id] = DeckState.new()
var deck: DeckState = decks[t.id]
var eid := t.entries[ei].id
deck.drawn[eid] = int(deck.drawn.get(eid, 0)) + 1
return node
## Random among a request's options by their "weight" (each dynamic option
## weighs as much as the Chosen entry; fixed ones their own weight, or span
## on a ranged card). Position in `opts`, or -1 when every weight is 0.
static func _pick_option(opts: Array, rng: RandomNumberGenerator) -> int:
var total := 0
for o: Dictionary in opts:
total += maxi(0, int(o.get("weight", 1)))
if total <= 0:
return -1
var pick := rng.randi_range(0, total - 1)
for k in opts.size():
pick -= maxi(0, int((opts[k] as Dictionary).get("weight", 1)))
if pick < 0:
return k
return -1
static func _answered(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array, value: Variant, summary: String) -> void:
ctx.chain_vars["answer"] = value
if t.save_as != "":
@ -653,7 +819,7 @@ static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
step["kind"] = n["kind"]
if n.has("effects"):
step["effects"] = (n["effects"] as Array).duplicate(true)
for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled", "case"]:
for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled", "case", "option"]:
if n.has(k):
step[k] = n[k]
return step
@ -807,6 +973,7 @@ static func lint_pipes(board: TowerBoard) -> Array[Dictionary]:
var out: Array[Dictionary] = []
for t in board.tables:
out.append_array(lint_router(t))
out.append_array(lint_options(t))
for i in t.entries.size():
var e := t.entries[i]
var first_other := ""
@ -851,6 +1018,41 @@ static func lint_router(t: RollTable) -> Array[Dictionary]:
return out
## Problems with a card's dynamic and conditional options (empty when fine):
## a bad options_from pattern or options_where filter, a filter without
## options_from, options_from or show_if on a card that isn't a pick choice
## (they do nothing there), show_if conditions that don't parse, and a
## dynamic card with no Chosen entry.
static func lint_options(t: RollTable) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var pick := t.kind == RollTable.KIND_CHOICE and t.choice == "pick"
var from := t.options_from.strip_edges()
var where := t.options_where.strip_edges()
if from != "":
if not pick:
out.append({"table_id": t.id, "entry_id": "", "message": "Options from %s does nothing: only Which option cards take options from variables" % from})
else:
var p := RollTable.parse_options_from(from)
if str(p["error"]) != "":
out.append({"table_id": t.id, "entry_id": "", "message": "Options from %s: %s" % [from, p["error"]]})
if t.entries.is_empty():
out.append({"table_id": t.id, "entry_id": "", "message": "This card takes options from %s but has no Chosen entry" % from})
if where != "":
if from == "":
out.append({"table_id": t.id, "entry_id": "", "message": "Only where %s does nothing without Options from" % where})
elif Expr.check(where) != "":
out.append({"table_id": t.id, "entry_id": "", "message": "Only where %s: %s" % [where, Expr.check(where)]})
for e in t.entries:
var w := e.show_if.strip_edges()
if w == "":
continue
if not pick:
out.append({"table_id": t.id, "entry_id": e.id, "message": "Show only if %s does nothing: only Which option cards hide options" % w})
elif Expr.check(w) != "":
out.append({"table_id": t.id, "entry_id": e.id, "message": "Show only if %s: %s" % [w, Expr.check(w)]})
return out
static func _table_name(board: TowerBoard, id: String) -> String:
var t := board.get_table(id)
return Formatter.strip_tags(t.name) if t else id

View file

@ -33,6 +33,9 @@ var pipe_otherwise: Dictionary = {}
## Router cards: this case's condition. "" is the Otherwise case (always
## matches). Ignored on other kinds.
var when: String = ""
## Pick choices: the option is offered (in the pop-up and to Random) only when
## this expression is true when the card is reached. "" means always.
var show_if: String = ""
var has_range: bool = false
var range_lo: int = 1
var range_hi: int = 1
@ -182,6 +185,8 @@ func to_dict() -> Dictionary:
d["effects"] = effects
if when.strip_edges() != "":
d["when"] = when.strip_edges()
if show_if.strip_edges() != "":
d["show_if"] = show_if.strip_edges()
if not pipes.is_empty():
var list: Array = []
for p in pipes:
@ -217,6 +222,7 @@ static func from_dict(d: Dictionary) -> TableEntry:
e.weight = maxi(0, int(d.get("weight", 1)))
e.effects = str(d.get("effects", ""))
e.when = str(d.get("when", "")).strip_edges() if d.get("when") != null else ""
e.show_if = str(d.get("show_if", "")).strip_edges() if d.get("show_if") != null else ""
for p: Variant in d.get("pipes", []):
if p is Dictionary:
var target := str(p.get("table", ""))

View file

@ -14,6 +14,7 @@ extends RefCounted
## {@skill_*} every set variable with that prefix, sorted:
## "Gun Combat 1, Pilot 0"
## {= expr} a computed value (see Expr), e.g. {= dm(@str)}
## {@[expr]} the board variable named by expr, e.g. {@[option]}
##
## Inserted pieces are wrapped in internal url tags so the UI can show hover
## pop-ups through RichTextLabel's meta_hover_started signal:
@ -101,6 +102,12 @@ static func expand_async(text: String, ctx: RollContext, live: bool = false) ->
out += _expand_expr(text.substr(i + 2, close - i - 2), ctx)
i = close + 1
continue
if i + 2 < n and text[i + 1] == "@" and text[i + 2] == "[":
var close_b := Expr.bracket_end(text, i + 2)
if close_b > 0 and close_b + 1 < n and text[close_b + 1] == "}":
out += _indirect_var(text.substr(i + 3, close_b - i - 3), ctx)
i = close_b + 2
continue
var lm: RegExMatch = _re(_LIST_PATTERN).search(text, i)
if lm != null and lm.get_start() == i:
out += Formatter.close_open_tags(ctx.list_text(lm.get_string(1)))
@ -149,6 +156,18 @@ static func error_marker(message: String) -> String:
return "[url=error:expr]⚠ %s[/url]" % Formatter.escape_literal(message)
## {@[expr]}: the value of the board variable expr names, its unset marker,
## or an error marker for a bad expression or name.
static func _indirect_var(src: String, ctx: RollContext) -> String:
var r := Expr.evaluate(src.strip_edges(), ctx)
if r["error"] != "":
return error_marker(str(r["error"]))
var nm := Expr.indirect_name(r["value"])
if nm["error"] != "":
return error_marker(str(nm["error"]))
return _live_var("@" + str(nm["name"]), ctx)
static func _live_ref(ref: Dictionary, ctx: RollContext) -> String:
var name: String = ref["name"]
var id: String = ctx.resolve(name)

View file

@ -43,6 +43,81 @@ or ranges.
The pop-up also has **Cancel**, which stops the whole roll with a visible "Cancelled" marker.
Fast roll (Shift-click) still asks questions, because they are the player's decisions.
## 2a. Options from variables and conditional options
A `pick` card can build its options when the chain reaches it, from the board's variables,
and any option can be hidden when it doesn't apply. This covers "raise a skill you already
have", "convert one of your Contacts" or "the Officer table only when commissioned" without
a generated table per case.
### Options from variables
`options_from` (**Options: From variables** in the settings dialog) is one of:
| Pattern | Options |
|---|---|
| `@skill_*` (a prefix) | one per **set** board variable whose name starts with `skill_`, sorted by label. The label is the rest of the name, title-cased (`skill_gun_combat` → "Gun Combat"); the pop-up shows it with the value ("Gun Combat 2") |
| `@contacts` (a list variable) | one per comma-separated item, in list order. The label is the item |
`options_where` (**Only where**, optional) is an expression checked for every candidate, with
three chain variables bound: `option` (the variable name without `@`, such as `skill_pilot`,
or the list item), `option_label` ("Pilot") and `option_value` (the variable's value; for a
list, the item again). Only candidates for which it's true are offered, e.g.
`option_value >= 1` or `option != @last_contact`. An error counts as false for every
candidate and adds one red line ("Only where …: …") to the node.
**The Chosen entry.** A dynamic card's first entry is its **Chosen** entry (like the Answer
entry of a number card). Whichever dynamic option is picked:
1. `option`, `option_label` and `option_value` are set as chain variables (they last for the
rest of the roll, like `answer`);
2. `save_as`, if set, stores the label;
3. the Chosen entry happens like a rolled entry: its effects run, its text expands and its
pipes follow (with the snapshot rule of §3a).
The Chosen entry's text is the result text. Left as `Chosen` (the default) or empty, the result
reads as the option's label; otherwise it expands normally, e.g.
`Raised {option_label} to {@[option]}`. Indirect names (§4) let its effects change the picked
variable: `@[option] += 1`.
**Fixed extras.** Any entries after the Chosen entry are ordinary fixed options ("None of
these", "Learn something new"). They keep their own effects, text and pipes and never set
`option`. The pop-up lists the fixed options first (keys 1, 2, …), then the dynamic ones.
**Random.** Random picks among every offered option by weight: each dynamic option weighs as
much as the Chosen entry (1 unless changed), each fixed option its own weight (its range's
span on a ranged card). So three skills and a weight-2 "Something else" come up 20/20/20/40%,
and a fixed extra with weight 0 is offered to the player but never picked by Random. A plain
fixed card with nothing hidden rolls exactly as before (weights, ranges, card mode).
**No options.** When nothing is offered (no candidate passes and there are no visible fixed
options), the card doesn't ask: the node stops with a visible "No options available". A board
routes around that with a router or a conditional pipe before the card, e.g. a pipe
`when count(@skill_*) > 0`.
### Conditional options (`show_if`)
Any option of a `pick` card, fixed ones and the Chosen entry included, can have a `show_if`
expression (**Show only if**, edited under the option's row with the **if** toggle in Build
mode, or in the settings dialog). It's evaluated when the card is reached, before the pop-up
opens. When it's false the option isn't offered: not in the pop-up and not to Random, and it
never runs (a reply naming a hidden option counts as Random among the offered ones). A
`show_if` on the Chosen entry hides every dynamic option at once. An error counts as false and
adds a red line ("Show only if …: …"). If every option is hidden, the node stops with "No
options available", as above. `show_if` does nothing on other kinds (routers have their own
cases).
Examples: `@commissioned` (the Officer option), `@last_career != "Army"` (not the career you
just left), `@gold >= 10` (only when affordable).
### On the board and in previews
A dynamic card says "Options from @skill_* · where option_value >= 1" under its question,
and in Play mode how many options are available right now. Its first row is **Chosen**; fixed
rows are numbered from 1. Options with a condition show "only if …". The choice pop-up's
preview for a dynamic option names the variable behind it and shows the Chosen entry's effects
and pipes; a card preview (`TablePreview`) says "Options: each @skill_* that's set, where …".
## 3. Loop cards
A loop card has a `loop` mode and a `loop_expr` expression, plus two fixed entries:
@ -111,7 +186,8 @@ has no dice. Its entries are **cases**, each with an entry-level `when` expressi
settings dialog.
`Roller.lint_pipes(board)` lists problems for a board check: `when` or case conditions that
don't parse, an otherwise pipe listed before a `when` pipe on the same entry (a hint: it still
don't parse, bad `options_from` patterns, `options_where` and `show_if` expressions that don't
parse, `options_from`/`show_if` on cards where they do nothing (§2a), an otherwise pipe listed before a `when` pipe on the same entry (a hint: it still
works), an otherwise pipe on an entry with no `when` pipe (it always runs), and routers with
no cases or whose Otherwise case isn't last. Each item is `{table_id, entry_id, message}`.
@ -127,6 +203,11 @@ evaluated with Godot's `Expression`, after a small rewrite.
- **Variables:**
- `@name` reads a board variable (§5). If it's unset, it reads as `0` in arithmetic and as
`""` next to text.
- `@[expr]` reads the board variable **named by** `expr` (an indirect name), e.g.
`@[option]` or `@["skill_" + option]`. The computed name is lowercased and a leading `@`
is dropped; it must then be lowercase letters, digits and `_` (not starting with a
digit), or the expression fails with "@[…] gave "Old Bill", which isn't a variable name".
Unset reads as `0` (or `""` next to text), like `@name`.
- A bare `name` reads a chain variable (`answer`, `i`, or anything saved with `-> name`).
- **Dice:** `2d6`, `d20`, `3D`, `D3`, `2D`. A missing count means 1, and missing sides mean 6, so
`2D` is 2d6. Every die in an expression is rolled fresh.
@ -172,8 +253,14 @@ follow.
@skill_vacc_suit = max(@skill_vacc_suit, 0) gain at level 0
@traits += "Psionic"
reset @skill_*
@[option] += 1 the variable named by option (indirect)
@["skill_" + option] = max(@["skill_" + option], 0)
reset @[option]
```
An indirect target `@[expr]` is worked out when the statement runs. A bad expression or a
computed name that isn't a valid variable name is a red effect line, and nothing is written.
Each statement that runs is listed under its step in the result tray (e.g. "STR = 9"). A bad
statement shows a red marker in the tray and in Build mode rather than stopping the roll.
@ -182,6 +269,8 @@ statement shows a red marker in the tray and in Build mode rather than stopping
- `{@skill_*}` lists every set variable with that prefix, sorted, as `Gun Combat 1, Pilot 0`.
The name after the prefix is title-cased, with `_` read as a space.
- `{= expr}` shows a computed value, e.g. `STR {@str} ({= dm(@str)})`.
- `{@[expr]}` shows the variable named by `expr`, e.g. `{@[option]}`; unset shows its
`{@name?}` marker, a bad name an error marker.
- The existing `{@var|Table}`, `{hero}` and `[[refs]]` work as before.
## 6. Sheet cards
@ -195,6 +284,7 @@ step's result.
being rolled or answered, a router choosing a case, or one loop pass. Past that, the roll stops with "Stopped after
10,000 actions", and everything up to that point is kept.
- **Inline references:** `[[refs]]` inside text still nest at most 32 deep.
- **Picks:** a dynamic option counts the same single action as any pick.
- **Implementation:** pipes and loops must not use GDScript recursion proportional to chain
length. Long chains (thousands of steps) must not overflow the call stack. That applies to
the roller and to everything that walks a result (flatten, lighting, history).
@ -203,7 +293,13 @@ step's result.
- The roller is a coroutine. It `await`s `ctx.prompt.call(request)` whenever a choice card is
reached. With no prompt hook (tests, headless), `pick` chooses Random, `number` answers
`min`, and `text` answers `""`.
- **Request:** `{table_id, kind, prompt, options: [{index, text, details}], min, max, default}`.
- **Request:** `{table_id, kind, prompt, options: [{index, entry, text, details, weight}], min,
max, default, log, hidden}`. A pick's options are only the offered ones (§2a): fixed
options have `index` = `entry` = the entry's index; dynamic ones have `index` =
entries count + their position, `entry` 0 (the Chosen entry) and `dynamic`, `option`,
`label`, `value` and `value_text`. `log` holds `show_if`/`options_where` error lines and
`hidden` counts fixed options `show_if` hid. Replies must be one of the offered indices
(or -1); the UI and `BoardTester.answer()` both pick from `options`.
- **Reply:** `pick` returns an entry index or `-1` for Random. `number` returns an int.
`text` returns a String. `null` means Cancel.
- In the UI, when a prompt is needed, the steps so far appear instantly (lit on the board and
@ -217,12 +313,14 @@ step's result.
Table keys:
- `kind` (`roll` is the default and is omitted)
- `choice`, `prompt`, `save_as`, `min`, `max` (choice cards)
- `options_from`, `options_where` (pick choices with options from variables, §2a)
- `loop`, `loop_expr` (loop cards)
- `var_name`, `var_type`, `initial` (variable cards)
Entry keys:
- `effects` (String)
- `when` (String, router cases; empty or missing is Otherwise)
- `show_if` (String, pick options; empty or missing is always shown)
Pipe objects may have `"count": "<expression>"`, `"when": "<expression>"` and
`"otherwise": true` (left out when the pipe has a `when`).

View file

@ -111,7 +111,7 @@
"entries": [
{ "id": "e1", "text": "A trap snaps shut", "effects": "@hp -= 2", "range": [2, 6] },
{ "id": "e2", "text": "Dust and echoes", "range": [7, 9] },
{ "id": "e3", "text": "A glinting cache", "effects": "@gold += 2d6\n@loot += \"gem\"", "range": [10, 12] }
{ "id": "e3", "text": "A glinting cache", "effects": "@gold += 2d6\n@loot += if(1d6 <= 3, \"gem\", if(1d6 <= 3, \"silver idol\", \"old map\"))", "range": [10, 12] }
]
},
{
@ -124,7 +124,22 @@
"entries": [
{ "id": "e1", "text": "Carried up by a passing patrol", "when": "@hp <= 0", "effects": "@hp = 1", "pipes": ["report"] },
{ "id": "e2", "text": "Pockets heavy with gold", "when": "@gold >= 12", "details": "The guard at the top has noticed.", "pipes": ["way_out"] },
{ "id": "e3", "text": "Up the stairs", "pipes": ["way_out"] }
{ "id": "e3", "text": "Up the stairs", "pipes": [{ "table": "spend_find", "when": "@loot != \"\"" }, { "table": "way_out", "otherwise": true }] }
]
},
{
"id": "spend_find",
"name": "Spend a find",
"kind": "choice",
"prompt": "A shrine at the foot of the stairs. Leave one of your finds for luck?",
"options_from": "@loot",
"x": 1320,
"y": 640,
"details": "One option per item in Loot, plus two fixed ones. The last is only offered to a wounded delver.",
"entries": [
{ "id": "e1", "text": "Left the {option} at the shrine", "details": "Luck grows by one.", "effects": "@loot -= option\n@luck += 1", "pipes": ["way_out"] },
{ "id": "e2", "text": "Keep everything", "pipes": ["way_out"] },
{ "id": "e3", "text": "Trade it all for a healing draught", "show_if": "@hp <= 6", "details": "Only offered when HP is 6 or less.", "effects": "reset @loot\n@hp += 4", "pipes": ["way_out"] }
]
},
{

View file

@ -8,9 +8,11 @@ extends RefCounted
## {"format_version": 2, "id", "name", "tables": [table, ...], ["groups": [group, ...]]}
## group: id, name, x, y, w, h, [collapsed], [details], members (table ids)
## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode],
## [deck_empty], [kind], [choice], [prompt], [save_as], [min], [max],
## [deck_empty], [kind], [choice], [prompt], [save_as], [options_from],
## [options_where], [min], [max],
## [loop], [loop_expr], [var_name], [var_type], [initial], entries
## entry: id, text, [details], [weight], [range], [effects], [when], [pipes]
## entry: id, text, [details], [weight], [range], [effects], [when], [show_if],
## [pipes]
## pipe: a table id String, or {"table": id, "count": n or "<expression>",
## "save_as": name, "when": "<expression>", "otherwise": true}
## ("otherwise" is dropped when the pipe has a "when")
@ -157,6 +159,8 @@ static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Di
ed["effects"] = clean.call(str(ed["effects"]))
if ed.has("when"):
ed["when"] = clean.call(str(ed["when"]))
if ed.has("show_if"):
ed["show_if"] = clean.call(str(ed["show_if"]))
if ed.has("range"):
var r: Array = ed["range"]
if int(r[0]) > int(r[1]):
@ -308,7 +312,7 @@ static func _canon_table(td: Dictionary) -> Dictionary:
var kind := str(td.get("kind", "roll"))
if RollTable.KINDS.has(kind) and kind != "roll":
t["kind"] = kind
var defaults := {"choice": "pick", "prompt": "", "save_as": "", "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": ""}
for key: String in defaults:
if not td.has(key) or td[key] == null:
@ -345,6 +349,9 @@ static func _canon_entry(ev: Variant) -> Dictionary:
var when := str(ed.get("when", "")).strip_edges() if ed.get("when") != null else ""
if when != "":
e["when"] = when
var show_if := str(ed.get("show_if", "")).strip_edges() if ed.get("show_if") != null else ""
if show_if != "":
e["show_if"] = show_if
var src_pipes: Variant = ed.get("pipes", ed.get("triggers", []))
var pipes: Array = []
if src_pipes is Array:

View file

@ -61,6 +61,20 @@ func _scripted(answers: Dictionary, log: Array) -> Callable:
return a
## When the open question is the demo's optional "Spend a find" (asked only
## when the delver found loot), answers "Keep everything" and returns the
## next question; otherwise returns `d` unchanged.
func _past_spend(d: ChoiceDialog) -> ChoiceDialog:
if d == null or str(d.request.get("table_id", "")) != "spend_find":
return d
for o: Dictionary in d.request["options"]:
if Formatter.strip_tags(str(o["text"])) == "Keep everything":
d.answer(int(o["index"]))
break
await process_frame
return main.pending_choice()
func _var(name: String) -> Variant:
var v: Variant = main.persistent_vars.get(name)
return (v as Dictionary).get("value") if v is Dictionary else null
@ -167,7 +181,7 @@ func _test_dialog_answers() -> void:
d._spin.value = 2
d._confirm()
await process_frame
d = main.pending_choice()
d = await _past_spend(main.pending_choice())
_check(d != null and d.kind == "pick" and d._options.size() == 3, "then the pick pop-up with three options")
if d == null:
return
@ -259,7 +273,7 @@ func _test_keys() -> void:
le.text_submitted.emit(le.text)
await process_frame
_eq(_var("rooms"), 4, "a typed number is used")
d = main.pending_choice()
d = await _past_spend(main.pending_choice())
_check(d != null and d.kind == "pick", "pick pop-up for the key test")
if d == null:
return

608
tests/test_options.gd Normal file
View file

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

View file

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

View file

@ -17,6 +17,9 @@ extends ModalCard
## option's details and effects, and a TablePreview for every table it pipes
## to or mentions. Number and text questions preview where the Answer leads.
##
## 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.
##
## 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
## (Esc, the window closing, a new roll replacing this one) answers null,
@ -143,7 +146,9 @@ func _option_row(k: int, o: Dictionary) -> Control:
col.size_flags_horizontal = SIZE_EXPAND_FILL
col.mouse_filter = MOUSE_FILTER_IGNORE
row.add_child(col)
var text := RichText.label(RichText.decorate(str(o.get("text", ""))), 17, Style.INK, false, true, true)
var dynamic: bool = o.get("dynamic", false)
var shown := Formatter.escape_literal(str(o.get("label", ""))) if dynamic else str(o.get("text", ""))
var text := RichText.label(RichText.decorate(shown), 17, Style.INK, false, true, true)
text.mouse_filter = MOUSE_FILTER_IGNORE
col.add_child(text)
var det := Formatter.strip_tags(str(o.get("details", ""))).strip_edges()
@ -155,6 +160,17 @@ func _option_row(k: int, o: Dictionary) -> Control:
sub.mouse_filter = MOUSE_FILTER_IGNORE
col.add_child(sub)
b.tooltip_text = det
var vt := str(o.get("value_text", ""))
if dynamic and vt != "":
var badge := PanelContainer.new()
badge.mouse_filter = MOUSE_FILTER_IGNORE
badge.size_flags_vertical = SIZE_SHRINK_CENTER
badge.add_theme_stylebox_override("panel", Style.bordered(Style.box(Color(Style.BRASS, 0.18), 6, [9, 1, 9, 2]), 1, Color(Style.BRASS_DARK, 0.4)))
var vl := Style.make_label(vt, Style.display(), 18, Style.COPPER_DARK)
vl.mouse_filter = MOUSE_FILTER_IGNORE
vl.set_meta("option_value", true)
badge.add_child(vl)
row.add_child(badge)
b.add_child(row)
# Buttons don't size to their children, so follow the row's height.
var fit := func() -> void: b.custom_minimum_size.y = row.get_combined_minimum_size().y + 17.0
@ -536,7 +552,8 @@ func _entry_for(k: int) -> TableEntry:
var opts: Array = request.get("options", [])
if k < 0 or k >= opts.size():
return null
index = int((opts[k] as Dictionary).get("index", k))
var o: Dictionary = opts[k]
index = int(o.get("entry", o.get("index", k)))
return t.entries[index] if index >= 0 and index < t.entries.size() else null
@ -556,6 +573,17 @@ func preview_for_option(k: int) -> Control:
heading.mouse_filter = Control.MOUSE_FILTER_IGNORE
box.add_child(heading)
var any := false
var o: Dictionary = (request.get("options", []) as Array)[k] if kind == "pick" else {}
if o.get("dynamic", false):
# The variable (or list item) behind a dynamic option, and its value.
any = true
var what := "option = %s" % str(o.get("option", ""))
if str(o.get("value_text", "")) != "":
what += " · value %s" % str(o["value_text"])
var ol := Style.make_label(what, Style.body_bold(), 13, RichText.VAR_INK)
ol.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
ol.mouse_filter = Control.MOUSE_FILTER_IGNORE
box.add_child(ol)
var det := e.details.strip_edges()
if det != "":
any = true

View file

@ -12,6 +12,10 @@ extends PanelContainer
## per case, showing its condition ("if @str >= 8", "Otherwise") with its
## outlet. Live text (values, sheets, prompts) is only re-rendered by
## refresh_live(), which Main calls after rolls and edits, never per frame.
## A pick card whose options come from variables (docs/LOGIC.md §2a) says
## "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
## condition, edited under its row (the "if" toggle) in Build.
const WIDTH := 256.0
## Build mode has more controls per row, so cards are a little wider there.
@ -53,6 +57,10 @@ var _deck_label: Label
var _open_details: Dictionary = {}
## Entry ids whose effects editor is open (Build mode).
var _open_effects: Dictionary = {}
## Entry ids whose Show only if editor is open (Build mode, pick choices).
var _open_show_if: Dictionary = {}
## Play mode: "3 available now" on a dynamic pick card.
var _options_label: Label
var _table_details_open := false
## Live parts, updated by refresh_live().
var _prompt_label: RichTextLabel
@ -118,6 +126,7 @@ func rebuild() -> void:
_var_value = null
_var_hint = null
_sheet_label = null
_options_label = null
_live_cache.clear()
var build := main.mode == Main.Mode.BUILD
@ -178,6 +187,8 @@ func rebuild() -> void:
else:
_list_box.add_child(_make_row(e, i, build, ranged, numw))
_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):
@ -435,6 +446,17 @@ func _make_kind_header(_build: bool) -> Control:
l.mouse_filter = MOUSE_FILTER_IGNORE
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
v.add_child(l)
if table.is_dynamic():
var bad := not Roller.lint_options(table).is_empty()
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.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()
v.add_child(ol)
if not _build:
_options_label = Style.make_label("", Style.body(true), 12, Style.MUTED)
_options_label.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(_options_label)
return v
RollTable.KIND_LOOP:
var chip := PanelContainer.new()
@ -480,6 +502,23 @@ static func draw_fork(ci: CanvasItem, c: Vector2, r: float, color: Color, width:
ci.draw_circle(base, width * 0.9, color)
## "Options from @skill_* · where option_value >= 1" for a dynamic pick card.
static func options_line(t: RollTable) -> String:
var s := "Options from " + t.options_from.strip_edges()
if t.options_where.strip_edges() != "":
s += " · where " + t.options_where.strip_edges()
return s
func _is_pick() -> bool:
return table.kind == RollTable.KIND_CHOICE and table.choice == "pick"
## True for the Chosen row of a dynamic pick card.
func _is_chosen_row(index: int) -> bool:
return index == 0 and table.is_dynamic()
## A router case's condition as shown: "if @str >= 8", or "Otherwise".
static func case_label(e: TableEntry) -> String:
var w := e.when.strip_edges()
@ -543,6 +582,7 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
# Loop rows and the Answer row of number/text choices are fixed: no number,
# weight or delete.
var fixed := table.kind == RollTable.KIND_LOOP or (table.kind == RollTable.KIND_CHOICE and table.choice != "pick")
var chosen := _is_chosen_row(index)
var num: Label = null
if build and ranged:
@ -554,7 +594,10 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
r.add_child(_range_edit(e, false))
h.add_child(r)
else:
num = Style.make_label("" if fixed else (str(index + 1) if table.kind == RollTable.KIND_ROUTER else table.num_label(e, index)), Style.display(true), 16, Style.MUTED)
var nl := "" if fixed else (str(index + 1) if table.kind == RollTable.KIND_ROUTER else table.num_label(e, index))
if table.is_dynamic() and not ranged:
nl = "★" if chosen else str(index)
num = Style.make_label(nl, Style.display(true), 16, Style.MUTED)
num.custom_minimum_size = Vector2(numw, 0)
num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
num.size_flags_vertical = SIZE_SHRINK_CENTER
@ -574,8 +617,21 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
al.tooltip_text = "Its effects and pipes run after the player answers ({answer} holds the answer)"
h.add_child(al)
else:
var cbox: VBoxContainer = null
if chosen:
# 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)
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()
cbox.add_child(cl)
h.add_child(cbox)
var edit := LineEdit.new()
edit.text = e.text
if chosen:
edit.placeholder_text = "(the option's name)"
edit.tooltip_text = "The result text. Leave it as Chosen (or empty) to show the picked option's name; {option_label}, {option_value} and {@[option]} work"
edit.size_flags_horizontal = SIZE_EXPAND_FILL
edit.size_flags_vertical = SIZE_SHRINK_CENTER
edit.custom_minimum_size = Vector2(40, 0)
@ -587,14 +643,23 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
e.text = s
main.mark_dirty()
)
h.add_child(edit)
if cbox != null:
cbox.add_child(edit)
else:
h.add_child(edit)
if not ranged and not fixed:
h.add_child(_weight_edit(e))
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:
if not fixed and not chosen:
var x := Button.new()
x.text = "×"
x.tooltip_text = "Delete this result"
@ -612,6 +677,11 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
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() != "":
var si := Style.make_label("only if " + e.show_if.strip_edges(), Style.body_bold(true), 12, Style.COPPER_DARK)
si.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
si.mouse_filter = MOUSE_FILTER_IGNORE
col.add_child(si)
if e.effects.strip_edges() != "":
col.add_child(_effects_chip(e))
h.add_child(col)
@ -798,6 +868,14 @@ func _row_text(e: TableEntry) -> String:
s = cond
else:
s = "%s\n%s" % [cond, s]
elif table.is_dynamic() and table.entries.find(e) == 0:
var own := Formatter.strip_tags(e.text).strip_edges()
if rolled != "":
s = "[color=#%s]Chosen ·[/color] [b]%s[/b]" % [muted, RichText.decorate(rolled)]
elif own == "" or own == Roller.CHOSEN:
s = "[i][color=#%s]Chosen: the picked option[/color][/i]" % muted
else:
s = "[color=#%s]Chosen ·[/color] %s" % [muted, s]
elif table.kind == RollTable.KIND_CHOICE and table.choice != "pick":
if rolled != "":
s = "[color=#%s]Answer ·[/color] [b]%s[/b]" % [muted, RichText.decorate(rolled)]
@ -854,6 +932,47 @@ static func effect_summary(text: String, board: TowerBoard) -> String:
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()
@ -1014,6 +1133,11 @@ func refresh_live() -> void:
var s := RichText.decorate(Roller.render_sheet(main.data, main.persistent_vars, table))
if _sheet_label.text != s:
_sheet_label.text = s
if is_instance_valid(_options_label):
var n := Roller.available_count(table, Roller.live_context(main.data, main.persistent_vars))
var txt := "No options available now" if n == 0 else ("1 option available now" if n == 1 else "%d options available now" % n)
if _options_label.text != txt:
_options_label.text = txt
if is_instance_valid(_prompt_label):
var p: String
if main.mode == Main.Mode.BUILD:
@ -1166,6 +1290,8 @@ func _update_warning() -> void:
var lines := PackedStringArray()
for item: Dictionary in Roller.lint_router(table):
lines.append(str(item["message"]))
for item: Dictionary in Roller.lint_options(table):
lines.append(str(item["message"]))
if not lines.is_empty():
problems = ("%s\n" % problems if problems != "" else "") + "\n".join(lines)
_warn_label.text = problems

View file

@ -106,6 +106,8 @@ static func summary_line(t: RollTable) -> String:
return "%s (a whole number from %s to %s)" % [ask, t.min_expr, t.max_expr]
"text":
return ask + " (free text)"
if t.is_dynamic():
return "%s\nOptions: %s" % [ask, t.options_description()]
return ask
RollTable.KIND_LOOP:
var e := t.loop_expr.strip_edges()
@ -139,7 +141,14 @@ static func _row(t: RollTable, e: TableEntry, index: int) -> Control:
cond.max_lines_visible = 2
cond.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
col.add_child(cond)
if t.kind == RollTable.KIND_CHOICE and t.choice == "pick" and e.show_if.strip_edges() != "":
var si := _label("only if " + e.show_if.strip_edges(), 12, Style.COPPER_DARK, true, true)
si.max_lines_visible = 2
si.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
col.add_child(si)
var tx := Formatter.strip_tags(e.text).strip_edges()
if t.is_dynamic() and index == 0 and (tx == "" or tx == Roller.CHOSEN):
tx = "The picked option"
var text := _label(tx if tx != "" else "(empty)", 13, Style.INK, false, true)
text.max_lines_visible = 2
text.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
@ -161,7 +170,11 @@ static func _row(t: RollTable, e: TableEntry, index: int) -> Control:
static func row_label(t: RollTable, e: TableEntry, index: int) -> String:
match t.kind:
RollTable.KIND_CHOICE:
return str(index + 1) if t.choice == "pick" else "Answer"
if t.choice != "pick":
return "Answer"
if t.is_dynamic():
return "Chosen" if index == 0 else str(index)
return str(index + 1)
RollTable.KIND_LOOP:
return "Each" if index == 0 else "After"
RollTable.KIND_ROUTER:

View file

@ -42,6 +42,16 @@ var _save_as: LineEdit
var _min: LineEdit
var _max: LineEdit
var _minmax_row: Control
## Pick choices: "fixed" or "vars" (options from variables, plus fixed extras).
var _options_mode := "fixed"
var _options_box: Control
var _opt_mode_box: Control
var _opt_from: LineEdit
var _opt_where: LineEdit
var _opt_note: Label
var _show_if_box: Control
## entry id -> its Show only if field.
var _show_if: Dictionary = {}
var _loop_mode := "times"
var _loop_expr: LineEdit
var _loop_note: Label
@ -63,6 +73,7 @@ const TITLES := {
RollTable.KIND_ROUTER: "Router settings",
}
const CHOICE_LABELS := ["Which option", "How many", "Open ended"]
const OPTION_LABELS := ["Fixed list", "From variables (+ fixed extras)"]
const LOOP_LABELS := ["Times", "While", "Until"]
const LOOP_NOTES := {
"times": "Runs Each time this many times (worked out once), then Afterwards. e.g. 3, @answer, 1d3",
@ -80,6 +91,7 @@ func _init(p_table: RollTable = null) -> void:
_card_mode = table.card_mode
_deck_empty = table.deck_empty
_choice = table.choice
_options_mode = "vars" if table.options_from.strip_edges() != "" else "fixed"
_loop_mode = table.loop_mode
_var_type = table.var_type
_build()
@ -270,6 +282,13 @@ func settings() -> Dictionary:
s["save_as"] = _save_as.text.strip_edges()
s["min"] = _min.text.strip_edges()
s["max"] = _max.text.strip_edges()
s["options_mode"] = _options_mode
s["options_from"] = _opt_from.text.strip_edges()
s["options_where"] = _opt_where.text.strip_edges()
var si := {}
for eid: String in _show_if:
si[eid] = (_show_if[eid] as LineEdit).text.strip_edges()
s["show_if"] = si
RollTable.KIND_LOOP:
s["loop_mode"] = _loop_mode
s["loop_expr"] = _loop_expr.text.strip_edges()
@ -329,6 +348,7 @@ func _build_kind() -> void:
(c as Control).size_flags_horizontal = SIZE_EXPAND_FILL
_minmax_row = mm
box.add_child(mm)
_build_options(box)
RollTable.KIND_LOOP:
box.add_child(section("Repeat"))
box.add_child(segmented(LOOP_LABELS, RollTable.LOOPS.find(_loop_mode), func(i: int) -> void:
@ -403,6 +423,55 @@ func _build_kind() -> void:
body.add_child(box)
## Pick choices: where the options come from, and a Show only if field per
## option.
func _build_options(box: VBoxContainer) -> void:
var mb := VBoxContainer.new()
mb.add_theme_constant_override("separation", 6)
mb.add_child(section("Options"))
mb.add_child(segmented(OPTION_LABELS, 1 if _options_mode == "vars" else 0, func(i: int) -> void:
_options_mode = "vars" if i == 1 else "fixed"
_refresh()
))
box.add_child(mb)
_opt_mode_box = mb
var ob := VBoxContainer.new()
ob.add_theme_constant_override("separation", 8)
_opt_from = LineEdit.new()
_opt_from.text = table.options_from
_opt_from.placeholder_text = "@skill_* or @contacts"
style_line_edit(_opt_from)
_opt_from.text_changed.connect(func(_t: String) -> void: _refresh())
ob.add_child(field("Options from (@prefix_* or a @list)", _opt_from))
_opt_where = LineEdit.new()
_opt_where.text = table.options_where
_opt_where.placeholder_text = "option_value >= 1 (optional)"
style_line_edit(_opt_where)
_opt_where.text_changed.connect(func(_t: String) -> void: _refresh())
ob.add_child(field("Only where (optional)", _opt_where))
_opt_note = note("")
ob.add_child(_opt_note)
box.add_child(ob)
_options_box = ob
var sb := VBoxContainer.new()
sb.add_theme_constant_override("separation", 6)
sb.add_child(section("Show only if"))
sb.add_child(note("Checked when the card is reached. An option whose condition is false isn't offered, not even to Random. Empty means always."))
for i in table.entries.size():
var e := table.entries[i]
var le := LineEdit.new()
le.text = e.show_if
le.placeholder_text = "always"
style_line_edit(le)
le.text_changed.connect(func(_t: String) -> void: _refresh())
_show_if[e.id] = le
var label := Formatter.strip_tags(e.text).strip_edges()
var cap := "Chosen (every option from variables)" if (i == 0 and table.is_dynamic()) else "Option %d%s" % [i + (0 if table.is_dynamic() else 1), (" · " + label) if label != "" else ""]
sb.add_child(field(cap, le))
box.add_child(sb)
_show_if_box = sb
func _refresh_kind() -> void:
var s := settings()
var problems := kind_problems(table, s)
@ -417,12 +486,35 @@ func _refresh_kind() -> void:
msg = "Only the first option is kept, as the Answer row (its effects and pipes stay)."
elif _choice != table.choice and _choice == "pick":
msg = "The Answer row becomes the first option; two more are added."
elif _choice == "pick" and _options_mode == "vars" and table.is_dynamic():
msg = "The player picks one of the options from variables or a fixed extra, or Random."
elif _choice == "pick" and _options_mode == "fixed" and table.is_dynamic():
msg = "Back to a fixed list: the Chosen row becomes an ordinary option (or goes, if it does nothing)."
elif _choice == "pick":
msg = "The player picks one of the card's options, or Random."
else:
msg = "The answer goes in {answer}; the Answer row's effects and pipes run after it."
_choice_note.text = msg
_mark(_save_as, s["save_as"] == "" or _re(SAVE_PATTERN).search(TemplateKit.probe(s["save_as"])) != null)
var pick := _choice == "pick"
_opt_mode_box.visible = pick
_options_box.visible = pick and _options_mode == "vars"
_show_if_box.visible = pick and not _show_if.is_empty()
if pick and _options_mode == "vars":
_mark(_opt_from, options_from_error(s["options_from"]) == "")
_mark(_opt_where, when_error(s["options_where"]) == "")
var desc := RollTable.new()
desc.options_from = s["options_from"]
desc.options_where = s["options_where"]
var how := "One option for %s, labelled with its name and value, after any fixed options. The Chosen row runs for whichever is picked; option, option_label and option_value hold it, e.g. @[option] += 1." % desc.options_description() \
if options_from_error(s["options_from"]) == "" else "Write @skill_* for each set variable with that prefix, or @contacts for each item of a list."
if not table.is_dynamic():
how += " A Chosen row is added first; the options already on the card stay as fixed extras."
_opt_note.text = how
elif pick and table.is_dynamic():
_opt_note.text = ""
for eid: String in _show_if:
_mark(_show_if[eid] as LineEdit, when_error((_show_if[eid] as LineEdit).text) == "")
_mark(_min, Expr.check(TemplateKit.probe(s["min"])) == "" and s["min"] != "")
_mark(_max, Expr.check(TemplateKit.probe(s["max"])) == "" and s["max"] != "")
RollTable.KIND_LOOP:
@ -521,6 +613,21 @@ static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray:
var save := TemplateKit.probe(str(s.get("save_as", t.save_as)).strip_edges())
if save != "" and _re(SAVE_PATTERN).search(save) == null:
out.append("Save as: use a name like career, or @career to keep it.")
if str(s.get("choice", t.choice)) == "pick":
if str(s.get("options_mode", "vars" if t.options_from != "" else "fixed")) == "vars":
var ferr := options_from_error(str(s.get("options_from", t.options_from)))
if ferr != "":
out.append("Options from: " + ferr)
var werr := when_error(str(s.get("options_where", t.options_where)))
if werr != "":
out.append("Only where: " + werr)
var si: Dictionary = s.get("show_if", {})
for eid: String in si:
var serr := when_error(str(si[eid]))
if serr != "":
var e := t.find_entry(eid)
var at := t.entries.find(e) if e != null else -1
out.append("Show only if (%s): %s" % [("option %d" % (at + 1)) if at >= 0 else eid, serr])
if str(s.get("choice", t.choice)) == "number":
for k in [["min", "Lowest"], ["max", "Highest"]]:
var src := TemplateKit.probe(str(s.get(k[0], "")).strip_edges())
@ -555,6 +662,14 @@ static func when_error(src: String) -> String:
return Expr.check(src) if src != "" else ""
## "" when an options_from pattern is usable, else why not ("" is refused).
static func options_from_error(src: String) -> String:
src = TemplateKit.probe(src.strip_edges())
if src == "":
return "write @prefix_* or @list"
return str(RollTable.parse_options_from(src)["error"])
## A hint about the order of router cases (an Otherwise that isn't last), or "".
static func router_hint(cases: Array) -> String:
for i in cases.size():
@ -612,6 +727,16 @@ static func _apply_kind(t: RollTable, s: Dictionary) -> void:
t.choice = c
t.prompt = str(s.get("prompt", t.prompt))
t.save_as = str(s.get("save_as", t.save_as)).strip_edges()
var si: Dictionary = s.get("show_if", {})
for eid: String in si:
var se := t.find_entry(eid)
if se != null:
se.show_if = str(si[eid]).strip_edges()
if t.choice != "pick":
t.options_from = ""
t.options_where = ""
elif s.has("options_mode"):
_apply_options(t, str(s["options_mode"]) == "vars", str(s.get("options_from", "")), str(s.get("options_where", "")))
if t.choice == "number":
t.min_expr = str(s.get("min", t.min_expr)).strip_edges()
t.max_expr = str(s.get("max", t.max_expr)).strip_edges()
@ -637,6 +762,36 @@ static func _apply_kind(t: RollTable, s: Dictionary) -> void:
t.entries[0].text = str(s["template"])
## Switches a pick card between a fixed list and options from variables.
## Turning variables on adds a Chosen entry first (untouched default
## "Option N" entries go; anything else stays as a fixed extra). Turning them
## off makes the Chosen entry an ordinary option, or drops it if it does
## nothing (no effects, pipes, details or text of its own).
static func _apply_options(t: RollTable, on: bool, from: String, where: String) -> void:
if on:
if not t.is_dynamic():
var keep: Array[TableEntry] = []
for e in t.entries:
var blank := e.effects.strip_edges() == "" and e.pipes.is_empty() and e.details.strip_edges() == "" \
and e.show_if.strip_edges() == "" and RegEx.create_from_string("^Option \\d+$").search(e.text.strip_edges()) != null
if not blank:
keep.append(e)
t.entries = keep
t.entries.insert(0, TableEntry.new(TowerBoard.new_id("e"), Roller.CHOSEN))
t.options_from = from.strip_edges()
t.options_where = where.strip_edges()
return
if t.is_dynamic() and not t.entries.is_empty():
var c := t.entries[0]
var txt := Formatter.strip_tags(c.text).strip_edges()
if c.effects.strip_edges() == "" and c.pipes.is_empty() and c.details.strip_edges() == "" and (txt == "" or txt == Roller.CHOSEN):
t.entries.remove_at(0)
t.options_from = ""
t.options_where = ""
if t.entries.is_empty():
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Option 1"))
# ---------- Pure editing logic ----------
## Wraps text[sel.x:sel.y] in open/close_tag. With an empty range, inserts the