Compare commits

...

10 commits

Author SHA1 Message Date
fe883cbeda DESIGN.md: book tables merged; next steps
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:36:12 -06:00
764811b858 Docs: book-tables status, history §12, size-audit list
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:27:39 -06:00
0e45ea7abc Value pickers list the values columns save
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:26:55 -06:00
03bc168756 UI for scales: make, show and edit ordered-step values
- Making one: Scale (ordered steps) in + Card, the inspector's Type switch
  and the settings dialog; steps one per line and a starting step dropdown
  (InspectorScale); new scales get Low, Medium, High.
- Showing one: the variable card shows the current step and the steps in a
  row with the current one marked; the Variables tab stores a typed step
  number or name as the step.
- Plain words: Builder ops step_up, step_down, toward, at_least, at_most
  (BuilderScales; step_up/down need the board), DescribeScales phrases,
  scale effect rows (EffectsScaleRow) and step dropdowns in conditions.
- Help: a Scales topic after Values and changes.
- Tests: test_ui_scales, plus builder and describe cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:25:55 -06:00
446ad8ab17 Saved roll steps keep each column's result, so column highlights survive history and fast rolls
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:25:48 -06:00
1377368428 UI for cards with columns: header and cells, inspector Columns section, help
- TableCardColumns: the column-name header, each row's cells after its text
  (Play: wrapping text; Build: a field per cell, edited inline), cards widen
  per column, and in "each" mode the cell each column landed on is lit
  (Main.lit_columns, from the rolled node's columns).
- InspectorColumns: Add columns, add/rename/move/remove (cells kept in step),
  one roll vs each column, Save as (value picker) and Only if (condition
  builder); the result inspector gets a field per extra column.
- Help: a Columns topic after Ranged tables and dice.
- tests/test_ui_columns.gd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:25:03 -06:00
8bbc7002a0 Thread dice must roll dice: Dice.roll_problem shared by the field and the board check
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:19:36 -06:00
df03168382 Thread inspector: roll with other dice, roll again on some results
- InspectorThreadRolls (new helper): "Roll it with [ ] instead" for a card
  with numbered ranges (placeholder: the card's own dice), and a collapsible
  "Roll again if it comes up: …" tick list of the card's results (scrolls
  past 7 rows; open state kept across rebuilds).
- Inspector.set_pipe_dice / set_pipe_reroll delegators; edits go through
  Inspector.wrote like the other thread options, so undo covers them.
- Help: two short subsections in the Threads topic.
- tests/test_ui_threads.gd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:18:49 -06:00
a97709128c Docs: scales, columns, thread dice and rerolls (LOGIC §3e, §3f, §5.4; ARCHITECTURE §3c)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:18:49 -06:00
e3cc925e42 Engine: scale values, cards with columns, thread dice override and rerolls
- Scales: var_type scale with steps; stored as step names, read as step
  numbers in rules (a quoted step name beside a scale reads as its number);
  += / -= move steps and stop at the ends; toward().
- Columns: RollTable.columns / column_rolls (row or each), TableEntry.cells;
  RollColumns fills the other columns, saves each, honours a column's when.
- Threads: dice (roll with other dice instead) and reroll (result ids).
- RollTable save/load split into RollTableIO; Expr's base into ExprBase.
- RollLintBook checks; JSON canon keeps the new keys; tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:12:47 -06:00
74 changed files with 2764 additions and 242 deletions

View file

@ -10,7 +10,9 @@ extends RefCounted
##
## Effect model: {"ok": true, "op", "var", "amount"}
## op "set" (=), "add" (+=), "subtract" (-=), "multiply" (*=),
## "divide" (/=), "reset", "append" (+= "text"), "remove" (-= "text")
## "divide" (/=), "reset", "append" (+= "text"), "remove" (-= "text"),
## and for scale values "step_up", "step_down", "toward",
## "at_least", "at_most" (BuilderScales; step_up/down need `board`)
## var "@name", a chain name ("name"), "@prefix_*" (reset only) or
## "@[expr]" (indirect, e.g. "@[option]")
## amount String: the expression as written ("1", "2d6", "\"Aslan\"",
@ -42,7 +44,13 @@ static var _num_re: RegEx = null
## Parses one effect statement into a model, or {"ok": false, "error"} when
## it doesn't fit (a parse error, or an amount that isn't an expression).
static func parse_effect(stmt: String) -> Dictionary:
## With `board`, += / -= on a scale value read as step_up / step_down.
static func parse_effect(stmt: String, board: TowerBoard = null) -> Dictionary:
var m := _parse_effect(stmt)
return BuilderScales.refine(m, m.get("ok", false) and BuilderScales.is_scale(str(m["var"]), board))
static func _parse_effect(stmt: String) -> Dictionary:
var src := stmt.strip_edges()
if src == "":
return {"ok": false, "error": "Empty statement"}
@ -85,6 +93,8 @@ static func effect_text(m: Dictionary) -> String:
var amount := str(m.get("amount", "")).strip_edges() if m.get("amount") != null else ""
if v == "":
return ""
if BuilderScales.OPS.has(op):
return BuilderScales.text(op, v, amount)
match op:
"reset":
return "reset " + v
@ -98,10 +108,10 @@ static func effect_text(m: Dictionary) -> String:
## Every statement of an effects field as a model (ok or not), in order.
static func parse_effects(text: String) -> Array[Dictionary]:
static func parse_effects(text: String, board: TowerBoard = null) -> Array[Dictionary]:
var out: Array[Dictionary] = []
for s in Effects.split(text):
var m := parse_effect(s)
var m := parse_effect(s, board)
m["src"] = s
out.append(m)
return out
@ -365,7 +375,7 @@ static func quote(s: String) -> String:
## name (the first source wins).
## name "@luck" (board value), "@skill_*" (a collection), "tier" (chain)
## label Describe.label(name, board)
## kind "number", "text", "list" or "collection"
## kind "number", "text", "list", "collection" or "scale"
## source "variable" (a variable card), "collection", "effect" (an effect
## target), "save_as" (a pipe's or choice's save_as, or
## [[Table -> name]]), "input" (a card input), "read" (only read by
@ -405,6 +415,10 @@ static func known_values(board: TowerBoard) -> Array[Dictionary]:
var reads: Array = []
var chain := {}
for t in board.tables:
for col: Dictionary in t.columns:
if str(col.get("save_as", "")) != "":
add.call(_value_name(str(col["save_as"])), "text", "save_as", t.id)
reads.append([str(col.get("when", "")), t.id])
match t.kind:
RollTable.KIND_CHOICE:
if t.choice != "pick":

64
core/builder_scales.gd Normal file
View file

@ -0,0 +1,64 @@
class_name BuilderScales
extends RefCounted
## The scale forms of Builder's effect model (Scales, docs/PLAIN.md §2):
## step_up @climate += 1 (amount "1")
## step_down @climate -= 2 (amount "2")
## toward @climate = toward(@climate, "Temperate") (amount "Temperate")
## at_least @atmo = max(@atmo, "Medium") (amount "Medium")
## at_most @atmo = min(@atmo, "Thin") (amount "Thin")
## step_up/step_down are += / -= on a value a scale card declares, so they
## need the board (or the caller's word) to tell them apart from add/subtract;
## the other three are read from the text alone. Their amount is the step's
## name without quotes, like append/remove.
const OPS: Array[String] = ["step_up", "step_down", "toward", "at_least", "at_most"]
const _FNS := {"toward": "toward", "at_least": "max", "at_most": "min"}
const _OP_OF := {"toward": "toward", "max": "at_least", "min": "at_most"}
## True when `v` ("@climate") is declared by a scale card on `board`.
static func is_scale(v: String, board: TowerBoard) -> bool:
return card_for(v, board) != null
## The scale card that declares `v` ("@climate"), or null.
static func card_for(v: String, board: TowerBoard) -> RollTable:
if board == null or not v.begins_with("@"):
return null
var n := v.substr(1).to_lower()
for t in board.tables:
if t.is_scale() and t.var_name == n:
return t
return null
## A model with its scale form read: a "set" of toward/max/min(<the same
## value>, "Step") becomes toward/at_least/at_most, and add/subtract on a
## scale (`scale` true) becomes step_up/step_down. Anything else as it is.
static func refine(m: Dictionary, scale: bool) -> Dictionary:
if not m.get("ok", false):
return m
var op := str(m["op"])
var v := str(m["var"])
if op == "set":
var t := Builder.tokens(str(m["amount"]))
if t.size() == 6 and t[0]["t"] == "name" and _OP_OF.has(t[0]["s"]) and t[1]["s"] == "(" and t[2]["t"] == "var" \
and t[2]["s"] == v and t[3]["s"] == "," and t[4]["t"] == "str" and t[5]["s"] == ")":
return {"ok": true, "op": _OP_OF[t[0]["s"]], "var": v, "amount": Builder.unquote(str(t[4]["s"]))}
elif scale and (op == "add" or op == "subtract"):
return {"ok": true, "op": "step_up" if op == "add" else "step_down", "var": v, "amount": str(m["amount"])}
return m
## The statement for a scale model, or "" when it isn't one (or not filled in).
static func text(op: String, v: String, amount: String) -> String:
if amount == "":
return ""
match op:
"step_up":
return "%s += %s" % [v, amount]
"step_down":
return "%s -= %s" % [v, amount]
"toward", "at_least", "at_most":
return "%s = %s(%s, %s)" % [v, _FNS[op], v, Builder.quote(amount)]
return ""

View file

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

View file

@ -55,9 +55,10 @@ static func label(name: String, board: TowerBoard) -> String:
## Label table for a board: {"vars": {name: label}, "stems": [[stem, label]]
## longest first, "inputs": {name: label}}.
## longest first, "inputs": {name: label}, "scales": {name: steps}}.
static func _labels(board: TowerBoard) -> Dictionary:
var vars := {}
var scales := {}
var stems: Array = []
var inputs := {}
if board != null:
@ -68,12 +69,14 @@ static func _labels(board: TowerBoard) -> Dictionary:
stems.append([t.var_name, lab if lab != "" else RollContext.pretty_name(t.var_name)])
elif lab != "" and not vars.has(t.var_name):
vars[t.var_name] = lab
if t.is_scale() and not scales.has(t.var_name):
scales[t.var_name] = t.steps
for inp: Dictionary in t.inputs:
var il := str(inp.get("label", "")).strip_edges()
if il != "" and not inputs.has(str(inp.get("name", ""))):
inputs[str(inp.get("name", ""))] = il
stems.sort_custom(func(a: Array, b: Array) -> bool: return str(a[0]).length() > str(b[0]).length())
return {"vars": vars, "stems": stems, "inputs": inputs}
return {"vars": vars, "stems": stems, "inputs": inputs, "scales": scales}
static func _label(name: String, L: Dictionary) -> String:
@ -139,6 +142,11 @@ static func _effect(stmt: String, L: Dictionary, table: RollTable) -> String:
return src
var v := str(m["var"])
var subj := _chosen(table, L) if v.begins_with("@[") else _label(v, L)
var steps: Variant = _steps(v, L)
if steps != null:
var sc := DescribeScales.effect(BuilderScales.refine(m, true), subj, steps, func(a: String) -> String: return _expr(a, L))
if sc != "":
return _short(sc, src)
var amount := str(m["amount"])
var out := ""
match str(m["op"]):
@ -229,7 +237,16 @@ static func _clause(c: Dictionary, L: Dictionary) -> String:
return subj + " is not set"
"has":
return "%s include %s" % [subj, _value(str(c["value"]), L)]
return "%s %s" % [subj, _tail(cmp, str(c["value"]), L)]
var value := str(c["value"])
var steps: Variant = _steps(str(c["var"]), L)
if steps != null and value.is_valid_int():
value = Builder.quote(Scales.label_at(steps, int(value)))
return "%s %s" % [subj, _tail(cmp, value, L)]
## The steps of a scale value ("@climate"), or null when it isn't one.
static func _steps(v: String, L: Dictionary) -> Variant:
return L.get("scales", {}).get(v.trim_prefix("@").to_lower()) if v.begins_with("@") else null
## The comparison after a value name: "is 8 or more", "is at most 3", "is
@ -356,10 +373,6 @@ static func _expr(expr: String, L: Dictionary) -> String:
return _short(out, src)
# ---------------------------------------------------------------- helpers
## `s`, or when it's too long the original text (if that's shorter) or a cut.

View file

@ -61,12 +61,31 @@ static func pipe(entry: TableEntry, target_id: String, board: TowerBoard) -> Str
parts.append("×" + Describe._expr(ce, L))
elif entry.count_for(target_id) != 1:
parts.append("×%d" % entry.count_for(target_id))
if entry.dice_for(target_id) != "":
parts.append("with " + entry.dice_for(target_id))
var again := entry.reroll_for(target_id)
if not again.is_empty():
parts.append("again on " + reroll_names(again, board.get_table(target_id) if board else null))
var sv := entry.save_for(target_id)
if sv != "":
parts.append("saves " + Describe._label(sv, L))
return " · ".join(parts)
## "Mixed, Binary": the names of the results a thread rolls again on (their
## numbers on a ranged card: "96–00"), in the card's order.
static func reroll_names(ids: Array, t: RollTable) -> String:
if t == null:
return ", ".join(ids)
var out := PackedStringArray()
for i in t.entries.size():
var e := t.entries[i]
if ids.has(e.id):
var label := Formatter.strip_tags(e.text).strip_edges()
out.append(t.num_label(e, i) if e.has_range or label == "" else label)
return ", ".join(out)
## A check card: "Roll 2d6 + Strength modifier, need 8 or more" ("need 5 or
## less" for a roll-under check). "" for other kinds.
static func check(table: RollTable, board: TowerBoard) -> String:

42
core/describe_scales.gd Normal file
View file

@ -0,0 +1,42 @@
class_name DescribeScales
extends RefCounted
## Scale values in plain words (Describe, Scales): "Climate 1 step up",
## "Climate 2 steps down", "Climate = Hot", "Climate 1 step toward
## Temperate", "Atmosphere at least Medium", "Atmosphere at most Thin". A
## step's number in a rule reads as its name ("@climate = 2" -> "Climate =
## Cold").
## The phrase for a scale model (BuilderScales.refine'd), or "" when the op
## isn't a scale one. `steps` are the value's steps; `expr` turns an amount
## expression into words (Describe._expr).
static func effect(m: Dictionary, subj: String, steps: Array, expr: Callable) -> String:
var amount := str(m["amount"])
match str(m["op"]):
"step_up", "step_down":
var up: bool = m["op"] == "step_up"
if amount.is_valid_int():
var n := int(amount)
if n < 0:
up = not up
n = -n
return "%s %d %s %s" % [subj, n, "step" if n == 1 else "steps", "up" if up else "down"]
return "%s %s steps %s" % [subj, expr.call(amount), "up" if up else "down"]
"set":
return "%s = %s" % [subj, step_word(amount, steps, expr)]
"toward":
return "%s 1 step toward %s" % [subj, amount]
"at_least":
return "%s at least %s" % [subj, amount]
"at_most":
return "%s at most %s" % [subj, amount]
return ""
## A value token beside a scale in words: a whole number reads as the step at
## that position ("2" -> "Cold"), anything else through `expr`.
static func step_word(tok: String, steps: Array, expr: Callable) -> String:
var s := tok.strip_edges()
if s.is_valid_int() and not steps.is_empty():
return Scales.label_at(steps, int(s))
return str(expr.call(s))

View file

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

View file

@ -15,6 +15,15 @@ static func why(fact: Dictionary, board: TowerBoard, plain: bool = true) -> Stri
match str(fact.get("type", "")):
"roll":
s = _why_roll(fact, L, plain)
if str(fact.get("column", "")) != "":
s = "%s: %s" % [fact["column"], s]
"reroll":
var skipped := PackedStringArray()
for x: Dictionary in fact.get("skipped", []):
skipped.append("%s (%s)" % [Expr.format_value(x.get("value")), x.get("text", "")])
s = ("Rolled again on " if plain else "reroll skipped ") + ", ".join(skipped)
if plain and str(fact.get("column", "")) != "":
s = "%s: %s" % [fact["column"], s]
"check":
s = _why_check(fact, L, plain)
"when":

View file

@ -43,6 +43,21 @@ static func is_valid_text(text: String) -> bool:
return parse(text).valid
## "" when `text` is something to roll instead of a card's dice: plain dice
## ("3d10+70"), or a rule that rolls at least one die ("2d6 + @luck").
## Otherwise a plain-words reason.
static func roll_problem(text: String) -> String:
var s := text.strip_edges()
if s == "" or parse(s).valid:
return ""
var err := Expr.check(s)
if err != "":
return err
if RegEx.create_from_string("(?i)(^|[^a-z0-9_@])\\d*d\\d*([^a-z0-9_]|$)").search(s) == null:
return "it doesn't roll any dice"
return ""
func min_value() -> int:
return count + bonus if valid else 0

View file

@ -191,6 +191,8 @@ static func _assign(st: Dictionary, ctx: RollContext, source_id: String, facts:
var card := ctx.declared(target)
if card != null:
type = card.var_type
if type == RollTable.VAR_SCALE:
return _assign_scale(st, ctx, source_id, facts, rhs, cur, label)
var as_list := false
if op == "+=" or op == "-=":
if type == "text" or type == "list":
@ -249,6 +251,32 @@ static func _assign(st: Dictionary, ctx: RollContext, source_id: String, facts:
return {"text": line}
## A scale value (Scales): "=" takes a step name or position, "+=" and "-="
## move it that many steps, stopping at the ends.
static func _assign_scale(st: Dictionary, ctx: RollContext, source_id: String, facts: Variant, rhs: Variant, cur: Variant, label: String) -> Dictionary:
var target: String = st["target"]
var op: String = st["op"]
var steps := ctx.scale_steps(target.trim_prefix("@"))
var value: Variant = rhs
var line := ""
if op == "+=" or op == "-=":
var b: Variant = Expr.to_value(rhs)
if not Expr.is_number(b):
return {"text": "%s: %s moves by a number of steps" % [st["src"], label], "error": true}
var delta := int(b) if op == "+=" else -int(b)
value = Scales.position_of(steps, cur) + delta if cur != null else delta
ctx.save(target, value, source_id)
line = "%s %s %s → %s" % [label, _signed(delta), "step" if absi(delta) == 1 else "steps", _shown(ctx.get_value(target))]
elif op == "=":
ctx.save(target, value, source_id)
line = "%s = %s" % [label, _shown(ctx.get_value(target))]
else:
return {"text": "%s: %s can only move up or down" % [st["src"], label], "error": true}
if facts != null:
(facts as Array).append({"type": "effect", "var": target, "op": op, "before": cur, "after": ctx.get_value(target)})
return {"text": line}
static func _reset(target: String, ctx: RollContext, facts: Variant = null) -> Dictionary:
if target.ends_with("*"):
var prefix := target.trim_prefix("@").trim_suffix("*")

View file

@ -47,14 +47,21 @@ static func evaluate(src: String, ctx: RollContext) -> Dictionary:
var v: Variant = null
if ctx != null:
v = ctx.get_value(("@" if pair[0] == "@" else "") + str(pair[1]))
# A scale value reads as its step's number (unset: 0).
var steps: Array[String] = []
if pair[0] == "@":
steps = ctx.scale_steps(str(pair[1]))
if not steps.is_empty():
v = Scales.position_of(steps, v) if v != null else 0
if v == null:
unset.append(k)
v = "" if text_side[k] else 0
else:
v = to_value(v)
values.append(v)
var base := _Base.new()
var base := ExprBase.new()
base.ctx = ctx
base.var_names = kinds
var e: Expression = p["expr"]
var out: Variant = e.execute(values, base, false)
if e.has_execute_failed() and not unset.is_empty():
@ -317,6 +324,7 @@ static func _rewrite(src: String) -> Dictionary:
var n_ind := 0
# Tokens as [kind, text]: kind "str", "var", "op", "other" (for text_side).
var toks: Array = []
var lits: Array[String] = []
var i := 0
var n := src.length()
while i < n:
@ -330,8 +338,11 @@ static func _rewrite(src: String) -> Dictionary:
if j >= n:
return {"text": "", "inputs": [], "vars": [], "text_side": [], "error": "A text value is missing its closing quote"}
var lit := src.substr(i, j - i + 1)
out += lit
toks.append(["str", lit])
# A placeholder: a step name beside a scale value becomes its number
# (ExprBase._lit), worked out below once the variables are known.
out += "\u0002%d\u0002" % lits.size()
toks.append(["str", lit, lits.size()])
lits.append(lit)
i = j + 1
continue
if c == "@" and i + 1 < n and src[i + 1] == "[":
@ -471,6 +482,21 @@ static func _rewrite(src: String) -> Dictionary:
continue
if toks[u][0] == "str" or (toks[u][0] == "op" and toks[u][1] == "in"):
text_side[toks[t][1]] = true
# Each text literal goes beside the nearest @variable (left first), so a
# step name can read as its number when that variable is a scale.
for t in toks.size():
if toks[t][0] != "str" or (toks[t] as Array).size() < 3:
continue
var near := -1
for d in range(1, toks.size()):
for u: int in [t - d, t + d]:
if near < 0 and u >= 0 and u < toks.size() and toks[u][0] == "var" and vars[toks[u][1]][0] == "@":
near = toks[u][1]
if near >= 0:
break
var lit_s: String = toks[t][1]
var put := lit_s if near < 0 else "_lit(%d, %s)" % [near, lit_s]
out = out.replace("\u0002%d\u0002" % toks[t][2], put)
return {"text": out, "inputs": inputs, "vars": vars, "text_side": text_side, "error": ""}
@ -494,51 +520,3 @@ static func _is_word(c: String) -> bool:
static func _is_word_start(c: String) -> bool:
return c == "_" or (c.to_lower() != c.to_upper())
## The base instance Expression calls helper functions on.
class _Base:
extends RefCounted
var ctx: RollContext = null
var error: String = ""
func _d(n: int, sides: int) -> int:
if ctx != null and ctx.faces != null:
var total := 0
for k in n:
var f := ctx.rng.randi_range(1, sides)
(ctx.faces as Array).append(f)
total += f
return total
return Expr.roll_dice(n, sides, ctx.rng if ctx != null else null)
func dm(x: Variant) -> int:
return Expr.dm(x)
func _if(cond: Variant, then_value: Variant, else_value: Variant) -> Variant:
return then_value if Expr.truthy(cond) else else_value
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
return ctx.count_vars(str(prefix))

82
core/expr_base.gd Normal file
View file

@ -0,0 +1,82 @@
class_name ExprBase
extends RefCounted
## The base instance Godot's Expression calls helper functions on, for Expr:
## dice, dm(), if(), has(), count(), toward(), indirect @[…] names, and step
## names beside scale values (_lit).
var ctx: RollContext = null
var error: String = ""
## The expression's variables, in input order: [kind ("@" or ""), name].
var var_names: Array = []
func _d(n: int, sides: int) -> int:
if ctx != null and ctx.faces != null:
var total := 0
for k in n:
var f := ctx.rng.randi_range(1, sides)
(ctx.faces as Array).append(f)
total += f
return total
return Expr.roll_dice(n, sides, ctx.rng if ctx != null else null)
func dm(x: Variant) -> int:
return Expr.dm(x)
func _if(cond: Variant, then_value: Variant, else_value: Variant) -> Variant:
return then_value if Expr.truthy(cond) else else_value
func has(list: Variant, item: Variant) -> bool:
return Expr.has_item(list, item)
## One step from `a` toward `b` (scale positions or plain numbers).
func toward(a: Variant, b: Variant) -> int:
return Scales.toward(a, b)
## A text literal beside variable `slot`: when that variable is a scale and
## the text is one of its steps, the step's number; otherwise the text.
func _lit(slot: int, text: String) -> Variant:
if ctx == null or slot < 0 or slot >= var_names.size():
return text
var pair: Array = var_names[slot]
if pair[0] != "@":
return text
var steps := ctx.scale_steps(str(pair[1]))
if steps.is_empty():
return text
var k := Scales.position_of(steps, text)
return k if k > 0 else text
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"]))
var steps := ctx.scale_steps(str(r["name"]))
if not steps.is_empty():
return Scales.position_of(steps, v) if v != null else 0
return unset if v == null else Expr.to_value(v)
func count(prefix: Variant) -> int:
if ctx == null:
return 0
return ctx.count_vars(str(prefix))

1
core/expr_base.gd.uid Normal file
View file

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

View file

@ -5,9 +5,42 @@ extends RefCounted
## build nodes with Roller's node helpers and push frames on its work stack.
## Most times a thread rolls again on the results it skips before giving up.
const MAX_REROLLS := 100
const ALL_REROLLED := "This thread rolls again on every result"
## pick_node() for the frame `f` that reached the card: its thread may roll
## with other dice (f.dice) and roll again on some results (f.reroll, result
## ids). Skipped rolls go in a {"type": "reroll", "skipped": [{value, text}]}
## why fact on the kept node.
static func pick_for(t: RollTable, ctx: RollContext, f: Dictionary) -> Dictionary:
var dice := str(f.get("dice", ""))
var skip: Array = f.get("reroll", [])
if skip.is_empty():
return pick_node(t, ctx, dice)
var left := false
for e in t.entries:
if not skip.has(e.id) and t.can_come_up(e):
left = true
if not left:
return Roller._stop(t, ALL_REROLLED)
var skipped: Array = []
for n in MAX_REROLLS:
var node := pick_node(t, ctx, dice)
if node.has("stop") or not skip.has((node["entry"] as TableEntry).id):
if not skipped.is_empty():
Roller._why(node, [{"type": "reroll", "skipped": skipped}])
return node
skipped.append({"value": node["value"], "text": Formatter.strip_tags((node["entry"] as TableEntry).text).strip_edges()})
return Roller._stop(t, ALL_REROLLED)
## Rolls an entry the normal way (card mode, ranges or weights). Returns a node
## with no children yet, or a stop node.
static func pick_node(t: RollTable, ctx: RollContext) -> Dictionary:
## with no children yet, or a stop node. `dice` (a thread's "roll with …
## instead") replaces a ranged card's own dice; past the ends then counts as
## the end result.
static func pick_node(t: RollTable, ctx: RollContext, dice: String = "") -> Dictionary:
var rng := ctx.rng
var index: int
var value: int
@ -33,21 +66,21 @@ static func pick_node(t: RollTable, ctx: RollContext) -> Dictionary:
elif t.is_ranged():
var was: Variant = ctx.faces
ctx.faces = []
var rv := t.roll_value(ctx)
var rv := RollRange.roll_value(t, ctx, dice)
var faces: Array = ctx.faces
ctx.faces = was
if was != null:
(was as Array).append_array(faces)
if rv["error"] != "":
return Roller._stop(t, "Can't roll %s: %s" % [t.roll_text(), rv["error"]])
return Roller._stop(t, "Can't roll %s: %s" % [RollRange.join(dice, t.dice_mod) if dice != "" else t.roll_text(), rv["error"]])
value = int(rv["value"])
fact = {"type": "roll", "pick": "dice", "dice": t.roll_text(), "faces": faces, "total": value}
fact = {"type": "roll", "pick": "dice", "dice": RollRange.join(dice, t.dice_mod) if dice != "" else t.roll_text(), "faces": faces, "total": value}
if rv.has("limited"):
fact["limited"] = rv["limited"]
fact["limit_expr"] = rv["limit_expr"]
fact["raw"] = rv["raw"]
# The Why line names the modifier ("+3 for Luck") when it's all of the change.
if t.has_mod() and not t.is_expr_dice() and t.dice_obj().bonus == 0:
if dice == "" and t.has_mod() and not t.is_expr_dice() and t.dice_obj().bonus == 0:
fact["mod_expr"] = t.dice_mod.strip_edges()
if not faces.is_empty():
var nat := 0
@ -55,8 +88,8 @@ static func pick_node(t: RollTable, ctx: RollContext) -> Dictionary:
nat += x
fact["nat"] = nat
fact["mod"] = int(fact.get("raw", value)) - nat
index = t.entry_index_clamped(value)
if t.clamps():
index = RollRange.index_for(t, value, dice != "")
if t.clamps() or dice != "":
var span := RollRange.span(t)
if value < span.x or value > span.y:
fact["counts_as"] = clampi(value, span.x, span.y)

81
core/roll_columns.gd Normal file
View file

@ -0,0 +1,81 @@
class_name RollColumns
extends RefCounted
## Cards with columns (a multi-column table, RollTable.columns): after a roll
## card with columns picks its result and expands its text, fill() works out
## the other columns.
##
## - "row" (RollTable.COLUMNS_ROW): every column reads the same result's cells.
## - "each" (COLUMNS_EACH): each column after the first is rolled on its own,
## the same way the card was (the thread's dice and rerolls included). The
## first column is the card's own roll, so its result's changes and threads
## happen as usual.
##
## Columns are worked out left to right. A column with "save_as" saves its
## text before the next one starts, so a later column's "when" (only roll it
## if …) can read it. A skipped column saves nothing.
##
## The node gets "columns": [{name, text, index, value?, skipped?}] and its
## summary becomes "Resources: Rich · Water: Plentiful".
static func fill(node: Dictionary, f: Dictionary, ctx: RollContext, depth: int) -> void:
var t: RollTable = node["table"]
var rows: Array = []
var parts := PackedStringArray()
var log: Array = []
var why: Array = []
for k in t.columns.size():
var col: Dictionary = t.columns[k]
var nm := str(col.get("name", ""))
var row := {"name": nm, "text": "", "index": int(node.get("index", -1))}
if k > 0:
var w := str(col.get("when", "")).strip_edges()
if w != "":
var r := Expr.evaluate(w, ctx)
if r["error"] != "":
log.append({"text": "Column %s, only if %s: %s" % [nm, w, r["error"]], "error": true})
if r["error"] != "" or not Expr.truthy(r["value"]):
row["skipped"] = true
rows.append(row)
continue
var text := ""
if k == 0:
text = str(node["summary"])
row["value"] = node.get("value")
else:
var pick := node
if t.column_rolls == RollTable.COLUMNS_EACH:
pick = RollCards.pick_for(t, ctx, f)
if pick.has("why"):
for fact: Dictionary in pick["why"]:
var c := fact.duplicate()
c["column"] = nm
why.append(c)
if pick.has("stop"):
text = str(pick["summary"])
else:
row["index"] = int(pick["index"])
row["value"] = pick.get("value")
ctx.depth = depth + 1
var ex: Dictionary = await TextExpander.expand_async(RollTable.cell_text(pick["entry"], k), ctx)
ctx.depth = depth
text = str(ex["text"])
for c2: Dictionary in ex["children"]:
c2["inline"] = true
(node["children"] as Array).append(c2)
row["text"] = text
rows.append(row)
var save := str(col.get("save_as", "")).strip_edges()
if save != "":
ctx.save(save, plain(text), t.id)
if Formatter.strip_tags(text).strip_edges() != "":
parts.append("%s: %s" % [Formatter.escape_literal(nm), text])
node["columns"] = rows
node["summary"] = " · ".join(parts)
Roller._log(node, log)
Roller._why(node, why)
## A column's text as a value: no formatting, no internal markers.
static func plain(text: String) -> String:
return Formatter.strip_tags(Formatter.to_export_bbcode(text)).strip_edges()

1
core/roll_columns.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://6xxec1n2jspg

View file

@ -108,6 +108,9 @@ func save(name: String, value: Variant, source_id: String = "") -> void:
n = n.substr(1)
if n == "":
return
var steps := scale_steps(n)
if not steps.is_empty():
value = Scales.store(steps, value)
persistent_vars[n] = {"value": value, "source": source_id}
persistent_changed = true
elif n != "":
@ -221,6 +224,15 @@ func declared(name: String) -> RollTable:
return _decl.get(name.strip_edges().trim_prefix("@"))
## The steps of board variable `name` (no "@") when a scale card declares it,
## else [] (Scales).
func scale_steps(name: String) -> Array[String]:
var card := declared(name)
if card == null or not card.is_scale():
return []
return card.steps
## Every declared variable name (no "@").
func declared_names() -> Array[String]:
declared("")

View file

@ -74,6 +74,7 @@ static func lint_pipes(board: TowerBoard) -> Array[Dictionary]:
out.append_array(lint_options(t))
out.append_array(lint_check(t))
out.append_array(lint_inputs(board, t))
out.append_array(RollLintBook.lint(board, t))
for i in t.entries.size():
var e := t.entries[i]
var first_other := ""

48
core/roll_lint_book.gd Normal file
View file

@ -0,0 +1,48 @@
class_name RollLintBook
extends RefCounted
## Board checks for the book-table features: threads that roll with other dice
## or roll again on some results, cards with columns, and scale values.
## Items are {table_id, entry_id, message, kind: "book", level: "error"|"hint"}.
static func lint(board: TowerBoard, t: RollTable) -> Array[Dictionary]:
var out: Array[Dictionary] = []
for e in t.entries:
for p in e.pipes:
var to := board.get_table(p)
if to == null:
continue
var dice := e.dice_for(p)
if dice != "":
if not to.is_ranged() or to.kind != RollTable.KIND_ROLL:
out.append(_item(t, e.id, "The thread to %s rolls with %s, but only a card with numbered ranges can use other dice." % [_n(to), dice], "hint"))
elif Dice.roll_problem(dice) != "":
out.append(_item(t, e.id, "The thread to %s rolls with %s: %s" % [_n(to), dice, Dice.roll_problem(dice)], "error"))
var again := e.reroll_for(p)
if not again.is_empty():
var left := 0
for x in to.entries:
if again.has(x.id):
continue
left += 1
var missing := again.filter(func(id: String) -> bool: return to.find_entry(id) == null)
if left == 0:
out.append(_item(t, e.id, "The thread to %s rolls again on every result, so it can never finish." % _n(to), "error"))
if not missing.is_empty():
out.append(_item(t, e.id, "The thread to %s rolls again on results that aren't on that card any more." % _n(to), "hint"))
if t.has_columns():
for c: Dictionary in t.columns:
var w := str(c.get("when", ""))
if w != "" and Expr.check(w) != "":
out.append(_item(t, "", "Column %s, only if %s: %s" % [c.get("name", ""), w, Expr.check(w)], "error"))
if t.is_scale() and t.steps.size() < 2:
out.append(_item(t, "", "The scale %s needs at least two steps." % _n(t), "error"))
return out
static func _n(t: RollTable) -> String:
return Formatter.strip_tags(t.name).strip_edges()
static func _item(t: RollTable, entry_id: String, msg: String, level: String) -> Dictionary:
return {"table_id": t.id, "entry_id": entry_id, "message": msg, "kind": "book", "level": level}

View file

@ -0,0 +1 @@
uid://7ht6b0osgunt

View file

@ -191,11 +191,17 @@ static func live_mod(t: RollTable, ctx: RollContext) -> Dictionary:
## Rolls the dice and adds the modifier. Returns {"value": int, "error":
## String}; dice faces go to ctx.faces when it's collecting them.
static func roll_value(t: RollTable, ctx: RollContext) -> Dictionary:
## String}; dice faces go to ctx.faces when it's collecting them. `dice_text`
## (a thread's "roll with … instead") replaces the card's own dice.
static func roll_value(t: RollTable, ctx: RollContext, dice_text: String = "") -> Dictionary:
var total := 0
if not t.is_expr_dice():
var d := t.dice_obj()
var src := dice_text.strip_edges()
var d := t.dice_obj()
var plain := not t.is_expr_dice()
if src != "":
d = Dice.parse(src)
plain = d.valid
if plain:
if ctx.faces != null:
total = d.bonus
for k in d.count:
@ -207,7 +213,7 @@ static func roll_value(t: RollTable, ctx: RollContext) -> Dictionary:
else:
total = d.roll(ctx.rng)
else:
var r := Expr.evaluate(t.dice, ctx)
var r := Expr.evaluate(src if src != "" else t.dice, ctx)
if r["error"] != "":
return {"value": 0, "error": r["error"]}
total = Expr.as_int(r, 0)
@ -240,9 +246,10 @@ static func limit(t: RollTable, v: int, ctx: RollContext) -> Dictionary:
## The result index for a rolled total: past the ends counts as the end
## result on a table that clamps; otherwise -1 when no range holds it.
static func index_for(t: RollTable, value: int) -> int:
if clamps(t):
## result on a table that clamps (or always, with `force_clamp`); otherwise -1
## when no range holds it.
static func index_for(t: RollTable, value: int, force_clamp: bool = false) -> int:
if force_clamp or clamps(t):
var s := span(t)
value = clampi(value, s.x, s.y)
for i in t.entries.size():

View file

@ -35,7 +35,13 @@ const LOOPS: Array[String] = ["times", "while", "until"]
## A variable card with var_type "collection" declares a group of board
## values @<var_name>_<item> (docs/PLAIN.md §3); its name labels the group.
const VAR_COLLECTION := "collection"
const VAR_TYPES: Array[String] = ["number", "text", "list", VAR_COLLECTION]
## A variable card with var_type "scale" lists ordered steps (Scales).
const VAR_SCALE := "scale"
const VAR_TYPES: Array[String] = ["number", "text", "list", VAR_COLLECTION, VAR_SCALE]
## Cards with columns: one roll picks the row for every column ("row"), or
## each column is rolled on its own ("each"; RollColumns).
const COLUMNS_ROW := "row"
const COLUMNS_EACH := "each"
## Check cards (docs/PLAIN.md §4.1): success when the total is >= ("ge") or
## <= ("le") the target.
const CHECK_CMPS: Array[String] = ["ge", "le"]
@ -72,6 +78,13 @@ var deck_empty: String = "reshuffle"
## What a Deck-mode card that waits for Shuffle gives once it's empty ("" = "Empty").
var deck_empty_text: String = ""
var entries: Array[TableEntry] = []
## Roll cards with columns (a multi-column table): Array of {"name": String,
## "save_as": value name (optional), "when": condition (optional)}. Column 0
## is each result's own text; the others are TableEntry.cells. Empty = a
## plain one-column card.
var columns: Array = []
## COLUMNS_ROW or COLUMNS_EACH.
var column_rolls: String = COLUMNS_ROW
## One of KINDS.
var kind: String = KIND_ROLL
@ -101,6 +114,8 @@ var loop_expr: String = ""
var var_name: String = ""
var var_type: String = "number"
var initial: String = ""
## Scale variables: the ordered steps, lowest first.
var steps: Array[String] = []
## Check cards: the dice, the modifier and the target (expressions) and the
## comparison ("ge" or "le"). entries[0] is Success, entries[1] Failure.
var check_dice: String = CHECK_DEFAULT_DICE
@ -163,6 +178,7 @@ static func create(p_kind: String, p_id: String, p_name: String, sub: String = "
if t.var_type == VAR_COLLECTION and t.var_name.length() > 3 and t.var_name.ends_with("s") and not t.var_name.ends_with("ss"):
t.var_name = t.var_name.substr(0, t.var_name.length() - 1)
t.initial = "0" if t.var_type == "number" else ""
if t.var_type == VAR_SCALE: t.steps.assign(["Low", "Medium", "High"]); t.initial = "Low"
KIND_SHEET:
t.entries.append(TableEntry.new("e1", "[b]%s[/b]" % p_name))
KIND_ROUTER:
@ -176,6 +192,31 @@ static func create(p_kind: String, p_id: String, p_name: String, sub: String = "
return t
## True for a roll card with columns.
func has_columns() -> bool:
return kind == KIND_ROLL and not columns.is_empty()
## The column names, in order.
func column_names() -> Array[String]:
var out: Array[String] = []
for c: Dictionary in columns:
out.append(str(c.get("name", "")))
return out
## Column `k`'s text on a result: its own text for column 0, else its cell.
static func cell_text(e: TableEntry, k: int) -> String:
if k == 0:
return e.text
return e.cells[k - 1] if k - 1 < e.cells.size() else ""
## True for a scale variable card.
func is_scale() -> bool:
return kind == KIND_VARIABLE and var_type == VAR_SCALE
## True for a collection variable card.
func is_collection() -> bool:
return kind == KIND_VARIABLE and var_type == VAR_COLLECTION
@ -426,138 +467,11 @@ static func _looks_literal(src: String) -> bool:
func to_dict() -> Dictionary:
var list: Array = []
for e in entries:
list.append(e.to_dict())
var d := {"id": id, "name": name, "x": roundi(position.x), "y": roundi(position.y), "entries": list}
if kind != KIND_ROLL:
d["kind"] = kind
if collapsed:
d["collapsed"] = true
if details != "":
d["details"] = details
if not tags.is_empty():
d["tags"] = tags.duplicate()
if color != "":
d["color"] = color
if roll_floor.strip_edges() != "":
d["roll_floor"] = roll_floor.strip_edges()
if roll_ceiling.strip_edges() != "":
d["roll_ceiling"] = roll_ceiling.strip_edges()
if width > 0.0:
d["w"] = roundi(width)
if list_height > 0.0:
d["list_h"] = roundi(list_height)
if is_ranged():
d["dice"] = dice
if has_mod():
d["dice_mod"] = dice_mod.strip_edges()
if card_mode:
d["card_mode"] = true
if deck_empty != "reshuffle":
d["deck_empty"] = deck_empty
if deck_empty_text != "":
d["deck_empty_text"] = deck_empty_text
if kind == KIND_CHOICE:
if choice != "pick":
d["choice"] = choice
if prompt != "":
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":
d["max"] = max_expr
elif kind == KIND_LOOP:
if loop_mode != "times":
d["loop"] = loop_mode
if loop_expr != "":
d["loop_expr"] = loop_expr
elif kind == KIND_VARIABLE:
if var_name != "":
d["var_name"] = var_name
if var_type != "number":
d["var_type"] = var_type
if initial != "":
d["initial"] = initial
elif kind == KIND_CHECK:
if check_dice != CHECK_DEFAULT_DICE:
d["check_dice"] = check_dice
if check_mod != "":
d["check_mod"] = check_mod
if check_cmp != "ge":
d["check_cmp"] = check_cmp
if check_target != CHECK_DEFAULT_TARGET:
d["check_target"] = check_target
if not inputs.is_empty():
var list2: Array = []
for inp: Dictionary in inputs:
var o := {"name": str(inp.get("name", ""))}
if str(inp.get("label", "")) != "":
o["label"] = str(inp["label"])
if str(inp.get("default", "")) != "":
o["default"] = str(inp["default"])
list2.append(o)
d["inputs"] = list2
return d
return RollTableIO.to_dict(self)
static func from_dict(d: Dictionary) -> RollTable:
var t := RollTable.new(str(d.get("id", "")), str(d.get("name", "")))
t.position = Vector2(float(d.get("x", 0)), float(d.get("y", 0)))
t.collapsed = bool(d.get("collapsed", false))
t.details = str(d.get("details", ""))
for tag: Variant in d.get("tags", []):
t.tags.append(str(tag))
t.color = str(d.get("color", ""))
t.roll_floor = str(d.get("roll_floor", ""))
t.roll_ceiling = str(d.get("roll_ceiling", ""))
t.width = maxf(0.0, float(d.get("w", 0)))
t.list_height = maxf(0.0, float(d.get("list_h", 0)))
if d.has("dice"):
t.dice = str(d["dice"])
elif int(d.get("die", 0)) > 1:
t.dice = "1d%d" % int(d["die"])
t.dice_mod = expr_text(d.get("dice_mod", ""), "").strip_edges()
t.card_mode = bool(d.get("card_mode", false))
t.deck_empty = "stop" if str(d.get("deck_empty", "reshuffle")) == "stop" else "reshuffle"
t.deck_empty_text = str(d.get("deck_empty_text", ""))
var k := str(d.get("kind", KIND_ROLL))
t.kind = k if KINDS.has(k) else KIND_ROLL
var c := str(d.get("choice", "pick"))
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"))
t.loop_mode = lm if LOOPS.has(lm) else "times"
t.loop_expr = expr_text(d.get("loop_expr", ""), "")
t.var_name = str(d.get("var_name", "")).strip_edges().trim_prefix("@")
var vt := str(d.get("var_type", "number"))
t.var_type = vt if VAR_TYPES.has(vt) else "number"
t.initial = expr_text(d.get("initial", ""), "")
t.check_dice = expr_text(d.get("check_dice", CHECK_DEFAULT_DICE), CHECK_DEFAULT_DICE).strip_edges()
if t.check_dice == "":
t.check_dice = CHECK_DEFAULT_DICE
t.check_mod = expr_text(d.get("check_mod", ""), "").strip_edges()
var cc := str(d.get("check_cmp", "ge"))
t.check_cmp = cc if CHECK_CMPS.has(cc) else "ge"
t.check_target = expr_text(d.get("check_target", CHECK_DEFAULT_TARGET), CHECK_DEFAULT_TARGET).strip_edges()
if t.check_target == "":
t.check_target = CHECK_DEFAULT_TARGET
t.inputs = clean_inputs(d.get("inputs", []))
for ed: Variant in d.get("entries", []):
if ed is Dictionary:
t.entries.append(TableEntry.from_dict(ed))
return t
return RollTableIO.from_dict(d)
## Expression fields may arrive as JSON numbers: 3.0 -> "3".

176
core/roll_table_io.gd Normal file
View file

@ -0,0 +1,176 @@
class_name RollTableIO
extends RefCounted
## RollTable to and from its JSON Dictionary (RollTable.to_dict/from_dict
## delegate here). Keys at their defaults are left out.
static func to_dict(t: RollTable) -> Dictionary:
var list: Array = []
for e in t.entries:
list.append(e.to_dict())
var d := {"id": t.id, "name": t.name, "x": roundi(t.position.x), "y": roundi(t.position.y), "entries": list}
if t.kind != RollTable.KIND_ROLL:
d["kind"] = t.kind
if t.collapsed:
d["collapsed"] = true
if t.details != "":
d["details"] = t.details
if not t.tags.is_empty():
d["tags"] = t.tags.duplicate()
if t.color != "":
d["color"] = t.color
if t.roll_floor.strip_edges() != "":
d["roll_floor"] = t.roll_floor.strip_edges()
if t.roll_ceiling.strip_edges() != "":
d["roll_ceiling"] = t.roll_ceiling.strip_edges()
if t.width > 0.0:
d["w"] = roundi(t.width)
if t.list_height > 0.0:
d["list_h"] = roundi(t.list_height)
if t.is_ranged():
d["dice"] = t.dice
if t.has_mod():
d["dice_mod"] = t.dice_mod.strip_edges()
if t.card_mode:
d["card_mode"] = true
if t.deck_empty != "reshuffle":
d["deck_empty"] = t.deck_empty
if t.deck_empty_text != "":
d["deck_empty_text"] = t.deck_empty_text
if not t.columns.is_empty():
d["columns"] = clean_columns(t.columns)
if t.column_rolls != RollTable.COLUMNS_ROW:
d["column_rolls"] = t.column_rolls
if t.kind == RollTable.KIND_CHOICE:
if t.choice != "pick":
d["choice"] = t.choice
if t.prompt != "":
d["prompt"] = t.prompt
if t.save_as != "":
d["save_as"] = t.save_as
if t.options_from.strip_edges() != "":
d["options_from"] = t.options_from.strip_edges()
if t.options_where.strip_edges() != "":
d["options_where"] = t.options_where.strip_edges()
if t.min_expr != "0":
d["min"] = t.min_expr
if t.max_expr != "99":
d["max"] = t.max_expr
elif t.kind == RollTable.KIND_LOOP:
if t.loop_mode != "times":
d["loop"] = t.loop_mode
if t.loop_expr != "":
d["loop_expr"] = t.loop_expr
elif t.kind == RollTable.KIND_VARIABLE:
if t.var_name != "":
d["var_name"] = t.var_name
if t.var_type != "number":
d["var_type"] = t.var_type
if t.initial != "":
d["initial"] = t.initial
if t.var_type == RollTable.VAR_SCALE and not t.steps.is_empty():
d["steps"] = t.steps.duplicate()
elif t.kind == RollTable.KIND_CHECK:
if t.check_dice != RollTable.CHECK_DEFAULT_DICE:
d["check_dice"] = t.check_dice
if t.check_mod != "":
d["check_mod"] = t.check_mod
if t.check_cmp != "ge":
d["check_cmp"] = t.check_cmp
if t.check_target != RollTable.CHECK_DEFAULT_TARGET:
d["check_target"] = t.check_target
if not t.inputs.is_empty():
var list2: Array = []
for inp: Dictionary in t.inputs:
var o := {"name": str(inp.get("name", ""))}
if str(inp.get("label", "")) != "":
o["label"] = str(inp["label"])
if str(inp.get("default", "")) != "":
o["default"] = str(inp["default"])
list2.append(o)
d["inputs"] = list2
return d
static func from_dict(d: Dictionary) -> RollTable:
var t := RollTable.new(str(d.get("id", "")), str(d.get("name", "")))
t.position = Vector2(float(d.get("x", 0)), float(d.get("y", 0)))
t.collapsed = bool(d.get("collapsed", false))
t.details = str(d.get("details", ""))
for tag: Variant in d.get("tags", []):
t.tags.append(str(tag))
t.color = str(d.get("color", ""))
t.roll_floor = str(d.get("roll_floor", ""))
t.roll_ceiling = str(d.get("roll_ceiling", ""))
t.width = maxf(0.0, float(d.get("w", 0)))
t.list_height = maxf(0.0, float(d.get("list_h", 0)))
if d.has("dice"):
t.dice = str(d["dice"])
elif int(d.get("die", 0)) > 1:
t.dice = "1d%d" % int(d["die"])
t.dice_mod = RollTable.expr_text(d.get("dice_mod", ""), "").strip_edges()
t.card_mode = bool(d.get("card_mode", false))
t.deck_empty = "stop" if str(d.get("deck_empty", "reshuffle")) == "stop" else "reshuffle"
t.deck_empty_text = str(d.get("deck_empty_text", ""))
t.columns = clean_columns(d.get("columns", []))
t.column_rolls = RollTable.COLUMNS_EACH if str(d.get("column_rolls", "")) == RollTable.COLUMNS_EACH else RollTable.COLUMNS_ROW
var k := str(d.get("kind", RollTable.KIND_ROLL))
t.kind = k if RollTable.KINDS.has(k) else RollTable.KIND_ROLL
var c := str(d.get("choice", "pick"))
t.choice = c if RollTable.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 = RollTable.expr_text(d.get("options_where", ""), "").strip_edges()
t.min_expr = RollTable.expr_text(d.get("min", "0"), "0")
t.max_expr = RollTable.expr_text(d.get("max", "99"), "99")
var lm := str(d.get("loop", "times"))
t.loop_mode = lm if RollTable.LOOPS.has(lm) else "times"
t.loop_expr = RollTable.expr_text(d.get("loop_expr", ""), "")
t.var_name = str(d.get("var_name", "")).strip_edges().trim_prefix("@")
var vt := str(d.get("var_type", "number"))
t.var_type = vt if RollTable.VAR_TYPES.has(vt) else "number"
t.initial = RollTable.expr_text(d.get("initial", ""), "")
t.steps = Scales.clean(d.get("steps", []))
t.check_dice = RollTable.expr_text(d.get("check_dice", RollTable.CHECK_DEFAULT_DICE), RollTable.CHECK_DEFAULT_DICE).strip_edges()
if t.check_dice == "":
t.check_dice = RollTable.CHECK_DEFAULT_DICE
t.check_mod = RollTable.expr_text(d.get("check_mod", ""), "").strip_edges()
var cc := str(d.get("check_cmp", "ge"))
t.check_cmp = cc if RollTable.CHECK_CMPS.has(cc) else "ge"
t.check_target = RollTable.expr_text(d.get("check_target", RollTable.CHECK_DEFAULT_TARGET), RollTable.CHECK_DEFAULT_TARGET).strip_edges()
if t.check_target == "":
t.check_target = RollTable.CHECK_DEFAULT_TARGET
t.inputs = RollTable.clean_inputs(d.get("inputs", []))
for ed: Variant in d.get("entries", []):
if ed is Dictionary:
t.entries.append(TableEntry.from_dict(ed))
return t
## Cleans a "columns" value from JSON or the UI: Array of {name, save_as?,
## when?} with blank names dropped and empty keys left out.
static func clean_columns(v: Variant) -> Array:
var out: Array = []
if not (v is Array):
return out
for item: Variant in v:
var nm := ""
var save := ""
var when := ""
if item is Dictionary:
nm = str(item.get("name", "")) if item.get("name") != null else ""
save = str(item.get("save_as", "")) if item.get("save_as") != null else ""
when = str(item.get("when", "")) if item.get("when") != null else ""
elif item is String:
nm = item
nm = nm.strip_edges()
if nm == "":
continue
var o := {"name": nm}
if save.strip_edges() != "":
o["save_as"] = save.strip_edges()
if when.strip_edges() != "":
o["when"] = when.strip_edges()
out.append(o)
return out

View file

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

View file

@ -36,7 +36,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", "deck_empty", "dropped", "kept", "combined", "stopped_before", "case", "option", "check", "inputs"]:
for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled", "deck_empty", "dropped", "kept", "combined", "stopped_before", "case", "option", "check", "inputs", "columns"]:
if n.has(k):
step[k] = n[k]
if n.has("why"):

View file

@ -270,7 +270,7 @@ static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack:
_attach(f, sheet, ctx)
await _enter(sheet, f, ctx, stack, true, true)
_:
var node := RollCards.pick_node(t, ctx)
var node := RollCards.pick_for(t, ctx, f)
if node.has("nat"):
ctx.chain_vars["nat"] = node["nat"]
node.erase("nat")
@ -303,6 +303,9 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr
c["inline"] = true
kids.append(c)
node["summary"] = ex["text"]
if t.has_columns() and not node.has("kind"):
await RollColumns.fill(node, f, ctx, depth)
ctx.depth = depth
# The Chosen entry of a dynamic pick reads as the option's label unless
# it has text of its own.
if node.has("option"):
@ -348,6 +351,10 @@ static func _queue_pipes(node: Dictionary, ctx: RollContext, stack: Array, depth
var fr := {"op": OP_PIPE, "node": node, "entry": e, "to": p, "left": int(item["count"]), "save": e.save_for(p), "depth": depth}
if item.has("with"):
fr["with"] = item["with"]
if e.dice_for(p) != "":
fr["dice"] = e.dice_for(p)
if not e.reroll_for(p).is_empty():
fr["reroll"] = e.reroll_for(p)
var mode := e.combine_for(p)
if mode != "all" and int(item["count"]) > 1:
# Runs after every repeat: combines them (RollCombine).
@ -405,8 +412,9 @@ static func _do_pipe(board: TowerBoard, f: Dictionary, ctx: RollContext, stack:
f["left"] = int(f["left"]) - 1
stack.append(f)
var fr := {"op": OP_ROLL, "id": f["to"], "parent": f["node"], "save": f["save"], "depth": f["depth"]}
if f.has("with"):
fr["with"] = f["with"]
for key in ["with", "dice", "reroll"]:
if f.has(key):
fr[key] = f[key]
if f.get("no_follow", false):
fr["no_follow"] = true
stack.append(fr)

65
core/scales.gd Normal file
View file

@ -0,0 +1,65 @@
class_name Scales
extends RefCounted
## Scale values (docs/LOGIC.md §5.4): a variable card with var_type "scale"
## lists ordered steps ("Supercold", "Cold", "Temperate", "Hot", "Superhot").
##
## - The value is stored as the step's name, so {@climate} shows "Cold".
## - In rules it reads as the step's number (1 = the first step), and a quoted
## step name next to it reads as that step's number too, so
## @atmosphere >= "Thin" and @climate = toward(@climate, "Temperate") work.
## - Saving a number picks that step, stopping at the ends; saving a name
## matches the steps without caring about capitals.
## The step whose position (1-based) is `n`, kept within the ends. "" when
## there are no steps.
static func label_at(steps: Array, n: int) -> String:
if steps.is_empty():
return ""
return str(steps[clampi(n, 1, steps.size()) - 1])
## The position (1-based) of a step name, or 0 when it isn't one. Numbers are
## taken as positions as they are.
static func position_of(steps: Array, v: Variant) -> int:
if v is int or v is float:
return int(v)
var s := str(v).strip_edges().to_lower()
for k in steps.size():
if str(steps[k]).to_lower() == s:
return k + 1
return 0
## What a scale variable stores for `v`: a number becomes the step at that
## position (kept within the ends), a step name its canonical spelling, and
## anything else is kept as it is.
static func store(steps: Array, v: Variant) -> Variant:
if steps.is_empty():
return v
if v is int or v is float or (v is String and (v as String).is_valid_float()):
return label_at(steps, roundi(float(v)))
var k := position_of(steps, v)
return str(steps[k - 1]) if k > 0 else v
## Moves position `a` one step toward position `b`.
static func toward(a: Variant, b: Variant) -> int:
var x := int(Expr.to_value(a)) if Expr.is_number(Expr.to_value(a)) else 0
var y := int(Expr.to_value(b)) if Expr.is_number(Expr.to_value(b)) else 0
return x + signi(y - x)
## Cleans a "steps" value from JSON or the UI: trimmed names, blanks dropped.
static func clean(v: Variant) -> Array[String]:
var out: Array[String] = []
var items: Array = []
if v is Array:
items = v
elif v is String:
items = Array((v as String).split("\n"))
for item: Variant in items:
var s := str(item).strip_edges()
if s != "":
out.append(s)
return out

1
core/scales.gd.uid Normal file
View file

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

View file

@ -45,6 +45,14 @@ var pipe_combine: Dictionary = {}
## target table id -> true: the roll waits before following this thread until
## the player continues (Roller.OP_PAUSE). Missing = no pause.
var pipe_pause: Dictionary = {}
## target table id -> dice to roll the target with instead of its own
## ("3d10+70"; a ranged target only). Missing = the card's own dice.
var pipe_dice: Dictionary = {}
## target table id -> Array of the target's result ids to roll again on
## ("re-roll any result of 96+"). Missing = keep whatever comes up.
var pipe_reroll: Dictionary = {}
## Cards with columns: this result's text in columns 1.. (column 0 is `text`).
var cells: Array[String] = []
## Choice options: what picking this costs (RollCosts): a value name and an
## amount (an expression). "" = free.
var cost_value: String = ""
@ -215,6 +223,40 @@ func combine_for(target: String) -> String:
return str(pipe_combine.get(target, "all"))
## The dice the thread rolls its card with instead of the card's own, or "".
func dice_for(target: String) -> String:
return str(pipe_dice.get(target, "")).strip_edges()
## The target's result ids the thread rolls again on (a copy; [] for none).
func reroll_for(target: String) -> Array[String]:
var out: Array[String] = []
var v: Variant = pipe_reroll.get(target)
if v is Array:
for x: Variant in v:
if str(x) != "" and not out.has(str(x)):
out.append(str(x))
return out
func set_pipe_dice(target: String, dice: String) -> void:
if dice.strip_edges() == "":
pipe_dice.erase(target)
else:
pipe_dice[target] = dice.strip_edges()
func set_pipe_reroll(target: String, ids: Array) -> void:
var clean: Array[String] = []
for x: Variant in ids:
if str(x) != "" and not clean.has(str(x)):
clean.append(str(x))
if clean.is_empty():
pipe_reroll.erase(target)
else:
pipe_reroll[target] = clean
## Removes a pipe along with its options.
func remove_pipe(target: String) -> void:
pipes.erase(target)
@ -226,6 +268,8 @@ func remove_pipe(target: String) -> void:
pipe_color.erase(target)
pipe_combine.erase(target)
pipe_pause.erase(target)
pipe_dice.erase(target)
pipe_reroll.erase(target)
func to_dict() -> Dictionary:
@ -252,7 +296,9 @@ func to_dict() -> Dictionary:
var col := str(pipe_color.get(p, ""))
var comb := combine_for(p)
var paused := pipe_pause.has(p)
if expr == "" and n == 1 and s == "" and w == "" and not other and wv == null and col == "" and comb == "all" and not paused:
var dice := dice_for(p)
var again := reroll_for(p)
if expr == "" and n == 1 and s == "" and w == "" and not other and wv == null and col == "" and comb == "all" and not paused and dice == "" and again.is_empty():
list.append(p)
else:
var po := {"table": p}
@ -274,10 +320,16 @@ func to_dict() -> Dictionary:
po["combine"] = comb
if paused:
po["pause"] = true
if dice != "":
po["dice"] = dice
if not again.is_empty():
po["reroll"] = again
list.append(po)
d["pipes"] = list
if has_range:
d["range"] = [range_lo, range_hi]
if not cells.is_empty():
d["cells"] = cells.duplicate()
if page != "":
d["page"] = page
if image != "":
@ -316,8 +368,14 @@ static func from_dict(d: Dictionary) -> TableEntry:
e.pipe_combine[target] = str(p["combine"])
if bool(p.get("pause", false)):
e.pipe_pause[target] = true
e.set_pipe_dice(target, str(p.get("dice", "")) if p.get("dice") != null else "")
if p.get("reroll") is Array:
e.set_pipe_reroll(target, p["reroll"])
elif str(p) != "":
e.add_pipe(str(p))
if d.get("cells") is Array:
for c: Variant in d["cells"]:
e.cells.append(str(c) if c != null else "")
var r: Variant = d.get("range")
if r is Array and r.size() == 2:
e.has_range = true

View file

@ -164,6 +164,18 @@ templates/ built-in templates · examples/logic_demo.json (original demo board)
group `parent`; table `color`, `w`, `list_h`, `roll_floor`, `roll_ceiling`, `deck_empty_text`;
result `page`, `image`, `cost {value, amount}`; thread `color`, `combine`, `pause`.
## 3c. Modules added 2026-11-10 (book tables)
- **Scales:** `core/scales.gd` (store/read step names), `core/expr_base.gd` (Expression's base
instance, split out of `expr.gd`: `_lit` turns a step name beside a scale into its number,
`toward()`), `Effects._assign_scale`, `RollContext.scale_steps`.
- **Columns:** `core/roll_columns.gd` (fills the other columns after a roll), `RollTable.columns`
/ `column_rolls` / `cell_text`, `TableEntry.cells`.
- **Thread dice and rerolls:** `TableEntry.pipe_dice` / `pipe_reroll`, `RollCards.pick_for`,
`RollRange.roll_value(…, dice_text)`.
- **Checks and IO:** `core/roll_lint_book.gd`; `core/roll_table_io.gd` (RollTable to/from JSON,
split out of `roll_table.gd`). JSON keys: table `columns`, `column_rolls`, `steps`; result
`cells`; thread `dice`, `reroll`. Spec: LOGIC.md §3e, §3f, §5.4.
## 4. Data and storage
- **Collections:** `user://collections/<id>.json`, format_version 2 (`{format_version, id,
name, tables, groups?}`). On Linux that's `~/.local/share/godot/app_userdata/TableTower/`.

View file

@ -1,7 +1,7 @@
# Table Tarot (repo: TableTower) — Status and Plan
**Engine:** Godot 4.7.2 (GDScript) · **Started:** 2026-11-08 · **Last updated:** 2026-11-10 (the
2026-11-10 plan is finished and on `main`)
2026-11-10 plan and the book-tables features are finished and on `main`)
The short page to read at the start of every session. Everything else is read only when needed:
- `docs/ARCHITECTURE.md`: feature summary, file map (§3b lists the 2026-11-10 modules), storage, known gaps.
@ -42,6 +42,17 @@ Card, Result, Change, Reset, Dice wording rules: `docs/HISTORY.md` §6 "Terminol
selection box in Play and Build; panning is middle-drag or Space+drag.
- **Audits done:** the seven files over 600 lines were split into helpers; tests share `TestBase`.
- **The user is playtesting.** Expect more bug reports; fix them first.
- **Book tables (merged to `main` 2026-11-10):** four features for printed-book procedures, found by
building The Perilous Void's world generation: **Scales** (ordered steps that move up/down),
**Columns** (multi-column tables, one roll per row or per column), thread **"roll with … instead"**
and thread **"roll again if it comes up"**. Spec: LOGIC.md §3e, §3f, §5.4; modules: ARCHITECTURE §3c.
The goal behind it: handle any book's random tables and oracles (HISTORY §12).
- **Spread built with them:** `perilous-void-stage-1` in the user's collections (72 cards, Stage I of
the book's world generation). Generator: `TableTower-private/perilous_void/build_world_gen.py`.
Stage II (pp. 62–78: surface features, resource details, lifeforms) is not built yet; the user
hasn't opened the spread in the app yet (only headless runs and one screenshot).
**Next, likely:** the user's feedback on the Perilous Void spread; Stage II of it; a size audit (§4).
## 4. Open items
**Waiting on the user**
@ -49,7 +60,8 @@ Card, Result, Change, Reset, Dice wording rules: `docs/HISTORY.md` §6 "Terminol
platform-tools) is not. Ask before downloading. No Android preset yet.
- Fonts: the theme editor has no font choice until more OFL fonts are bundled.
- A UI name for the Collection card kind.
- Reroll rule: should a "reroll" result that comes up during its own reroll be ignored and rolled again?
- Reroll rule: probably settled by the thread option "Roll again if it comes up" (a reroll thread
can skip its own result). Confirm with the user.
- Thread string art (the user will draw it), then use it like `CardFrame` does for cards.
- Repo privacy on Forgejo: needs Niles/sock's username and a token from the user.
@ -57,8 +69,12 @@ Card, Result, Change, Reset, Dice wording rules: `docs/HISTORY.md` §6 "Terminol
- `export_presets.cfg` has the user's uncommitted edits (a Windows preset). Its `include_filter`
is empty, so Windows builds lack `help/*.txt` and `templates/*.json` (the Linux preset has them).
Tell the user rather than editing their file.
- Still over ~450 lines: inspector_card (591), roll_table (569), expr (544), main_cli, board_tester
(505), builder, roller, tower_board, group_card. Split when next touched.
- Over ~400 lines: inspector_card (593), board_tester (505), main_cli, builder (499), expr (520),
roller, tower_board, group_card, main_rolling (417), describe (408), inspector (407). A size
audit is due. (roll_table was split: RollTableIO.)
- Small ideas from the Perilous Void spread: an empty list shows blank in a sheet (no "none"
default); a value change that should apply when a later value is rolled (Shattered lowers
atmosphere after Gas/Life were already decided) has no clean form.
- Known gaps: ARCHITECTURE.md §7.
## 5. Working on it

View file

@ -185,3 +185,16 @@ export template download approved.
left-drag now selects in Play too.
28. **Audits.** Seven 600+-line files split by parallel agents; tests share `TestBase`. Two
computer crashes mid-run; agents were resumed from their worktrees.
## 12. Book tables (2026-11-10, merged to `main`)
The user's aim, stated while doing this: Table Tarot should handle any random roll table or oracle
procedure it reasonably can, from any tabletop RPG book. Building The Perilous Void's world
generation found four gaps; all four were built:
29. **Scales** (`var_type: "scale"`, `steps`): values stored as step names, read as step numbers in
rules; += / -= move steps; toward(); conditions like "Atmosphere is at least Thin".
30. **Columns** (multi-column tables): `columns`, `column_rolls` (row / each), `cells`; per-column
save and "only if"; per-column highlights on the card.
31. **Thread dice** ("Roll it with 3d10+70 instead") and **thread rerolls** ("Roll again if it
comes up: 96–00"). Answers the open reroll question for threads back into a card.
32. Engine by the main session; UI by three parallel worktree agents (threads, columns, scales).

View file

@ -277,6 +277,37 @@ may pass values with `"with": {"<name>": "<expression>"}`.
it needs no recursion and respects the 10,000-action limit; a halted roll still puts the
values back.
## 3e. Columns (multi-column tables)
Many books print one table with several result columns (Size → Diameter, Gravity, Moons,
Regions). A roll card may have `columns`: `[{name, save_as?, when?}]`. Column 0 is each
result's own `text`; the other columns are the result's `cells` (Strings, full text: `[[refs]]`,
`{@x}`, `{= 2d10*10}`).
- `column_rolls: "row"` (the default): one roll picks the row, and every column reads it.
- `column_rolls: "each"`: "roll 1d10 for each of …". Column 0 is the card's own roll, so its
result's changes and threads happen as usual. Every other column is rolled on its own, the
same way (a thread's dice and rerolls included, §3f). Those extra rolls don't run changes or
threads.
- Left to right, each column's text is saved under its `save_as` before the next one starts,
so a later column's `when` ("only roll Life if Atmosphere is at least Thin") can read it.
A column whose `when` is false (or fails, with a red line) is skipped and saves nothing.
- The node gets `columns: [{name, text, index, value?, skipped?}]` and the summary
"Resources: Rich · Water: Plentiful". Extra column rolls add `roll` why facts with a
`column` key. Code: `core/roll_columns.gd`.
## 3f. Threads that roll with other dice or roll again
Two more thread options (stored on the thread object):
- **`dice`** ("Roll it with 3d10+70 instead"): a ranged roll card is rolled with these dice
(or an expression) instead of its own; its modifier and limits still apply, and a total past
the ends counts as the end result. Other card kinds ignore it (a lint hint).
- **`reroll`** ("Roll again if it comes up: 96–00"): result ids of the target card. When one
comes up, the roll is made again (up to 100 times) and the skipped rolls are listed in a
`reroll` why fact (`skipped: [{value, text}]`). If every result is skipped, the node stops
with "This thread rolls again on every result" (and the board check says so). Repeated
rolls (a count) reroll each roll separately. Code: `RollCards.pick_for()`.
## 4. Expressions
Expressions appear in loop rules, pipe counts, pipe conditions, router cases, `min`/`max`,
@ -368,6 +399,21 @@ statement shows a red marker in the tray and in Build mode rather than stopping
`{@name?}` marker, a bad name an error marker.
- The existing `{@var|Table}`, `{hero}` and `[[refs]]` work as before.
### 5.4 Scales (ordered steps)
A variable card with `var_type: "scale"` lists `steps`, lowest first (Supercold, Cold,
Temperate, Hot, Superhot). Code: `core/scales.gd`, `ExprBase._lit`.
- The value is stored as the step's name, so `{@climate}` shows "Cold".
- In expressions it reads as the step's number (1 = the first step; unset reads 0). A quoted
step name next to it reads as that step's number too: each text literal goes with the
nearest `@variable` (left first), and turns into a number only when that variable is a
scale and the text is one of its steps. So `@atmo >= "Thin"`, `@climate = "Cold"` and
`@climate = "Cold" and @atmo >= "Thin"` all work; `"Cold" + "!"` stays text.
- Saving a number picks that step, stopping at the ends; saving a name matches without
caring about capitals; any other text is kept as it is.
- Changes: `@climate += 1` / `-= 2` move steps; `@climate = toward(@climate, "Temperate")`
moves one step toward a step; `@atmo = max(@atmo, "Medium")` raises to at least,
`min(…)` lowers to at most. `*=` and `/=` are refused.
## 6. Sheet cards
A sheet card holds one template (its single entry's text, multi-line BBCode). On the board it
always shows the template rendered with current values, so a character sheet stays up to
@ -417,14 +463,18 @@ Table keys:
- `inputs`: `[{"name": "tier", "label": "Tier", "default": "1"}]` (any card; `label` and
`default` left out when empty)
- `steps` (scale variable cards, Array of Strings), `columns` and `column_rolls` (§3e)
Entry keys:
- `cells` (Array of Strings, columns 1.. of a card with columns)
- `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>"`,
`"otherwise": true` (left out when the pipe has a `when`) and
`"with": {"<input name>": "<expression>"}` (§3d).
`"with": {"<input name>": "<expression>"}` (§3d), `"dice": "3d10+70"` and
`"reroll": ["<result id>", …]` (§3f).
## 10. Why trace
@ -444,6 +494,7 @@ so history keeps them. The key is left out when a node has no facts. Each fact h
| `effect` | any node whose entry has effects, one per statement that ran | `var` (the real target, `@[…]` resolved), `op` (`=`, `+=`, `-=`, `*=`, `/=`, `reset`), `before`, `after` (null when unset); a prefix reset has `count` instead |
| `when` | the node whose entry has the pipe, one per conditional pipe | `to` (table id), `expr`, `values`, `result`, `error`? |
| `otherwise` | likewise, one per otherwise pipe | `to`, `result` |
| `reroll` | a node a thread rolled again (§3f) | `skipped: [{value, text}]`; `column` on an extra column's roll |
`values` maps each variable the expression reads (`"@luck"`, or a chain name such as `"tier"`) to
its value when it was evaluated (null when unset); indirect `@[…]` names aren't listed. The

View file

@ -53,6 +53,16 @@ A [b]ranged table[/b] gives each result a range of numbers instead of a weight,
Dice can be written `2d6`, `d20`, `3D` or `D3`. A missing count means 1 and missing sides mean 6, so `2D` is 2d6. To add a value to the dice, use a [topic]Roll modifiers[/topic] modifier.
# Columns
A card can give each result more than one part, like a row of a printed table with several columns. A [b]World[/b] card might have the columns Type | Resources | Water | Atmosphere | Life, and each row fills them all in: Garden · Rich · Some · Thin · Yes.
- In Build mode, select the card and press [b]+ Add columns[/b] in the inspector. The first column is each result's own text; the card gets a heading row with the column names.
- Type each column's text right on the card, or in the inspector when a result is selected.
- [b]One roll for the whole row[/b] picks a row and gives you every column of it.
- [b]Roll each column separately[/b] rolls again for every column, for rules like "roll 1d10 for each of Resources, Water, Atmosphere and Life". After the roll, the part each column landed on is lit.
- [b]Save as[/b] keeps a column's text as a value, so later text and rules can use it.
- [b]Only roll this column if[/b] skips a column unless a condition is true, such as "only roll Life if the Atmosphere is at least Thin". Columns are rolled left to right, so a condition can use what an earlier column saved.
- Remove a column with its ×: its text goes from every result.
# Threads
A thread carries the roll from a result to another card.
- In Build mode, drag from the ● at the right of a result onto another card to lay a thread.
@ -66,6 +76,16 @@ A thread carries the roll from a result to another card.
- [b]Otherwise[/b] runs the thread only when none of the result's Only if threads ran.
- [b]Inputs[/b] pass values to a card that declares them.
## Rolling with other dice
A thread can roll a card with numbered ranges using different dice, just this once.
- Type the dice in [b]Roll it with … instead[/b], such as `3d10+70`. Leave it empty to use the card's own dice.
- Example: a World Feature card is rolled with 1d100, but "Multiple features" rolls it twice with 3d10+70, so only the higher results come up.
## Rolling again on some results
A thread can roll its card again when certain results come up.
- Open [b]Roll again if it comes up[/b] and tick those results.
- Example: "Mixed" rolls World Feature twice, rolling again on any 96 or higher, so it never lands on itself.
[demo]threads[/demo]
# Roll modifiers
@ -119,6 +139,18 @@ A spread can remember [b]values[/b] between rolls, such as Luck, Gold or the cur
## Conditions
Conditions are used by Only if threads, branches, repeats and Show only if. In plain words they read "Luck is at least 2". As text: `@luck >= 2`, `@town = "Saltmere"`, `@gold > 0 and @luck < 3`.
# Scales
A [b]Scale[/b] is a value that moves along steps in order, lowest first, such as a Climate that runs [b]Supercold, Cold, Temperate, Hot, Superhot[/b]. Add one with [b]+ Card ▾ → Scale (ordered steps)[/b], then list its steps, one per line, and pick the step it starts at. The card shows the current step, and the row of steps under it shows where that sits.
- Changes move it a step at a time and stop at the ends, so a result such as [i]Unexpectedly warmer[/i] can say [b]Climate 1 step up[/b]. Other changes: [b]Climate 2 steps down[/b], [b]Set Climate to Hot[/b], [b]Climate 1 step toward Temperate[/b], [b]Atmosphere at least Medium[/b] (raises it if it's lower) and [b]Atmosphere at most Thin[/b] (lowers it if it's higher).
- Conditions compare steps by their order: a thread can go [b]only if Atmosphere is at least Thin[/b], which is true for Thin and every step above it.
- Text shows the step's name: `{@climate}` reads "Cold".
## Writing scales as text
- `@climate += 1` and `@climate -= 1` move it, `@climate = "Hot"` sets it.
- `@climate = toward(@climate, "Temperate")` moves it one step toward Temperate.
- `@atmo = max(@atmo, "Medium")` raises it to at least Medium; `min` lowers it to at most.
- `@atmo >= "Thin"` is a condition.
# Logic cards
Besides roll tables and choices, [b]+ Card ▾[/b] adds:
- [b]Check card[/b]: rolls dice plus a modifier against a target, such as 2d6 + Skill against 8, and follows its Success or Failure result.

View file

@ -129,7 +129,7 @@ static func _canon_table(td: Dictionary) -> Dictionary:
for e in src_entries:
entries.append(_canon_entry(e))
t["entries"] = entries
_keep(td, t, ["color", "w", "list_h", "roll_floor", "roll_ceiling", "deck_empty_text"])
_keep(td, t, ["color", "w", "list_h", "roll_floor", "roll_ceiling", "deck_empty_text", "columns", "column_rolls", "steps"])
return t
@ -180,11 +180,11 @@ static func _canon_entry(ev: Variant) -> Dictionary:
var wv := _canon_with(p.get("with"))
if not wv.is_empty():
np["with"] = wv
_keep(p, np, ["color", "combine", "pause"])
_keep(p, np, ["color", "combine", "pause", "dice", "reroll"])
pipes.append(np)
if not pipes.is_empty():
e["pipes"] = pipes
_keep(ed, e, ["page", "image"])
_keep(ed, e, ["page", "image", "cells"])
if ed.get("cost") is Dictionary:
e["cost"] = ed["cost"]
return e

234
tests/test_book_tables.gd Normal file
View file

@ -0,0 +1,234 @@
extends TestBase
## Book-table features in the engine: scale values, cards with columns, and
## threads that roll with other dice or roll again on some results.
## Run: godot --headless --path . -s res://tests/test_book_tables.gd -- --sample
func _init() -> void:
_test_scales()
_test_scale_effects()
await _test_columns_row()
await _test_columns_each()
_test_dice_override()
_test_reroll()
_test_save_load()
_test_lint()
finish()
const CLIMATE := ["Supercold", "Cold", "Temperate", "Hot", "Superhot"]
func _board() -> TowerBoard:
var b := TowerBoard.new()
var v := RollTable.create("variable", "v_climate", "Climate", "scale")
v.var_name = "climate"
v.steps.assign(CLIMATE)
b.tables.append(v)
var d := RollTable.create("variable", "v_atmo", "Atmosphere", "scale")
d.var_name = "atmo"
d.steps.assign(["None", "Thin", "Medium", "Dense"])
b.tables.append(d)
return b
func _ctx(b: TowerBoard, seed_value: int = 1) -> RollContext:
var rng := RandomNumberGenerator.new()
rng.seed = seed_value
return Roller.new_context(b, rng, {}, {})
func _ev(src: String, ctx: RollContext) -> Variant:
return Expr.evaluate(src, ctx)["value"]
func _test_scales() -> void:
var b := _board()
var ctx := _ctx(b)
ctx.save("@climate", 2)
_eq(ctx.get_value("@climate"), "Cold", "a number saves as the step at that position")
ctx.save("@climate", "temperate")
_eq(ctx.get_value("@climate"), "Temperate", "a step name saves in its own spelling")
ctx.save("@climate", 9)
_eq(ctx.get_value("@climate"), "Superhot", "past the top stops at the last step")
ctx.save("@climate", -3)
_eq(ctx.get_value("@climate"), "Supercold", "below the bottom stops at the first step")
ctx.save("@climate", "Cold")
_eq(_ev("@climate", ctx), 2, "a scale reads as its step's number")
_eq(_ev("@climate < \"Temperate\"", ctx), true, "a step name beside a scale reads as its number")
_eq(_ev("@climate >= \"Hot\"", ctx), false, "comparing steps")
_eq(_ev("toward(@climate, \"Temperate\")", ctx), 3, "toward moves one step")
_eq(_ev("@atmo >= \"Thin\"", ctx), false, "an unset scale reads as 0, below every step")
ctx.save("@atmo", "Medium")
_eq(_ev("@climate = \"Cold\" and @atmo >= \"Thin\"", ctx), true, "each step name goes with the scale beside it")
_eq(_ev("\"Cold\" + \"!\"", ctx), "Cold!", "text with no scale beside it stays text")
var text := TextExpander.render("It is {@climate}.", ctx)
_check(text.contains("Cold"), "{@climate} shows the step's name")
func _test_scale_effects() -> void:
var b := _board()
var ctx := _ctx(b)
Effects.run("@climate = \"Hot\"", ctx)
Effects.run("@climate += 1", ctx)
_eq(ctx.get_value("@climate"), "Superhot", "+= moves up a step")
Effects.run("@climate += 1", ctx)
_eq(ctx.get_value("@climate"), "Superhot", "and stops at the top")
var log := Effects.run("@climate -= 2", ctx)
_eq(ctx.get_value("@climate"), "Temperate", "-= moves down")
_check(str(log[0]["text"]).contains("Temperate") and str(log[0]["text"]).contains("steps"), "the log names the steps: %s" % log[0]["text"])
Effects.run("@climate = 1", ctx)
Effects.run("@climate = toward(@climate, \"Temperate\")", ctx)
_eq(ctx.get_value("@climate"), "Cold", "toward the middle from the bottom")
Effects.run("@atmo = \"Thin\"; @atmo = max(@atmo, \"Medium\")", ctx)
_eq(ctx.get_value("@atmo"), "Medium", "raise to at least Medium")
var bad := Effects.run("@climate *= 2", ctx)
_check(bad[0].get("error", false), "a scale can't be multiplied")
## World type card: 1d10, 3 results, columns Resources | Water | Life.
func _type_card(rolls: String) -> RollTable:
var t := RollTable.new("type", "Oceanic")
t.dice = "1d10"
t.column_rolls = rolls
t.columns = [{"name": "Resources", "save_as": "@res"}, {"name": "Water", "save_as": "@water"},
{"name": "Life", "save_as": "@life", "when": "@water != \"None\""}]
var rows := [[1, 3, "Poor", "None", "None"], [4, 9, "Rich", "Plentiful", "Simple"], [10, 10, "Ultra-Rich", "Maximal", "Complex"]]
for r: Array in rows:
var e := TableEntry.new("e%d" % r[0], r[2])
e.has_range = true
e.range_lo = r[0]
e.range_hi = r[1]
e.cells.assign([r[3], r[4]])
t.entries.append(e)
return t
func _test_columns_row() -> void:
var b := TowerBoard.new()
b.tables.append(_type_card(RollTable.COLUMNS_ROW))
for s in 20:
var ctx := _ctx(b, s)
var node := await Roller.roll_async(b, "type", ctx)
var e: TableEntry = node["entry"]
_eq(ctx.get_value("@res"), Formatter.strip_tags(e.text), "row: column 0 saves the result's text")
if e.cells[0] == "None":
_eq(ctx.get_value("@life"), null, "a skipped column saves nothing")
_check(bool((node["columns"] as Array)[2].get("skipped", false)), "and is marked skipped")
else:
_eq(ctx.get_value("@life"), e.cells[1], "row: every column reads the same result")
_check(str(node["summary"]).begins_with("Resources: "), "the summary names the columns: %s" % node["summary"])
func _test_columns_each() -> void:
var b := TowerBoard.new()
b.tables.append(_type_card(RollTable.COLUMNS_EACH))
var mixed := false
for s in 60:
var ctx := _ctx(b, s)
var node := await Roller.roll_async(b, "type", ctx)
var cols: Array = node["columns"]
if int(cols[0]["index"]) != int(cols[1]["index"]):
mixed = true
var columns_rolled := (node["why"] as Array).filter(func(f: Dictionary) -> bool: return str(f.get("column", "")) != "")
_check(columns_rolled.size() >= 1, "each: the other columns are rolled with why facts")
_check(mixed, "each: columns can land on different rows")
## Feature: 1d100 card, the thread rolls it with 3d10+70.
func _feature_board() -> TowerBoard:
var b := TowerBoard.new()
var start := RollTable.new("start", "Start")
var e := TableEntry.new("s1", "Go")
e.add_pipe("feat")
e.set_pipe_dice("feat", "3d10+70")
start.entries.append(e)
var feat := RollTable.new("feat", "Feature")
for r: Array in [[1, 70, "Nothing"], [71, 95, "Something"], [96, 100, "Multiple"]]:
var x := TableEntry.new("f%d" % r[0], r[2])
x.has_range = true
x.range_lo = r[0]
x.range_hi = r[1]
feat.entries.append(x)
b.tables.append(start)
b.tables.append(feat)
return b
func _test_dice_override() -> void:
var b := _feature_board()
var low := 100
for s in 80:
var tree := Roller.roll(b, "start", _ctx(b, s).rng)
var kid: Dictionary = tree["children"][0]
low = mini(low, int(kid["value"]))
_check(str((kid["why"] as Array)[0]["dice"]) == "3d10+70", "the why fact names the thread's dice")
_check(low >= 73, "3d10+70 never rolls below 73 (lowest %d)" % low)
_eq(DescribeCards.pipe(b.get_table("start").entries[0], "feat", b), "with 3d10+70", "the thread label says the dice")
func _test_reroll() -> void:
var b := _feature_board()
var e := b.get_table("start").entries[0]
e.set_pipe_dice("feat", "")
e.set_pipe_reroll("feat", ["f96"])
var skipped := false
for s in 200:
var tree := Roller.roll(b, "start", _ctx(b, s).rng)
var kid: Dictionary = tree["children"][0]
_check((kid["entry"] as TableEntry).id != "f96", "a result the thread rolls again on never stays")
for f: Dictionary in kid.get("why", []):
if f["type"] == "reroll":
skipped = true
_check(skipped, "a reroll why fact is recorded")
_eq(DescribeCards.pipe(e, "feat", b), "again on 96–00", "the label lists the numbers")
e.set_pipe_reroll("feat", ["f1", "f71", "f96"])
var tree2 := Roller.roll(b, "start", _ctx(b).rng)
_eq(str(tree2["children"][0]["stop"]), RollCards.ALL_REROLLED, "rolling again on everything stops")
func _test_save_load() -> void:
var b := _board()
b.tables.append(_type_card(RollTable.COLUMNS_EACH))
for t in _feature_board().tables:
b.tables.append(t)
b.get_table("start").entries[0].set_pipe_reroll("feat", ["f96"])
var text := JSON.stringify(b.to_dict())
var back := TowerBoard.new()
back.load_dict(JSON.parse_string(text))
_eq(back.get_table("v_climate").steps, CLIMATE, "scale steps round-trip")
var t := back.get_table("type")
_eq(t.column_rolls, RollTable.COLUMNS_EACH, "column rolls round-trip")
_eq(t.column_names(), ["Resources", "Water", "Life"], "columns round-trip")
_eq(str(t.columns[2].get("when", "")), "@water != \"None\"", "a column's condition round-trips")
_eq(t.entries[1].cells, ["Plentiful", "Simple"], "cells round-trip")
var se := back.get_table("start").entries[0]
_eq(se.dice_for("feat"), "3d10+70", "thread dice round-trip")
_eq(se.reroll_for("feat"), ["f96"], "thread rerolls round-trip")
var canon := JsonIO.canonical(JSON.parse_string(text))
var again := TowerBoard.new()
again.load_dict(canon)
_eq(again.get_table("type").entries[1].cells, ["Plentiful", "Simple"], "import keeps cells")
_eq(again.get_table("start").entries[0].reroll_for("feat"), ["f96"], "import keeps rerolls")
_eq(again.get_table("v_climate").steps, CLIMATE, "import keeps steps")
func _test_lint() -> void:
var b := _feature_board()
var e := b.get_table("start").entries[0]
e.set_pipe_reroll("feat", ["f1", "f71", "f96"])
var msgs := Roller.lint_pipes(b).map(func(i: Dictionary) -> String: return str(i["message"]))
_check(msgs.any(func(m: String) -> bool: return m.contains("every result")), "lint: rerolling everything")
var s := RollTable.create("variable", "v", "Odd", "scale")
s.steps.assign(["Only"])
b.tables.append(s)
msgs = Roller.lint_pipes(b).map(func(i: Dictionary) -> String: return str(i["message"]))
_check(msgs.any(func(m: String) -> bool: return m.contains("two steps")), "lint: a one-step scale")
var b2 := TowerBoard.new()
b2.tables.append(_type_card(RollTable.COLUMNS_EACH))
var names := Builder.known_values(b2).map(func(v: Dictionary) -> String: return str(v["name"]))
_check(names.has("@water") and names.has("@life"), "column save names are known values: %s" % str(names))
_eq(Dice.roll_problem("3d10+70"), "", "plain dice roll")
_eq(Dice.roll_problem("2d6 + @luck"), "", "a rule with dice rolls")
_eq(Dice.roll_problem("bogus"), "it doesn't roll any dice", "a word isn't dice")
_check(Dice.roll_problem("@luck + 2") != "", "a rule with no dice isn't dice")

View file

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

View file

@ -13,6 +13,7 @@ func _init() -> void:
_test_condition_round_trips()
_test_condition_not_ok()
_test_known_values()
_test_scales()
finish()
@ -204,3 +205,46 @@ func _test_known_values() -> void:
_check(not by.has("i") and not by.has("option"), "no loop, no dynamic pick")
_check(not by.has("@[option]") and not by.has("@x_*"), "no indirect or prefix targets")
_eq(Builder.known_values(null), [] as Array[Dictionary], "null spread")
# ---------------------------------------------------------------- scales
func _scale_board() -> TowerBoard:
var b := TowerBoard.new()
var c := RollTable.create(RollTable.KIND_VARIABLE, "v_climate", "Climate", RollTable.VAR_SCALE)
c.steps.assign(["Supercold", "Cold", "Temperate", "Hot", "Superhot"])
b.tables.append(c)
return b
func _test_scales() -> void:
var b := _scale_board()
_eq(Builder.parse_effect("@climate += 1", b), {"ok": true, "op": "step_up", "var": "@climate", "amount": "1"}, "step up on a scale")
_eq(Builder.parse_effect("@climate -= 2", b), {"ok": true, "op": "step_down", "var": "@climate", "amount": "2"}, "step down")
_eq(Builder.parse_effect("@climate += 1"), {"ok": true, "op": "add", "var": "@climate", "amount": "1"}, "without the board it's add")
_eq(Builder.parse_effect("@luck += 1", b), {"ok": true, "op": "add", "var": "@luck", "amount": "1"}, "not a scale: add")
_eq(Builder.parse_effect("@climate = \"Hot\"", b), {"ok": true, "op": "set", "var": "@climate", "amount": "\"Hot\""}, "set a step")
_eq(Builder.parse_effect("@climate = toward(@climate, \"Temperate\")"),
{"ok": true, "op": "toward", "var": "@climate", "amount": "Temperate"}, "toward")
_eq(Builder.parse_effect("@atmo = max(@atmo, \"Medium\")"), {"ok": true, "op": "at_least", "var": "@atmo", "amount": "Medium"}, "at least")
_eq(Builder.parse_effect("@atmo = min(@atmo, 'Thin')"), {"ok": true, "op": "at_most", "var": "@atmo", "amount": "Thin"}, "at most")
_eq(Builder.parse_effect("@atmo = max(@other, \"Medium\")")["op"], "set", "max of another value stays set")
_eq(Builder.parse_effect("@atmo = max(@atmo, 0)")["op"], "set", "max with a number stays set")
_eq(Builder.effect_text({"op": "toward", "var": "@climate", "amount": "Temperate"}), "@climate = toward(@climate, \"Temperate\")", "toward text")
_eq(Builder.effect_text({"op": "step_down", "var": "@climate", "amount": "1"}), "@climate -= 1", "step down text")
_eq(Builder.effect_text({"op": "at_most", "var": "@climate", "amount": ""}), "", "no step: no text")
for m: Dictionary in [
{"ok": true, "op": "step_up", "var": "@climate", "amount": "1"},
{"ok": true, "op": "step_down", "var": "@climate", "amount": "3"},
{"ok": true, "op": "toward", "var": "@climate", "amount": "Temperate"},
{"ok": true, "op": "at_least", "var": "@climate", "amount": "Cold"},
{"ok": true, "op": "at_most", "var": "@climate", "amount": "Semi-arid"},
{"ok": true, "op": "set", "var": "@climate", "amount": "\"Hot\""}]:
_eq(Builder.parse_effect(Builder.effect_text(m), b), m, "scale round trip " + str(m["op"]))
var kinds := {}
for k: Dictionary in Builder.known_values(b):
kinds[k["name"]] = k["kind"]
_eq(kinds.get("@climate"), "scale", "known_values: a scale card's kind is scale")
var fresh := RollTable.create(RollTable.KIND_VARIABLE, "s", "Mood", RollTable.VAR_SCALE)
_eq(fresh.steps, ["Low", "Medium", "High"], "a new scale gets default steps")
_eq(fresh.initial, "Low", "and starts at the first")

View file

@ -18,6 +18,7 @@ func _init() -> void:
_test_why_from_rolls()
_test_fallbacks()
_test_rules_view()
_test_scales()
finish()
@ -341,3 +342,26 @@ func _test_rules_view() -> void:
_eq(StateStore.new(dir).rules_view(), "text", "kept in the state file")
st.set_rules_view("plain")
st.save()
# ---------------------------------------------------------------- scales
func _test_scales() -> void:
var b := _board()
var c := _var_card("v_climate", "Climate", "climate", RollTable.VAR_SCALE)
c.steps.assign(["Supercold", "Cold", "Temperate", "Hot", "Superhot"])
b.tables.append(c)
var a := _var_card("v_atmo", "Atmosphere", "atmo", RollTable.VAR_SCALE)
a.steps.assign(["None", "Thin", "Medium", "Dense"])
b.tables.append(a)
_eq(Describe.effect("@climate += 1", b), "Climate 1 step up", "step up")
_eq(Describe.effect("@climate -= 2", b), "Climate 2 steps down", "steps down")
_eq(Describe.effect("@climate += -1", b), "Climate 1 step down", "a negative step up")
_eq(Describe.effect("@climate = \"Hot\"", b), "Climate = Hot", "set a step")
_eq(Describe.effect("@climate = 2", b), "Climate = Cold", "a step's number reads as its name")
_eq(Describe.effect("@climate = toward(@climate, \"Temperate\")", b), "Climate 1 step toward Temperate", "toward")
_eq(Describe.effect("@atmo = max(@atmo, \"Medium\")", b), "Atmosphere at least Medium", "at least")
_eq(Describe.effect("@atmo = min(@atmo, \"Thin\")", b), "Atmosphere at most Thin", "at most")
_eq(Describe.effect("@luck += 1", b), "Luck +1", "not a scale: as before")
_eq(Describe.condition("@atmo >= \"Thin\"", b), "Atmosphere is at least Thin", "condition at least a step")
_eq(Describe.condition("@atmo = 3", b), "Atmosphere is Medium", "a number in a condition reads as the step")

222
tests/test_ui_columns.gd Normal file
View file

@ -0,0 +1,222 @@
extends TestBase
## Cards with columns on the spread and in the inspector: the header and the
## cells, the lit cells after a roll, inline cell editing, and the inspector's
## Columns section (add, rename, move, remove, roll mode, save as, only if)
## with the result's cell fields, all undoable.
## Run: godot --headless --path . -s res://tests/test_ui_columns.gd -- --sample
var insp: Inspector
func _init() -> void:
if not await start_main():
return
main.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT)
main.size = Vector2(1440, 900)
insp = main.inspector
await _load()
await _test_card()
await _test_lit_cells()
await _test_real_roll()
await _test_build_cells()
await _test_inspector_columns()
await _test_result_cells()
finish()
func _board_dict() -> Dictionary:
return {"format_version": 2, "id": "cols-test", "name": "Columns test", "tables": [
{"id": "world", "name": "World", "x": 40, "y": 40, "column_rolls": "each",
"columns": [{"name": "Type"}, {"name": "Resources", "save_as": "@res"}, {"name": "Water"}, {"name": "Life", "when": "@res == \"Rich\""}],
"entries": [
{"id": "e1", "text": "Rocky", "cells": ["Poor", "None", "No"]},
{"id": "e2", "text": "Ocean", "cells": ["Fair", "Plentiful", "Yes"]},
{"id": "e3", "text": "Garden", "cells": ["Rich", "Some", "Yes"]}]},
{"id": "rowcard", "name": "Row card", "x": 700, "y": 40,
"columns": [{"name": "Name"}, {"name": "Trait"}],
"entries": [{"id": "e1", "text": "Ana", "cells": ["Bold"]}]},
{"id": "plain", "name": "Plain", "x": 40, "y": 400,
"entries": [{"id": "e1", "text": "One"}, {"id": "e2", "text": "Two"}]},
]}
func _load() -> void:
main.data.load_dict(_board_dict())
main.lit_entries.clear()
main.lit_pipes.clear()
main.lit_texts.clear()
main.lit_columns.clear()
main.persistent_vars.clear()
main.set_mode(Main.Mode.PLAY)
main._rebuild_cards()
main.clear_inspector()
await _frames(4)
func _t(id: String) -> RollTable:
return main.data.get_table(id)
func _cells(tid: String, eid: String) -> Array:
return main.card_for(tid).rows_ui.columns_ui.cells.get(eid, [])
func _header_names(card: TableCard) -> Array:
var out: Array = []
for c in card.find_children("*", "MarginContainer", true, false):
if c.has_meta("columns_header"):
for l in c.find_children("*", "Label", true, false):
out.append((l as Label).text)
return out
# ---------- The card ----------
func _test_card() -> void:
print("Card")
var card := main.card_for("world")
_eq(_header_names(card), ["Type", "Resources", "Water", "Life"], "the header names every column")
_eq(_header_names(main.card_for("plain")), [], "a plain card has no header")
var cs := _cells("world", "e2")
_eq(cs.size(), 3, "a row shows a cell per extra column")
_eq((cs[1]["label"] as RichTextLabel).text, "Plentiful", "a cell shows its text")
_check(card.card_width() > main.card_for("plain").card_width() + 3 * 100.0, "a card with columns is wider")
var text: RichTextLabel = card.rows_ui.parts["e2"]["text"]
_eq(text.text, "Ocean", "the row's own text is column 0")
func _test_lit_cells() -> void:
print("Lit cells")
var card := main.card_for("world")
main.lit_entries["world:e1"] = true
main.lit_texts["world:e1"] = "Type: Rocky · Resources: Rich · Water: Plentiful"
main.lit_columns["world:e1"] = [{"name": "Type", "text": "Rocky", "index": 0},
{"name": "Resources", "text": "Rich", "index": 2}, {"name": "Water", "text": "Plentiful", "index": 1},
{"name": "Life", "text": "", "index": 0, "skipped": true}]
card.refresh_lit()
var text: RichTextLabel = card.rows_ui.parts["e1"]["text"]
_eq(text.text, "Rocky", "the lit row shows column 0, not the whole summary")
var rich: Dictionary = _cells("world", "e3")[0]
_check(bool((rich["box"] as Control).get_meta("lit", false)), "each column lights the cell it landed on")
_eq((rich["label"] as RichTextLabel).text, "Rich", "with the rolled text")
_check(bool((_cells("world", "e2")[1]["box"] as Control).get_meta("lit", false)), "a second column lights another row")
_check(not bool((_cells("world", "e1")[0]["box"] as Control).get_meta("lit", false)), "the lit row's own cell for that column isn't lit")
_check(not bool((_cells("world", "e1")[2]["box"] as Control).get_meta("lit", false)), "a skipped column lights nothing")
main.lit_entries.clear()
main.lit_texts.clear()
main.lit_columns.clear()
card.refresh_lit()
_check(not bool((rich["box"] as Control).get_meta("lit", false)), "clearing the roll unlights the cells")
func _test_real_roll() -> void:
print("A real roll")
main.rolling.start_roll("rowcard")
for i in 200:
if main.current.get("done", false):
break
await _frames()
_check(main.is_entry_lit("rowcard", "e1"), "the row lights")
var card := main.card_for("rowcard")
_eq((card.rows_ui.parts["e1"]["text"] as RichTextLabel).text, "Ana", "the row shows its own text")
_eq((_cells("rowcard", "e1")[0]["label"] as RichTextLabel).text, "Bold", "and its cell")
_eq(main.lit_text("rowcard", "e1"), "Name: Ana · Trait: Bold", "(the summary names the columns)")
func _test_build_cells() -> void:
print("Build cells")
main.set_mode(Main.Mode.BUILD)
await _frames(2)
var card := main.card_for("world")
_check(card.card_width() > TableCard.BUILD_WIDTH + 3 * 100.0, "Build keeps the room for the columns")
var cs := _cells("world", "e1")
var le: LineEdit = cs[1]["edit"]
_eq(le.text, "None", "Build shows a field per cell")
main.undo_redo._commit_edits()
le.text = "A little"
le.text_changed.emit("A little")
main.undo_redo._commit_edits()
_eq(_t("world").find_entry("e1").cells[1], "A little", "typing in a cell edits it")
main.undo_redo.undo()
await _frames(2)
_eq(_t("world").find_entry("e1").cells[1], "None", "undo puts the cell back")
func _test_inspector_columns() -> void:
print("Inspector columns")
var t := _t("plain")
main.select_card("plain")
await _frames(2)
main.undo_redo._commit_edits()
_press("+ Add columns")
_eq(t.column_names(), ["Result", "Column 2"] as Array[String], "Add columns makes Result and one more")
_eq(t.entries[0].cells, ["" ] as Array[String], "every result gets a cell")
_press("+ Add column")
_eq(t.columns.size(), 3, "+ Add column")
_eq(t.entries[1].cells.size(), 2, "the cells keep in step")
var nm: LineEdit = insp.fields["column_name_1"]
nm.text = "Water"
nm.text_changed.emit("Water")
_eq(t.column_names()[1], "Water", "renaming a column")
_eq(_header_names(main.card_for("plain"))[1], "Water", "the card's header follows")
t.entries[0].cells.assign(["wet", "big"])
(insp.fields["column_name_2"] as LineEdit).text_changed.emit("Size")
InspectorColumns.move_column(t, 2, -1)
insp.wrote(t, false, true)
_eq(t.column_names(), ["Result", "Size", "Water"] as Array[String], "moving a column")
_eq(t.entries[0].cells, ["big", "wet"] as Array[String], "moves its cells too")
InspectorColumns.remove_column(t, 1)
insp.wrote(t, false, true)
_eq(t.column_names(), ["Result", "Water"] as Array[String], "removing a column")
_eq(t.entries[0].cells, ["wet"] as Array[String], "removes its cell from every result")
var mode: OptionButton = insp.fields["column_rolls"]
mode.item_selected.emit(1)
_eq(t.column_rolls, RollTable.COLUMNS_EACH, "Roll each column separately")
(insp.fields["column_save_1"] as ValuePicker).choose("@water")
_eq(str(t.columns[1].get("save_as", "")), "@water", "Save as picks a value")
main.undo_redo._commit_edits()
var cond: ConditionBuilder = insp.fields["column_when_1"]
cond.changed.emit("@luck >= 2")
_eq(str(t.columns[1].get("when", "")), "@luck >= 2", "Only if sets the column's condition")
main.undo_redo._commit_edits()
main.undo_redo.undo()
await _frames(2)
# Quick edits to one card merge into one step (MainHistory), so undo may go further back.
_check(not JSON.stringify(_t("plain").to_dict()).contains("@luck"), "undo takes the condition back")
for i in 12:
main.undo_redo.undo()
await _frames()
if _t("plain").columns.is_empty():
break
_check(_t("plain").columns.is_empty() and _t("plain").entries[0].cells.is_empty(), "undo goes back to a plain card")
main.select_card("plain")
await _frames(2)
_press("+ Add columns")
InspectorColumns.remove_column(_t("plain"), 1)
_check(_t("plain").columns.is_empty() and _t("plain").entries[0].cells.is_empty(), "removing the last extra column turns columns off")
func _test_result_cells() -> void:
print("Result cells")
main.select_result("world", "e2")
await _frames(2)
_check(insp.fields.has("cell_1") and insp.fields.has("cell_3"), "the result shows a field per extra column")
var le: LineEdit = insp.fields["cell_2"]
_eq(le.text, "Plentiful", "with the cell's text")
main.undo_redo._commit_edits()
le.text_changed.emit("Seas")
main.undo_redo._commit_edits()
_eq(_t("world").find_entry("e2").cells[1], "Seas", "editing it changes the cell")
var card_edit: LineEdit = _cells("world", "e2")[1]["edit"]
_eq(card_edit.text, "Seas", "and the card")
main.undo_redo.undo()
await _frames(2)
_eq(_t("world").find_entry("e2").cells[1], "Plentiful", "undo")
func _press(label: String) -> void:
for b in insp.find_children("*", "Button", true, false):
if (b as Button).text == label:
(b as Button).pressed.emit()
return
_check(false, "no button %s" % label)

View file

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

191
tests/test_ui_scales.gd Normal file
View file

@ -0,0 +1,191 @@
extends TestBase
## Scale values in the UI (Scales): making one (+ Card, the inspector's steps
## and starting step, switching type), showing one (the card's value and row
## of steps, the Variables tab), the effect and condition rows for a scale,
## and the help topic.
## Run: godot --headless --path . -s res://tests/test_ui_scales.gd -- --sample
const CLIMATE := ["Supercold", "Cold", "Temperate", "Hot", "Superhot"]
var insp: Inspector
func _init() -> void:
if not await start_main():
return
main.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT)
main.size = Vector2(1440, 900)
main.set_mode(Main.Mode.BUILD)
insp = main.inspector
await _load()
await _test_add_card()
await _test_inspector_fields()
await _test_settings_dialog()
await _test_card_shows_steps()
await _test_effect_rows()
await _test_condition_rows()
_test_help()
finish()
func _load() -> void:
main.data.load_dict({"format_version": 2, "id": "scales-test", "name": "Scales test", "tables": [
{"id": "climate", "name": "Climate", "kind": "variable", "var_name": "climate", "var_type": "scale",
"steps": CLIMATE, "initial": "Temperate", "x": 40, "y": 40, "entries": []},
{"id": "luck", "name": "Luck", "kind": "variable", "var_name": "luck", "var_type": "number", "initial": "2",
"x": 40, "y": 300, "entries": []},
{"id": "weather", "name": "Weather", "x": 340, "y": 40, "entries": [
{"id": "e1", "text": "Unexpectedly warmer", "effects": "@climate += 1", "pipes": [{"table": "luck_t", "when": "@climate >= \"Cold\""}]},
{"id": "e2", "text": "Calm"}]},
{"id": "luck_t", "name": "Lucky", "x": 700, "y": 40, "entries": [{"id": "e1", "text": "Yes"}]},
]})
main.persistent_vars.clear()
main._rebuild_cards()
main.clear_inspector()
await _frames(4)
func _t(id: String) -> RollTable:
return main.data.get_table(id)
func _test_add_card() -> void:
var found := false
for k: Array in MainEditing.ADD_KINDS:
found = found or (k[1] == RollTable.KIND_VARIABLE and k[2] == RollTable.VAR_SCALE and str(k[0]).begins_with("Scale"))
_check(found, "+ Card lists Scale (ordered steps)")
var t := main.editing.add_table(RollTable.KIND_VARIABLE, RollTable.VAR_SCALE)
_check(t.is_scale() and t.steps == (["Low", "Medium", "High"] as Array[String]) and t.initial == "Low", "a new scale has Low, Medium, High and starts Low")
main.data.remove_table(t.id)
main._rebuild_cards()
await _frames(2)
func _test_inspector_fields() -> void:
main.select_card("climate")
await _frames(2)
var te := insp.fields.get("steps") as TextEdit
_check(te != null and te.text == "\n".join(CLIMATE), "the inspector lists the steps, one per line")
var start := insp.fields.get("initial") as OptionButton
_check(start != null and start.item_count == 5 and start.selected == 2, "the starting value is a dropdown of the steps, on Temperate")
start.item_selected.emit(3)
_eq(_t("climate").initial, "Hot", "picking a step sets the starting value")
_eq(insp.apply_settings({"steps": "Only one"}), "A scale needs at least two steps, one per line.", "one step isn't a scale")
te.text = "Cold\nMild\nWarm"
te.text_changed.emit()
_eq(_t("climate").steps, ["Cold", "Mild", "Warm"] as Array[String], "editing the lines sets the steps")
_eq(_t("climate").initial, "Cold", "a starting step that's gone falls back to the first")
_eq((insp.fields.get("initial") as OptionButton).item_count, 3, "the starting dropdown follows the steps")
insp.apply_settings({"steps": "Semi-arid\nWet"})
_eq(_t("climate").initial, "\"Semi-arid\"", "a step with a dash starts as quoted text")
_eq(Roller.variable_display(main.data, main.persistent_vars, _t("climate"))["text"], "Semi-arid", "and still shows as the step")
# Switching types.
main.select_card("luck")
await _frames(2)
insp.apply_settings({"var_type": "scale"}, true)
_check(_t("luck").is_scale() and _t("luck").steps.size() == 3 and _t("luck").initial == "Low", "a number turned into a scale gets the default steps")
insp.apply_settings({"var_type": "number", "initial": ""}, true)
_eq(_t("luck").var_type, "number", "and back")
insp.apply_settings({"initial": "2"})
_t("climate").steps.assign(CLIMATE)
_t("climate").initial = "Temperate"
main.mark_dirty()
await _frames(2)
func _test_settings_dialog() -> void:
var d := TableSettingsDialog.new(_t("climate"))
main.add_child(d)
await _frames(1)
_check(d._kind._steps_field.visible and d._kind._steps.text == "\n".join(CLIMATE), "the settings dialog shows the steps for a scale")
_eq(d.settings()["steps"], "\n".join(CLIMATE), "and passes them on")
d.queue_free()
d = TableSettingsDialog.new(_t("luck"))
main.add_child(d)
await _frames(1)
_check(not d._kind._steps_field.visible and not d.settings().has("steps"), "but not for a number")
d.queue_free()
await _frames(1)
func _test_card_shows_steps() -> void:
main.set_variable("climate", "4")
await _frames(2)
_eq(main.persistent_vars["climate"]["value"], "Hot", "typing a step number in the Variables tab stores the step")
main.set_variable("climate", "cold")
_eq(main.persistent_vars["climate"]["value"], "Cold", "a name is matched without caring about capitals")
main._rebuild_cards()
await _frames(2)
var ui := main.card_for("climate").value_ui
_eq(ui.var_value.text, "Cold", "the card shows the current step")
_eq(ui.steps_row.get_child_count(), 5, "and every step in a row")
var lit := []
for chip in ui.steps_row.get_children():
var l := chip.get_child(0) as Label
if (chip as PanelContainer).get_theme_stylebox("panel").bg_color.a > 0.0:
lit.append(l.text)
_eq(lit, ["Cold"], "with the current one marked")
main.clear_variable("climate")
await _frames(2)
func _test_effect_rows() -> void:
main.select_result("weather", "e1")
await _frames(2)
var fx := insp.effects
var e := _t("weather").find_entry("e1")
_eq([fx.rows[0]["op"], fx.rows[0]["amount"]], ["step_up", "1"], "@climate += 1 is a Move up row")
_check(InspectorKit.find_tagged(fx, "res.fx.0.amount") != null, "with a count of steps")
fx.set_row_amount(0, "2")
_eq(e.effects, "@climate += 2", "Move up 2 steps")
fx.set_row_op(0, "step_down")
_eq(e.effects, "@climate -= 2", "Move down")
fx.set_row_op(0, "toward")
_eq(e.effects, "@climate = toward(@climate, \"Supercold\")", "Move toward starts at the first step")
_check(InspectorKit.find_tagged(fx, "res.fx.0.step") is OptionButton, "and picks the step from a dropdown")
fx.set_row_step(0, "Temperate")
_eq(e.effects, "@climate = toward(@climate, \"Temperate\")", "picking a step writes it")
fx.set_row_op(0, "at_least")
_eq(e.effects, "@climate = max(@climate, \"Temperate\")", "Raise to at least keeps the step")
fx.set_row_op(0, "at_most")
_eq(e.effects, "@climate = min(@climate, \"Temperate\")", "Lower to at most")
fx.set_row_op(0, "set")
_eq(e.effects, "@climate = \"Temperate\"", "Set to a step")
_eq(Describe.effect(e.effects, main.data), "Climate = Temperate", "reads in plain words")
fx.add_row()
fx.set_row_var(1, "@climate")
_eq(e.effects, "@climate = \"Temperate\"\n@climate += 1", "a new row on a scale is Move up 1")
fx.set_row_var(1, "@luck")
_eq(e.effects, "@climate = \"Temperate\"\n@luck += 1", "on a number it's Add again")
fx.remove_row(1)
e.effects = "@climate += 1"
main.mark_dirty()
await _frames(2)
func _test_condition_rows() -> void:
main.select_result("weather", "e1")
await _frames(2)
var cond: ConditionBuilder = insp.pipe_parts["luck_t"]["when"]
var e := _t("weather").find_entry("e1")
_check(InspectorKit.find_tagged(cond, "cond.0.step") is OptionButton or _has_step_dropdown(cond), "a scale clause picks its step from a dropdown")
_eq(Describe.condition(e.when_for("luck_t"), main.data), "Climate is at least Cold", "reads in plain words")
cond.set_clause_step(0, "Hot")
_eq(e.when_for("luck_t"), "@climate >= \"Hot\"", "picking a step writes it")
cond.add_clause()
cond.set_clause_var(1, "@climate")
_eq(cond.clauses[1]["value"], "\"Supercold\"", "a new scale clause starts at the first step")
func _has_step_dropdown(n: Node) -> bool:
for c in n.get_children():
if (c is OptionButton and (c as OptionButton).item_count == CLIMATE.size()) or _has_step_dropdown(c):
return true
return false
func _test_help() -> void:
var help := FileAccess.get_file_as_string("res://help/topics.txt")
var a := help.find("# Values and changes")
var b := help.find("# Scales")
_check(a >= 0 and b > a and help.find("\n# ", a + 1) == b - 1, "the Scales topic follows Values and changes")

View file

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

82
tests/test_ui_threads.gd Normal file
View file

@ -0,0 +1,82 @@
extends TestBase
## The thread inspector's "Roll it with … instead" field and "Roll again if
## it comes up" list: shown for a card with numbered ranges, edits land on the
## result, undo puts them back.
## Run: godot --headless --path . -s res://tests/test_ui_threads.gd -- --sample
func _init() -> void:
if not await start_main():
return
await _test_ranged_target()
await _test_plain_target()
finish()
func _parts(to: String) -> Dictionary:
return main.inspector.pipe_parts.get(to, {})
func _road() -> TableEntry:
return main.data.get_table("road").entries[3]
func _test_ranged_target() -> void:
print("Ranged target")
main.set_mode(Main.Mode.BUILD)
var e := _road()
e.add_pipe("wilderness")
main.mark_dirty()
main.undo_redo._commit_edits()
main.inspecting.select_pipe(Roller.pipe_key("road", e.id, "wilderness"))
await _frames(3)
var p := _parts("wilderness")
_check(p.has("dice"), "a ranged card gets the Roll it with field")
var dice := p.get("dice") as LineEdit
_eq(dice.placeholder_text, "1d100", "its placeholder is the card's own dice")
var toggle := p.get("reroll_toggle") as Button
_check(toggle != null and toggle.text.contains("never"), "the roll-again list starts closed, saying never: %s" % (toggle.text if toggle else ""))
var boxes: Dictionary = p.get("reroll", {})
var w := main.data.get_table("wilderness")
_eq(boxes.size(), w.entries.size(), "one tick box per result")
var last := w.entries[w.entries.size() - 1]
_check((boxes[last.id] as CheckBox).text.begins_with("96–00"), "a box shows the number and the text: %s" % (boxes[last.id] as CheckBox).text)
dice.text = "3d10+"
dice.text_changed.emit("3d10+")
_eq(e.dice_for("wilderness"), "", "dice that can't be rolled aren't kept")
dice.text = "3d10+70"
dice.text_changed.emit("3d10+70")
_eq(e.dice_for("wilderness"), "3d10+70", "the dice land on the thread")
main.undo_redo._commit_edits()
toggle.pressed.emit()
_check((boxes[last.id] as CheckBox).is_visible_in_tree(), "the list opens")
(boxes[last.id] as CheckBox).button_pressed = true
_eq(e.reroll_for("wilderness"), [last.id] as Array[String], "ticking adds the result")
_check(toggle.text.contains("96–00"), "the heading names it: %s" % toggle.text)
main.undo_redo._commit_edits()
# Quick edits to one card merge into one undo step (EditHistory.COALESCE_SECS).
main.undo_redo.undo()
await _frames(2)
e = _road()
_check(e.reroll_for("wilderness").is_empty(), "undo takes the tick back")
_eq(e.dice_for("wilderness"), "", "and the dice")
main.undo_redo.redo()
await _frames(2)
e = _road()
_eq(e.dice_for("wilderness"), "3d10+70", "redo brings the dice back")
_eq(e.reroll_for("wilderness"), [last.id] as Array[String], "and the tick")
var boxes2: Dictionary = _parts("wilderness").get("reroll", {})
_check(boxes2.has(last.id) and (boxes2[last.id] as CheckBox).button_pressed, "the inspector shows the tick again")
_check(DescribeCards.pipe(e, "wilderness", main.data).contains("again on 96–00"), "the thread's label says so")
func _test_plain_target() -> void:
print("Card without ranges")
var e := main.data.get_table("wilderness").entries[0]
main.inspecting.select_pipe(Roller.pipe_key("wilderness", e.id, "road"))
await _frames(3)
var p := _parts("road")
_check(not p.has("dice"), "no Roll it with field for a card without ranges")
_check(p.has("reroll"), "but the roll-again list is there")

View file

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

View file

@ -250,6 +250,13 @@ func set_pipe_color(hex: String, to: String) -> void:
InspectorThread.set_color(self, hex, to)
func set_pipe_dice(to: String, s: String) -> void:
InspectorThreadRolls.set_dice(self, to, s)
func set_pipe_reroll(to: String, rid: String, on: bool) -> void:
InspectorThreadRolls.set_reroll(self, to, rid, on)
func remove_pipe(to: String) -> void:
var t := selected_table()

View file

@ -24,6 +24,7 @@ static func build(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
RollTable.KIND_ROLL:
InspectorRoll.build(insp, box, t, plain)
InspectorRoll.deck(insp, box, t)
InspectorColumns.build(insp, box, t)
RollTable.KIND_CHECK:
_check(insp, box, t, plain)
RollTable.KIND_CHOICE:
@ -469,13 +470,15 @@ static func _variable(insp: Inspector, box: VBoxContainer, t: RollTable) -> void
var vn := _setting_line(insp, "var_name", t.var_name, "luck", err)
InspectorKit.code(vn)
box.add_child(InspectorKit.field("Name in rules (@name)", vn))
var types := ["number", "text", "list"]
var seg := ModalCard.segmented(["Number", "Text", "List"], maxi(0, types.find(t.var_type)), func(i: int) -> void:
InspectorKit.show_error(err, insp.apply_settings({"var_type": types[i]}, true))
var types := ["number", "text", "list", RollTable.VAR_SCALE]
var seg := ModalCard.segmented(["Number", "Text", "List", "Scale"], maxi(0, types.find(t.var_type)), func(i: int) -> void:
InspectorKit.show_error(err, insp.apply_settings({"var_type": types[i], "initial": "" if t.is_scale() else t.initial}, true))
)
box.add_child(InspectorKit.field("Type", seg))
var init := _setting_line(insp, "initial", t.initial, "0" if t.var_type == "number" else "nothing", err)
box.add_child(InspectorKit.field("Starting value", init))
if t.is_scale():
InspectorScale.build(insp, box, t, err)
else:
box.add_child(InspectorKit.field("Starting value", _setting_line(insp, "initial", t.initial, "0" if t.var_type == "number" else "nothing", err)))
box.add_child(err)

220
ui/inspector_columns.gd Normal file
View file

@ -0,0 +1,220 @@
class_name InspectorColumns
extends RefCounted
## The inspector's "Columns" section for a roll card (RollTable.columns, a
## multi-column table): "Add columns" turns them on (Result plus one more);
## then one roll for the whole row or each column rolled separately, and a box
## per column with its name, move and remove, "Save as [value ▾]" and (after
## the first) "Only roll this column if …". The result section's cell fields
## come from result_cells(). Writes go through Inspector.wrote, so undo works
## as for any card edit. The editing helpers keep every result's cells in step
## with the columns.
const ROLL_LABELS := ["One roll for the whole row", "Roll each column separately"]
const ROLL_MODES := [RollTable.COLUMNS_ROW, RollTable.COLUMNS_EACH]
const ROLL_NOTES := [
"One roll picks a row, and you get every column of that row.",
"The first column is the card's own roll. Each other column is rolled on its own, like “roll 1d10 for each”.",
]
static func build(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
var v := InspectorKit.vbox(8)
if t.columns.is_empty():
v.add_child(InspectorKit.note("Give each result more than one part, like a row of a printed table: Resources, Water, Atmosphere…", Style.MUTED, 13))
var add := InspectorKit.link("+ Add columns", "Split the results into columns")
add.pressed.connect(func() -> void:
add_columns(t)
insp.wrote(t, false, true))
v.add_child(add)
box.add_child(InspectorKit.field("Columns", v))
return
var mode := InspectorKit.dropdown(ROLL_LABELS, maxi(0, ROLL_MODES.find(t.column_rolls)))
mode.tooltip_text = "Whether one roll gives the whole row, or each column gets its own roll"
InspectorKit.tag(mode, "card.column_rolls")
insp.fields["column_rolls"] = mode
mode.item_selected.connect(func(i: int) -> void:
if t.column_rolls != ROLL_MODES[i]:
t.column_rolls = ROLL_MODES[i]
insp.wrote(t, false, true))
v.add_child(mode)
v.add_child(InspectorKit.note(ROLL_NOTES[maxi(0, ROLL_MODES.find(t.column_rolls))], Style.MUTED, 13))
for k in t.columns.size():
v.add_child(_column_box(insp, t, k))
var row := InspectorKit.hbox(12)
var more := InspectorKit.link("+ Add column", "Add a column at the end")
more.pressed.connect(func() -> void:
add_column(t)
insp.wrote(t, false, true))
row.add_child(more)
var off := InspectorKit.link("Remove columns", "Back to one text per result (the first column stays)")
off.add_theme_color_override("font_color", Style.DANGER_INK)
off.pressed.connect(func() -> void:
remove_columns(t)
insp.wrote(t, false, true))
row.add_child(off)
v.add_child(row)
box.add_child(InspectorKit.field("Columns", v))
static func _column_box(insp: Inspector, t: RollTable, k: int) -> Control:
var col: Dictionary = t.columns[k]
var panel := PanelContainer.new()
panel.add_theme_stylebox_override("panel", Style.bordered(Style.box(Style.CARD_SOFT, 8, [10, 8, 8, 8]), 1, Style.RULE))
var v := InspectorKit.vbox(6)
panel.add_child(v)
var head := InspectorKit.hbox(4)
var name := InspectorKit.line(str(col.get("name", "")), "Column name")
name.size_flags_horizontal = Control.SIZE_EXPAND_FILL
InspectorKit.tag(name, "col.%d.name" % k)
insp.fields["column_name_%d" % k] = name
name.text_changed.connect(func(s: String) -> void:
t.columns[k]["name"] = s
insp.wrote(t))
head.add_child(name)
if k > 0:
head.add_child(TableCardEditing.mini_button("↑", "Move this column left", k > 1, func() -> void:
move_column(t, k, -1)
insp.wrote(t, false, true)))
head.add_child(TableCardEditing.mini_button("↓", "Move this column right", k < t.columns.size() - 1, func() -> void:
move_column(t, k, 1)
insp.wrote(t, false, true)))
var rm := InspectorKit.xbutton("Remove this column (and its text on every result)")
rm.pressed.connect(func() -> void:
remove_column(t, k)
insp.wrote(t, false, true))
head.add_child(rm)
v.add_child(head)
if k == 0:
v.add_child(InspectorKit.note("The result's own text: its effects and threads go with this column.", Style.MUTED, 12))
var save := InspectorKit.flow()
save.add_child(InspectorKit.word("Save as"))
var pick := ValuePicker.new(insp.main)
pick.placeholder = "nothing"
pick.set_value(str(col.get("save_as", "")))
pick.tooltip_text = "Keep this column's text as a value, so later rules and text can use it"
pick.value_chosen.connect(func(n: String) -> void:
t.columns[k]["save_as"] = n
insp.wrote(t, false, true))
insp.fields["column_save_%d" % k] = pick
save.add_child(pick)
if str(col.get("save_as", "")) != "":
var clear := InspectorKit.xbutton("Don't save this column")
clear.pressed.connect(func() -> void:
t.columns[k].erase("save_as")
insp.wrote(t, false, true))
save.add_child(clear)
v.add_child(save)
if k > 0:
var w := str(col.get("when", ""))
var cond := ConditionBuilder.new()
cond.setup(insp.main, w, not insp.main.rules_plain(), "col.%d.when" % k,
{"empty_note": "Always rolled.", "extras": _earlier_saves(insp, t, k),
"add_label": "+ Only if…" if w == "" else "+ Add condition"})
cond.changed.connect(func(s: String) -> void:
if TableSettingsDialog.when_error(s) == "" and s.strip_edges() != str(t.columns[k].get("when", "")):
set_when(t, k, s)
insp.wrote(t))
insp.fields["column_when_%d" % k] = cond
v.add_child(InspectorKit.word("Only roll this column if", Style.MUTED))
v.add_child(cond)
return panel
## Values the columns before `k` save, for column k's condition pickers.
static func _earlier_saves(insp: Inspector, t: RollTable, k: int) -> Array:
var known := {}
for kv: Dictionary in Builder.known_values(insp.main.data):
known[str(kv["name"])] = true
var out: Array = []
for j in k:
var s := str(t.columns[j].get("save_as", "")).strip_edges()
if s != "" and not known.has(s):
out.append({"name": s, "label": str(t.columns[j].get("name", s)), "kind": "text"})
return out
## The result section: one text field per column after the first.
static func result_cells(insp: Inspector, t: RollTable, e: TableEntry) -> void:
if not t.has_columns():
return
for k in range(1, t.columns.size()):
var nm := str(t.columns[k].get("name", ""))
var le := InspectorKit.line(RollTable.cell_text(e, k), nm)
InspectorKit.tag(le, "res.cell.%d" % k)
insp.fields["cell_%d" % k] = le
le.text_changed.connect(func(s: String) -> void:
if RollTable.cell_text(e, k) != s:
TableCardColumns.set_cell(e, k, s)
insp.wrote(t))
insp._content.add_child(InspectorKit.field(nm if nm.strip_edges() != "" else "Column %d" % (k + 1), le))
# ---------- Editing (keeps every result's cells in step) ----------
## Turns columns on: "Result" (the results' own text) plus one more.
static func add_columns(t: RollTable) -> void:
if not t.columns.is_empty():
return
t.columns = [{"name": "Result"}]
t.column_rolls = RollTable.COLUMNS_ROW
add_column(t)
static func add_column(t: RollTable) -> void:
if t.columns.is_empty():
add_columns(t)
return
t.columns.append({"name": "Column %d" % (t.columns.size() + 1)})
for e in t.entries:
_fit(e, t.columns.size() - 1)
## Removes column `k` (not the first) and its cell on every result. With only
## the first column left, the card goes back to plain results.
static func remove_column(t: RollTable, k: int) -> void:
if k <= 0 or k >= t.columns.size():
return
t.columns.remove_at(k)
for e in t.entries:
if k - 1 < e.cells.size():
e.cells.remove_at(k - 1)
if t.columns.size() <= 1:
remove_columns(t)
## Back to a plain card: the results keep their own text, the cells go.
static func remove_columns(t: RollTable) -> void:
t.columns = []
t.column_rolls = RollTable.COLUMNS_ROW
for e in t.entries:
e.cells.clear()
## Moves column `k` left (-1) or right (+1); the first column stays put.
static func move_column(t: RollTable, k: int, by: int) -> void:
var to := k + by
if k <= 0 or to <= 0 or to >= t.columns.size():
return
var c: Dictionary = t.columns[k]
t.columns[k] = t.columns[to]
t.columns[to] = c
for e in t.entries:
_fit(e, t.columns.size() - 1)
var s := e.cells[k - 1]
e.cells[k - 1] = e.cells[to - 1]
e.cells[to - 1] = s
static func set_when(t: RollTable, k: int, s: String) -> void:
if s.strip_edges() == "":
t.columns[k].erase("when")
else:
t.columns[k]["when"] = s.strip_edges()
static func _fit(e: TableEntry, n: int) -> void:
while e.cells.size() < n:
e.cells.append("")

View file

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

View file

@ -2,8 +2,10 @@ class_name ConditionBuilder
extends VBoxContainer
## A condition editor: clauses `[value ▾] [comparison ▾] [amount] ×`, an
## and/or switch once there are two, and "+ Add condition"
## (Builder.parse_condition / condition_text). A condition the builder can't
## show (mixed and/or, dice, functions…) is a text field with its problem;
## (Builder.parse_condition / condition_text). For a scale value the amount
## is a dropdown of its steps ("Atmosphere is at least [Thin ▾]"). A condition
## the builder can't show (mixed and/or, dice, functions…) is a text field
## with its problem;
## "Edit as text" and "Use the builder" switch between the two.
## Emits `changed(text)`; clauses not filled in yet are left out.
@ -94,6 +96,10 @@ func set_join(j: String) -> void:
func set_clause_var(i: int, n: String) -> void:
clauses[i]["var"] = n
var steps := ScaleFields.steps_of(main, n)
var cur := Builder.unquote(str(clauses[i]["value"]))
if not steps.is_empty() and Scales.position_of(steps, cur) == 0 and not ["set", "unset"].has(str(clauses[i]["cmp"])):
clauses[i]["value"] = Builder.quote(steps[0])
_render()
_emit()
@ -112,6 +118,13 @@ func set_clause_value(i: int, typed: String) -> void:
_emit()
## A scale clause's step.
func set_clause_step(i: int, step: String) -> void:
clauses[i]["value"] = Builder.quote(step)
_render()
_emit()
func set_text_mode(on: bool) -> void:
if on == text_mode:
return
@ -204,7 +217,14 @@ func _clause_row(i: int) -> Control:
f.add_child(dd)
var err := InspectorKit.error_label()
var le: LineEdit = null
if cmp != "set" and cmp != "unset":
var steps := ScaleFields.steps_of(main, str(c["var"]))
if not steps.is_empty() and cmp != "set" and cmp != "unset" and cmp != "has":
var cur := str(c["value"])
cur = Builder.unquote(cur) if Builder.is_text_literal(cur) else (Scales.label_at(steps, int(cur)) if cur.is_valid_int() else cur)
var sd := ScaleFields.step_dropdown(steps, cur, func(st: String) -> void: set_clause_step(i, st))
InspectorKit.tag(sd, "%s.%d.step" % [_key, i])
f.add_child(sd)
elif cmp != "set" and cmp != "unset":
le = InspectorKit.amount(InspectorKit.shown_token(str(c["value"])), "8")
le.tooltip_text = "A number, a word, or a value such as @soc"
InspectorKit.tag(le, "%s.%d.value" % [_key, i])

View file

@ -2,7 +2,7 @@ class_name EffectsBuilder
extends VBoxContainer
## The inspector's "When this comes up" editor: one row per effect statement
## (Builder.parse_effects), each `[op ▾] [amount] to/from [value ▾] ×`, plus
## "+ Add a change". A statement the builder can't show stays a text field
## "+ Add a change". A scale value's row is EffectsScaleRow. A statement the builder can't show stays a text field
## with its problem. "Edit as text" switches to the whole effects text, and
## "Use the builder" switches back when every statement parses.
## Emits `changed(text)` with the statements (Builder.effect_text) joined by
@ -30,7 +30,7 @@ func setup(p_main: Main, text: String, p_table: RollTable, as_text: bool, key: S
add_theme_constant_override("separation", 6)
size_flags_horizontal = Control.SIZE_EXPAND_FILL
rows.clear()
for m in Builder.parse_effects(text):
for m in Builder.parse_effects(text, _board()):
rows.append(m)
# One unreadable statement doesn't turn the whole field into text: it
# shows as a text row among the others. Text mode starts as text.
@ -38,6 +38,10 @@ func setup(p_main: Main, text: String, p_table: RollTable, as_text: bool, key: S
_render()
func _board() -> TowerBoard:
return main.data if main else null
static func _all_ok(text: String) -> bool:
for m in Builder.parse_effects(text):
if not m["ok"]:
@ -94,7 +98,13 @@ func remove_row(i: int) -> void:
func set_row_op(i: int, op: String) -> void:
var m := rows[i]
if not m["ok"] or not OPS.has(op):
if not m["ok"] or not (OPS.has(op) or BuilderScales.OPS.has(op)):
return
var steps := ScaleFields.steps_of(main, str(m["var"]))
if BuilderScales.OPS.has(op) or (not steps.is_empty() and (op == "set" or op == "reset")) or BuilderScales.OPS.has(str(m["op"])):
EffectsScaleRow.set_op(m, op, steps)
_render()
_emit()
return
var was := str(m["op"])
m["op"] = op
@ -109,6 +119,8 @@ func set_row_op(i: int, op: String) -> void:
m["amount"] = InspectorKit.amount_expr(amt, _known_names()) if amt != "" else ""
elif amt == "" and was == "reset":
m["amount"] = "1"
if not steps.is_empty():
EffectsScaleRow.on_var(m, steps)
_render()
_emit()
@ -118,7 +130,7 @@ func set_row_amount(i: int, typed: String, render: bool = false) -> void:
var m := rows[i]
if not m["ok"]:
return
var listy := str(m["op"]) == "append" or str(m["op"]) == "remove"
var listy := ["append", "remove", "toward", "at_least", "at_most"].has(str(m["op"]))
m["amount"] = typed.strip_edges() if listy else InspectorKit.amount_expr(typed, _known_names())
if render:
_render()
@ -130,6 +142,18 @@ func set_row_var(i: int, n: String) -> void:
if not m["ok"]:
return
m["var"] = n
EffectsScaleRow.on_var(m, ScaleFields.steps_of(main, n))
_render()
_emit()
## A scale row's step (Set writes it quoted; Move toward, Raise and Lower as
## the name).
func set_row_step(i: int, step: String) -> void:
var m := rows[i]
if not m["ok"]:
return
m["amount"] = Builder.quote(step) if str(m["op"]) == "set" else step
_render()
_emit()
@ -138,7 +162,7 @@ func set_row_var(i: int, n: String) -> void:
func set_row_src(i: int, src: String) -> void:
var m := rows[i]
m["src"] = src
var p := Builder.parse_effect(src)
var p := Builder.parse_effect(src, _board())
m["error"] = str(p.get("error", ""))
_emit()
@ -153,7 +177,7 @@ func set_text_mode(on: bool) -> void:
if not _all_ok(_raw):
return
rows.clear()
for m in Builder.parse_effects(_raw):
for m in Builder.parse_effects(_raw, _board()):
rows.append(m)
text_mode = false
_render()
@ -245,6 +269,13 @@ func _row(i: int) -> Control:
check.call()
return v
var op := str(m["op"])
if EffectsScaleRow.shows(m, ScaleFields.steps_of(main, str(m["var"]))):
var sp := ValuePicker.new(main, str(m["var"]))
sp.value_chosen.connect(func(n: String) -> void: set_row_var(i, n))
var serr := InspectorKit.error_label()
EffectsScaleRow.fill(self, i, f, sp, x, serr)
v.add_child(serr)
return v
var dd := InspectorKit.dropdown(OP_LABELS, OPS.find(op))
dd.tooltip_text = "What to do"
dd.item_selected.connect(func(k: int) -> void: set_row_op(i, OPS[k]))

View file

@ -0,0 +1,134 @@
class_name EffectsScaleRow
extends RefCounted
## The effects builder's row for a scale value (BuilderScales): `[Move up ▾]
## [Climate ▾] by [1] step`, `[Set ▾] [Climate ▾] to [Hot ▾]`, `[Move toward ▾]
## [Climate ▾] one step toward [Temperate ▾]`, `[Raise ▾] [Atmosphere ▾] to at
## least [Medium ▾]`, `[Lower ▾] … to at most [Thin ▾]`, `[Reset ▾] [Climate ▾]`.
## Step pickers list the value's steps. Edits go through EffectsBuilder.
const OPS := ["step_up", "step_down", "set", "toward", "at_least", "at_most", "reset"]
const OP_LABELS := ["Move up", "Move down", "Set", "Move toward", "Raise", "Lower", "Reset"]
const _WORDS := {"set": "to", "toward": "one step toward", "at_least": "to at least", "at_most": "to at most"}
## True when row model `m` shows as a scale row: a scale op, or Set/Reset of a
## scale value to one of its steps (Set to an expression stays a plain row).
static func shows(m: Dictionary, steps: Array) -> bool:
var op := str(m["op"])
if BuilderScales.OPS.has(op):
return true
if steps.is_empty():
return false
if op == "reset":
return true
var a := str(m["amount"])
return op == "set" and (a == "" or (Builder.is_text_literal(a) and Scales.position_of(steps, Builder.unquote(a)) > 0))
## Switches row model `m` to `op`, keeping its step where it can: a count of
## steps for Move up/down, a step's name for the others (quoted for Set).
static func set_op(m: Dictionary, op: String, steps: Array) -> void:
var was := str(m["op"])
var step := current_step(m, steps)
if step == "" and not steps.is_empty():
step = str(steps[0])
m["op"] = op
match op:
"step_up", "step_down":
if was != "step_up" and was != "step_down":
m["amount"] = "1"
"set":
m["amount"] = Builder.quote(step) if step != "" else ""
"toward", "at_least", "at_most":
m["amount"] = step
"reset":
m["amount"] = ""
## After the row's value changed: a scale value turns Add/Subtract into Move
## up/down (and anything that can't apply into Move up 1); a value that isn't
## a scale turns the scale ops back into ordinary ones.
static func on_var(m: Dictionary, steps: Array) -> void:
var op := str(m["op"])
if not steps.is_empty():
match op:
"add":
m["op"] = "step_up"
"subtract":
m["op"] = "step_down"
"multiply", "divide", "append", "remove":
m["op"] = "step_up"
m["amount"] = "1"
"set":
if not shows(m, steps):
m["amount"] = Builder.quote(str(steps[0]))
return
match op:
"step_up":
m["op"] = "add"
"step_down":
m["op"] = "subtract"
"toward", "at_least", "at_most":
m["op"] = "set"
m["amount"] = Builder.quote(str(m["amount"])) if str(m["amount"]) != "" else ""
## The step a row names ("" for none or a count of steps).
static func current_step(m: Dictionary, steps: Array) -> String:
var a := str(m.get("amount", ""))
match str(m["op"]):
"set":
return Builder.unquote(a) if Builder.is_text_literal(a) else ""
"toward", "at_least", "at_most":
return a
return ""
## Fills flow `f` with row `i` of `eb` (the op dropdown, the value picker and
## the step or count), then `x`, and shows the row's problem in `err`.
static func fill(eb: EffectsBuilder, i: int, f: Container, picker: ValuePicker, x: Button, err: Label) -> void:
var m := eb.rows[i]
var op := str(m["op"])
var steps := ScaleFields.steps_of(eb.main, str(m["var"]))
var dd := InspectorKit.dropdown(OP_LABELS, OPS.find(op))
dd.tooltip_text = "What to do"
dd.item_selected.connect(func(k: int) -> void: eb.set_row_op(i, OPS[k]))
f.add_child(dd)
picker.kinds = ["scale"]
f.add_child(picker)
var msg := "" if str(m["var"]) != "" else "Pick the value to change."
match op:
"step_up", "step_down":
f.add_child(InspectorKit.word("by"))
var le := InspectorKit.amount(str(m["amount"]), "1")
le.tooltip_text = "How many steps: a number, or dice such as 1d3"
InspectorKit.tag(le, "%s.%d.amount" % [eb._key, i])
var unit := InspectorKit.word("step" if str(m["amount"]) == "1" else "steps")
le.text_changed.connect(func(s: String) -> void:
eb.set_row_amount(i, s)
unit.text = "step" if s.strip_edges() == "1" else "steps"
_check_count(m, le, err)
)
f.add_child(le)
f.add_child(unit)
f.add_child(x)
_check_count(m, le, err)
return
"set", "toward", "at_least", "at_most":
f.add_child(InspectorKit.word(_WORDS[op]))
var sd := ScaleFields.step_dropdown(steps, current_step(m, steps), func(s: String) -> void: eb.set_row_step(i, s))
InspectorKit.tag(sd, "%s.%d.step" % [eb._key, i])
f.add_child(sd)
if msg == "" and current_step(m, steps) == "":
msg = "Pick a step."
f.add_child(x)
InspectorKit.show_error(err, msg)
static func _check_count(m: Dictionary, le: LineEdit, err: Label) -> void:
var a := str(m["amount"]).strip_edges()
var msg := "Pick the value to change." if str(m["var"]) == "" else ""
if msg == "":
msg = "Fill in how many steps." if a == "" else InspectorKit.expr_error(a, "The number of steps")
InspectorKit.show_error(err, msg)
InspectorKit.mark(le, msg == "" or str(m["var"]) == "")

View file

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

View file

@ -69,7 +69,8 @@ static func section(insp: Inspector, t: RollTable, e: TableEntry) -> void:
InspectorKit.tag(le, "res.text")
le.text_changed.connect(insp.set_entry_text)
insp.fields["text"] = le
insp._content.add_child(InspectorKit.field("Text", le))
insp._content.add_child(InspectorKit.field(Inspector._title_of(str(t.columns[0].get("name", "")), "Text") if t.has_columns() else "Text", le))
InspectorColumns.result_cells(insp, t, e)
var det := InspectorKit.text_box(e.details, "Shown on hover (optional)", 36.0)
InspectorKit.tag(det, "res.details")

35
ui/inspector_scale.gd Normal file
View file

@ -0,0 +1,35 @@
class_name InspectorScale
extends RefCounted
## A scale variable card's fields in the inspector (Scales): its steps, one
## per line, lowest first, and a starting value picked from them. Writes go
## through Inspector.apply_settings (TableSettingsRules keeps the starting
## value one of the steps).
static func build(insp: Inspector, box: VBoxContainer, t: RollTable, err: Label) -> void:
var te := InspectorKit.text_box("\n".join(t.steps), "Low\nMedium\nHigh", 96.0)
InspectorKit.tag(te, "card.steps")
insp.fields["steps"] = te
box.add_child(InspectorKit.field("Steps, one per line, lowest first", te))
var start := HBoxContainer.new()
box.add_child(InspectorKit.field("Starting value", start))
_fill_start(insp, start, t, err)
te.text_changed.connect(func() -> void:
var msg := insp.apply_settings({"steps": te.text})
InspectorKit.mark(te, msg == "")
InspectorKit.show_error(err, msg)
if msg == "":
_fill_start(insp, start, t, err)
)
## The starting value's step dropdown in `holder` (refilled when the steps change).
static func _fill_start(insp: Inspector, holder: Container, t: RollTable, err: Label) -> void:
InspectorKit.clear(holder)
var dd := ScaleFields.step_dropdown(t.steps, Builder.unquote(t.initial), func(step: String) -> void:
InspectorKit.show_error(err, insp.apply_settings({"initial": ScaleFields.initial_text(step)}))
)
dd.tooltip_text = "The step it starts at, and goes back to on Reset"
InspectorKit.tag(dd, "card.initial")
insp.fields["initial"] = dd
holder.add_child(dd)

View file

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

View file

@ -245,6 +245,7 @@ static func box(insp: Inspector, t: RollTable, e: TableEntry, to: String) -> Con
v.add_child(cr)
v.add_child(sr)
v.add_child(cerr)
InspectorThreadRolls.rows(insp, e, to, target, v, parts)
var rm := InspectorKit.link("Delete thread", "Delete this thread")
rm.add_theme_color_override("font_color", Style.DANGER_INK)

View file

@ -0,0 +1,132 @@
class_name InspectorThreadRolls
extends RefCounted
## The thread inspector's "how the card is rolled" options: roll it with other
## dice instead (a card with numbered ranges only), and roll again on some of
## its results. InspectorThread.box() adds rows() to the thread box.
## Results the "Roll again" list shows before it scrolls, and its height then.
const LIST_ROWS := 7
const LIST_MAX_H := 196.0
## Inspector meta: the thread targets whose "Roll again" list is open.
const OPEN_META := "reroll_open"
## "" when `s` is dice the thread can roll with (empty = the card's own).
static func dice_error(s: String) -> String:
var d := s.strip_edges()
if Dice.roll_problem(d) == "":
return ""
return "That isn't something the app can roll. Try dice such as 3d10+70."
static func set_dice(insp: Inspector, to: String, s: String) -> void:
var e := insp.selected_entry()
if e == null or dice_error(s) != "" or s.strip_edges() == e.dice_for(to):
return
e.set_pipe_dice(to, s)
insp.wrote(insp.selected_table())
## Ticks (on) or unticks the target's result `rid` in the thread's "roll again" list.
static func set_reroll(insp: Inspector, to: String, rid: String, on: bool) -> void:
var e := insp.selected_entry()
if e == null:
return
var ids := e.reroll_for(to)
if ids.has(rid) == on:
return
if on:
ids.append(rid)
else:
ids.erase(rid)
e.set_pipe_reroll(to, ids)
insp.wrote(insp.selected_table())
## Adds the rows for the thread to `target` to `v`; fills `parts` with
## "dice" (LineEdit), "reroll_toggle" (Button) and "reroll" (rid -> CheckBox).
static func rows(insp: Inspector, e: TableEntry, to: String, target: RollTable, v: VBoxContainer, parts: Dictionary) -> void:
if target == null or target.kind != RollTable.KIND_ROLL or target.entries.is_empty():
return
if target.is_ranged():
_dice_row(insp, e, to, target, v, parts)
_reroll_rows(insp, e, to, target, v, parts)
static func _dice_row(insp: Inspector, e: TableEntry, to: String, target: RollTable, v: VBoxContainer, parts: Dictionary) -> void:
var row := InspectorKit.flow()
row.add_child(InspectorKit.word("Roll it with"))
var le := InspectorKit.amount(e.dice_for(to), target.dice)
le.tooltip_text = "Other dice to roll %s with this time, such as 3d10+70. Leave it empty to use the card's own dice (%s)." % [target.name, target.dice]
InspectorKit.tag(le, "pipe.%s.dice" % to)
row.add_child(le)
row.add_child(InspectorKit.word("instead"))
var err := InspectorKit.error_label()
le.text_changed.connect(func(s: String) -> void:
var msg := dice_error(s)
InspectorKit.show_error(err, msg)
InspectorKit.mark(le, msg == "")
set_dice(insp, to, s)
)
parts["dice"] = le
v.add_child(row)
v.add_child(err)
static func _reroll_rows(insp: Inspector, e: TableEntry, to: String, target: RollTable, v: VBoxContainer, parts: Dictionary) -> void:
var open: Dictionary = insp.get_meta(OPEN_META, {})
var toggle := InspectorKit.link("", "Pick results that are rolled again when they come up")
toggle.alignment = HORIZONTAL_ALIGNMENT_LEFT
toggle.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
toggle.size_flags_horizontal = Control.SIZE_EXPAND_FILL
v.add_child(toggle)
var scroll := ScrollContainer.new()
scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
# Short lists show whole; longer ones scroll inside a capped box.
if target.entries.size() <= LIST_ROWS:
scroll.vertical_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
else:
scroll.custom_minimum_size.y = LIST_MAX_H
var list := InspectorKit.vbox(0)
scroll.add_child(list)
var boxes := {}
for i in target.entries.size():
var te := target.entries[i]
var text := Formatter.strip_tags(te.text).strip_edges()
var num := target.num_label(te, i)
var cb := InspectorKit.check_box(("%s %s" % [num, text]).strip_edges() if text != "" else num, e.reroll_for(to).has(te.id))
cb.add_theme_font_override("font", Style.body())
cb.add_theme_font_size_override("font_size", 14)
cb.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
cb.clip_text = true
cb.size_flags_horizontal = Control.SIZE_EXPAND_FILL
cb.tooltip_text = cb.text
var rid := te.id
cb.toggled.connect(func(on: bool) -> void:
set_reroll(insp, to, rid, on)
_label_toggle(toggle, insp, to, target, scroll.visible)
)
boxes[te.id] = cb
list.add_child(cb)
v.add_child(scroll)
var show := func(on: bool) -> void:
scroll.visible = on
var o: Dictionary = insp.get_meta(OPEN_META, {})
if on:
o[to] = true
else:
o.erase(to)
insp.set_meta(OPEN_META, o)
_label_toggle(toggle, insp, to, target, on)
toggle.pressed.connect(func() -> void: show.call(not scroll.visible))
show.call(open.has(to))
parts["reroll_toggle"] = toggle
parts["reroll"] = boxes
## "Roll again if it comes up: 96–00 ▸" (or "never").
static func _label_toggle(toggle: Button, insp: Inspector, to: String, target: RollTable, open: bool) -> void:
var e := insp.selected_entry()
var ids: Array = e.reroll_for(to) if e else []
var picked := DescribeCards.reroll_names(ids, target) if not ids.is_empty() else "never"
toggle.text = "Roll again if it comes up: %s %s" % [picked, "▾" if open else "▸"]

View file

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

View file

@ -60,6 +60,7 @@ var _saving_enabled := true
var decks: Dictionary = {} # table id -> DeckState
var persistent_vars: Dictionary = {} # name without "@" -> {"value", "source"}
var lit_texts: Dictionary = {} # "tid:eid" -> expanded BBCode from the last roll
var lit_columns: Dictionary = {} # "tid:eid" -> the rolled node's "columns" (TableCardColumns)
var _details_popup: DetailsPopup
## Choice cards: func(request: Dictionary) -> Variant, awaited by the roller
## (docs/LOGIC.md §8). It opens the choice pop-up (_ask_player); tests swap in

View file

@ -22,6 +22,7 @@ const ADD_KINDS := [
["Branch: if / else if / otherwise", RollTable.KIND_ROUTER, "", "Branch"],
["Variable", RollTable.KIND_VARIABLE, "number", "New variable"],
["Collection (Skills, Contacts…)", RollTable.KIND_VARIABLE, RollTable.VAR_COLLECTION, "Skills"],
["Scale (ordered steps)", RollTable.KIND_VARIABLE, RollTable.VAR_SCALE, "New scale"],
["Sheet", RollTable.KIND_SHEET, "", "Sheet"],
]
const MENU_FROM_TEMPLATE := 100

View file

@ -73,6 +73,7 @@ func start_roll(tid: String, fast: bool = false) -> void:
m.lit_entries.clear()
m.lit_pipes.clear()
m.lit_texts.clear()
m.lit_columns.clear()
m.current = {"collection": m.data.id, "root": tid, "root_name": t.name, "time": m.current.get("time", Time.get_unix_time_from_system()),
"steps": [], "all": Roller.flatten(tree, []), "done": false, "chain_vars": ctx.chain_vars.duplicate()}
if ctx.halted != "":
@ -120,6 +121,7 @@ func show_progress() -> void:
m.lit_entries.clear()
m.lit_pipes.clear()
m.lit_texts.clear()
m.lit_columns.clear()
_light_steps(steps)
m._refresh_lit()
_reveal_steps(steps)
@ -233,6 +235,7 @@ func _play_one(n: Dictionary, my: int, depth: int) -> void:
var ek := Roller.entry_key(t.id, e.id)
m.lit_entries[ek] = true
m.lit_texts[ek] = str(n.get("summary", e.text))
TableCardColumns.note_lit(m, ek, n)
m._refresh_lit()
if card:
card.reveal(e.id)
@ -371,6 +374,7 @@ func _light_steps(steps: Array) -> void:
var ek := Roller.entry_key(tid, str(s["entry_id"]))
m.lit_entries[ek] = true
m.lit_texts[ek] = str(s.get("text", ""))
TableCardColumns.note_lit(m, ek, s)
if d > 0 and not (s.has("pass") or s.has("after")) and stack[d - 1] is Dictionary and (stack[d - 1] as Dictionary).has("entry_id"):
var p: Dictionary = stack[d - 1]
var ptid := str(p.get("table_id", ""))

View file

@ -25,6 +25,7 @@ func load_local_state() -> void:
m.lit_entries.clear()
m.lit_pipes.clear()
m.lit_texts.clear()
m.lit_columns.clear()
_ref_cache.clear()
if m.state == null or m.data == null:
return
@ -157,6 +158,8 @@ func set_variable(name: String, value: String) -> void:
source = card.id
var as_number := Expr.is_number(was) or (card != null and card.var_type == "number")
var typed: Variant = Expr.to_value(value) if as_number and Expr.is_number(value) else value
if card != null and card.is_scale():
typed = Scales.store(card.steps, value)
m.persistent_vars[name] = {"value": typed, "source": source}
_variables_changed()

40
ui/scale_fields.gd Normal file
View file

@ -0,0 +1,40 @@
class_name ScaleFields
extends RefCounted
## Small shared pieces for scale values (Scales) in the inspector: a value's
## steps, a dropdown of steps, and a step written as a rule literal.
## The steps of board value `v` ("@climate") when a scale card declares it,
## else [].
static func steps_of(main: Main, v: String) -> Array[String]:
var card := BuilderScales.card_for(v, main.data if main else null)
return card.steps if card else ([] as Array[String])
## A dropdown of `steps` with `current` selected (matched without caring about
## capitals). A `current` that isn't one of the steps is listed last, marked,
## so nothing is lost. `on_pick` gets the chosen step's name.
static func step_dropdown(steps: Array, current: String, on_pick: Callable) -> OptionButton:
var items: Array = steps.duplicate()
var at := Scales.position_of(steps, current) - 1 if current != "" else -1
if at < 0 and current != "":
items.append("%s (not a step)" % current)
at = items.size() - 1
var dd := InspectorKit.dropdown(items, at)
dd.tooltip_text = "Pick a step"
dd.item_selected.connect(func(k: int) -> void:
if k < steps.size():
on_pick.call(str(steps[k]))
)
return dd
## The steps a new scale card gets (RollTable.create's).
static func default_steps() -> Array[String]:
return RollTable.create(RollTable.KIND_VARIABLE, "", "", RollTable.VAR_SCALE).steps
## A step as a starting value: the name as it is when it reads as plain words,
## else quoted ("Semi-arid" has a dash, so it is "\"Semi-arid\"").
static func initial_text(step: String) -> String:
return step if RollTable._looks_literal(step) else Builder.quote(step)

1
ui/scale_fields.gd.uid Normal file
View file

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

View file

@ -32,6 +32,9 @@ var _loop_note: Label
var _var_name: LineEdit
var _var_type := "number"
var _initial: LineEdit
## Scale variables: the steps, one per line (shown only for the Scale type).
var _steps: TextEdit
var _steps_field: Control
var _template: TextEdit
var _template_preview: RichTextLabel
## Router cards: one condition field per case, in order.
@ -71,6 +74,8 @@ func add_settings(s: Dictionary) -> void:
s["var_name"] = _var_name.text.strip_edges().trim_prefix("@")
s["var_type"] = _var_type
s["initial"] = _initial.text.strip_edges()
if _var_type == RollTable.VAR_SCALE:
s["steps"] = _steps.text
RollTable.KIND_SHEET:
s["template"] = _template.text
RollTable.KIND_ROUTER:
@ -142,10 +147,17 @@ func build() -> void:
_var_name.text_changed.connect(func(_t: String) -> void: d._refresh())
box.add_child(ModalCard.field("Variable name (used as @name)", _var_name))
box.add_child(ModalCard.section("Type"))
box.add_child(ModalCard.segmented(["Number", "Text", "List", "Collection"], RollTable.VAR_TYPES.find(_var_type), func(i: int) -> void:
box.add_child(ModalCard.segmented(["Number", "Text", "List", "Collection", "Scale"], RollTable.VAR_TYPES.find(_var_type), func(i: int) -> void:
_var_type = RollTable.VAR_TYPES[i]
d._refresh()
))
_steps = TextEdit.new()
_steps.text = "\n".join(table.steps if not table.steps.is_empty() else ScaleFields.default_steps())
_steps.custom_minimum_size.y = 96
ModalCard.style_text_edit(_steps)
_steps.text_changed.connect(d._refresh)
_steps_field = ModalCard.field("Steps, one per line, lowest first", _steps)
box.add_child(_steps_field)
_initial = LineEdit.new()
_initial.text = table.initial
_initial.placeholder_text = "10, 2d6, or a word"
@ -295,6 +307,8 @@ func refresh() -> void:
RollTable.KIND_VARIABLE:
_mark(_var_name, TableSettingsRules._re(TableSettingsRules.VAR_PATTERN).search(TemplateKit.probe(s["var_name"])) != null)
_mark(_initial, TableSettingsRules._initial_error(s["initial"], _var_type) == "")
_steps_field.visible = _var_type == RollTable.VAR_SCALE
_initial.placeholder_text = "one of the steps" if _var_type == RollTable.VAR_SCALE else "10, 2d6, or a word"
RollTable.KIND_SHEET:
var ctx := Roller.live_context(table_board(), _live_vars())
_template_preview.text = RichText.decorate(TextExpander.render(_template.text, ctx)) if _template.text.strip_edges() != "" \

View file

@ -301,9 +301,11 @@ func card_width() -> float:
return (table.width if table.width > 0.0 else WIDTH) + extra_width()
## Build mode has more controls per row, so cards are a little wider there.
## Build mode has more controls per row, so cards are a little wider there;
## a card with columns is wider by its extra columns.
func extra_width() -> float:
return BUILD_WIDTH - WIDTH if main.mode == Main.Mode.BUILD else 0.0
var cols := rows_ui.columns_ui.extra_width() if rows_ui else 0.0
return (BUILD_WIDTH - WIDTH if main.mode == Main.Mode.BUILD else 0.0) + cols
## The height the results take now (the scrolling list's, if there is one).

206
ui/table_card_columns.gd Normal file
View file

@ -0,0 +1,206 @@
class_name TableCardColumns
extends RefCounted
## A TableCard's columns (a roll card with RollTable.columns): the small
## header row of column names over the results, each row's cells after its
## text (Play: the text, wrapping; Build: a field per cell, edited inline like
## the result text) and, after a roll, the cell each column landed on lit
## (from the rolled node's "columns", kept in Main.lit_columns). Column 0 is
## the row's own text, so TableCardRows draws it as usual.
## Width of one extra column's cell.
const CELL_W := 112.0
## Room the Build row keeps after the cells: the weight box and the ×.
const BUILD_TAIL := 34.0 + 22.0 + 8.0
const BUILD_TAIL_RANGED := 22.0 + 4.0
## Room a ranged Play row keeps for its chance ("17%").
const ODDS_TAIL := 36.0
var card: TableCard
## entry id -> Array of {"box", "label" (Play) or "edit" (Build), "k"}.
var cells: Dictionary = {}
func _init(p_card: TableCard) -> void:
card = p_card
func clear() -> void:
cells.clear()
func active() -> bool:
return card.table != null and card.table.has_columns()
## The extra card width the columns after the first need.
func extra_width() -> float:
if not active():
return 0.0
return (card.table.columns.size() - 1) * (CELL_W + _sep())
func _sep() -> float:
return 4.0 if card.main.mode == Main.Mode.BUILD else 8.0
## The row of column names over the results, lined up with the cells.
func make_header(build: bool, ranged: bool, numw: float) -> Control:
var t := card.table
var pad := MarginContainer.new()
pad.mouse_filter = Control.MOUSE_FILTER_PASS
pad.add_theme_constant_override("margin_left", 12)
pad.add_theme_constant_override("margin_right", 22)
pad.add_theme_constant_override("margin_bottom", 2)
var h := TableCard.hbox(int(_sep()))
pad.add_child(h)
var lead := Control.new()
lead.custom_minimum_size = Vector2(numw, 0)
lead.mouse_filter = Control.MOUSE_FILTER_IGNORE
h.add_child(lead)
for k in t.columns.size():
var l := Style.make_label(str(t.columns[k].get("name", "")), Style.body_bold(true), 12, Style.MUTED)
l.clip_text = true
l.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
l.mouse_filter = Control.MOUSE_FILTER_PASS
l.tooltip_text = _column_tip(t.columns[k], k)
if k == 0:
l.size_flags_horizontal = Control.SIZE_EXPAND_FILL
else:
l.custom_minimum_size = Vector2(CELL_W, 0)
h.add_child(l)
var tail := 0.0
if build:
tail = BUILD_TAIL_RANGED if ranged else BUILD_TAIL
elif ranged and t.has_chances():
tail = ODDS_TAIL
if tail > 0.0:
var sp := Control.new()
sp.custom_minimum_size = Vector2(tail, 0)
sp.mouse_filter = Control.MOUSE_FILTER_IGNORE
h.add_child(sp)
pad.set_meta("columns_header", true)
return pad
func _column_tip(col: Dictionary, k: int) -> String:
var bits := PackedStringArray()
if k > 0 and str(col.get("when", "")).strip_edges() != "":
bits.append("Only rolled if " + str(col["when"]).strip_edges())
if str(col.get("save_as", "")).strip_edges() != "":
bits.append("Saved as " + str(col["save_as"]).strip_edges())
return "\n".join(bits)
## Adds row `e`'s cells (columns 1..) to its row box `h`, right after the text.
func add_cells(h: HBoxContainer, e: TableEntry, index: int, build: bool) -> void:
if not active():
return
var list: Array = []
for k in range(1, card.table.columns.size()):
var c := _build_cell(e, k) if build else _play_cell(e, index, k)
h.add_child(c["box"])
list.append(c)
cells[e.id] = list
func _build_cell(e: TableEntry, k: int) -> Dictionary:
var edit := LineEdit.new()
edit.text = RollTable.cell_text(e, k)
edit.placeholder_text = str(card.table.columns[k].get("name", ""))
edit.custom_minimum_size = Vector2(CELL_W, 0)
edit.size_flags_vertical = Control.SIZE_SHRINK_CENTER
edit.add_theme_font_size_override("font_size", 15)
edit.tooltip_text = edit.placeholder_text
edit.text_changed.connect(func(s: String) -> void:
set_cell(e, k, s)
card.main.mark_dirty()
)
edit.focus_entered.connect(func() -> void: card.select_entry(e.id))
edit.set_meta("cell", k)
return {"box": edit, "edit": edit, "k": k}
func _play_cell(e: TableEntry, index: int, k: int) -> Dictionary:
var box := PanelContainer.new()
box.mouse_filter = Control.MOUSE_FILTER_PASS
box.custom_minimum_size = Vector2(CELL_W, 0)
box.size_flags_vertical = Control.SIZE_SHRINK_CENTER
var l := RichText.label("", 15, Style.INK, true)
l.custom_minimum_size = Vector2(CELL_W - 8.0, 0)
RichText.hook_hover(l, card.main)
box.add_child(l)
var c := {"box": box, "label": l, "k": k, "index": index, "entry": e}
_show_cell(c)
return c
## Re-renders a Play row's cells from the last roll (TableCardRows calls it
## with the row's text).
func refresh(eid: String) -> void:
for c: Dictionary in cells.get(eid, []):
if c.has("label"):
_show_cell(c)
func _show_cell(c: Dictionary) -> void:
var e: TableEntry = c["entry"]
var k: int = c["k"]
var rolled := rolled_cell(int(c["index"]), k)
var text := RichText.decorate(str(rolled["text"])) if not rolled.is_empty() \
else RichText.preview(RollTable.cell_text(e, k), card.main.data)
var l: RichTextLabel = c["label"]
if l.text != text:
l.text = text
l.tooltip_text = Formatter.strip_tags(text).strip_edges()
var lit := not rolled.is_empty()
# "Roll each column separately": a lit row's other cells weren't rolled.
var passed := not lit and card.table.column_rolls == RollTable.COLUMNS_EACH \
and card.main.is_entry_lit(card.table.id, e.id) and not _lit_columns().is_empty()
RichText.set_fonts(l, 15, true, lit)
l.add_theme_color_override("default_color", Style.MUTED if passed else Style.INK)
var box: PanelContainer = c["box"]
box.add_theme_stylebox_override("panel", Style.box(Style.ACCENT if lit and card.table.column_rolls == RollTable.COLUMNS_EACH else Color(0, 0, 0, 0), 4, [4, 2, 4, 2]))
box.set_meta("lit", lit)
# ---------- The last roll ----------
## The "columns" of every lit roll of this card in the last roll.
func _lit_columns() -> Array:
var out: Array = []
var pre := card.table.id + ":"
for key: String in card.main.lit_columns:
if key.begins_with(pre) and card.main.lit_entries.has(key):
out.append(card.main.lit_columns[key])
return out
## What column `k` rolled on result number `index` in the last roll
## ({name, text, index, value?}), or {} when it didn't land there.
func rolled_cell(index: int, k: int) -> Dictionary:
for cols: Array in _lit_columns():
if k < cols.size():
var c: Dictionary = cols[k]
if not c.get("skipped", false) and int(c.get("index", -1)) == index:
return c
return {}
## Main.lit_columns from a rolled node or step: its "columns", if it has them.
static func note_lit(m: Main, key: String, d: Dictionary) -> void:
if d.get("columns") is Array:
m.lit_columns[key] = d["columns"]
else:
m.lit_columns.erase(key)
# ---------- Editing ----------
## Sets column `k`'s text on result `e` (k 0 is its own text).
static func set_cell(e: TableEntry, k: int, s: String) -> void:
if k == 0:
e.text = s
return
while e.cells.size() < k:
e.cells.append("")
e.cells[k - 1] = s

View file

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

View file

@ -29,6 +29,8 @@ func fill(col: VBoxContainer, build: bool, ranged: bool, collapsed: bool) -> voi
col.add_child(pad)
var numw := card._num_width(build, ranged)
if card.rows_ui.columns_ui.active():
card._list_box.add_child(card.rows_ui.columns_ui.make_header(build, ranged, numw))
for i in card.table.entries.size():
var e := card.table.entries[i]
var lit := card.main.is_entry_lit(card.table.id, e.id)

View file

@ -19,6 +19,7 @@ var parts: Dictionary = {}
var more_label: Label
var sheet_label: RichTextLabel
var kind_rows: TableCardKindRows
var columns_ui: TableCardColumns
## Row styles by state, then +3 for the inspector's selected result, then +6
## for a striped (every second) row.
@ -32,6 +33,7 @@ var _odds: Dictionary = {}
func _init(p_card: TableCard) -> void:
card = p_card
kind_rows = TableCardKindRows.new(self)
columns_ui = TableCardColumns.new(p_card)
# Normal, flicker and lit; then the same with the copper bar of the
# inspector's selected result. Striped rows tint only the normal state, so
# the flicker and the lit result always read over the stripe.
@ -49,6 +51,7 @@ func _init(p_card: TableCard) -> void:
## Forgets the previous build's rows.
func clear() -> void:
parts.clear()
columns_ui.clear()
_odds.clear()
more_label = null
_flick_id = ""
@ -130,6 +133,7 @@ func make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float)
col.add_child(cl)
col.add_child(edit.text_edit(e, index, chosen))
add_rule_chips(col, e)
columns_ui.add_cells(h, e, index, true)
if not ranged and not fixed:
h.add_child(edit.weight_edit(e))
if not fixed and not chosen:
@ -146,6 +150,7 @@ func make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float)
col.add_child(text)
add_rule_chips(col, e)
h.add_child(col)
columns_ui.add_cells(h, e, index, false)
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
if ranged and table.has_chances():
var pct := Style.make_label("", Style.body(true), 12, Style.MUTED)
@ -207,6 +212,9 @@ func row_text(e: TableEntry) -> String:
var table := card.table
var main := card.main
var rolled := main.lit_text(table.id, e.id)
if columns_ui.active():
# The lit text is "Resources: Rich · Water: …"; this row shows column 0.
rolled = str(columns_ui.rolled_cell(table.entries.find(e), 0).get("text", ""))
var s := RichText.decorate(rolled) if rolled != "" else RichText.preview(e.text, main.data)
var muted := Style.MUTED.to_html(false)
if table.kind == RollTable.KIND_LOOP:
@ -355,6 +363,7 @@ func update_row_text(eid: String) -> void:
var want := row_text(p["entry"])
if text.text != want:
text.text = want
columns_ui.refresh(eid)
func flick_random() -> void:

View file

@ -2,10 +2,14 @@ class_name TableCardValue
extends RefCounted
## The body of a variable card (its live value, big) or a collection card (its
## members with live values), re-rendered by refresh() after rolls and edits.
## A scale card also shows its steps in a row with the current one marked.
var card: TableCard
var var_value: Label
var var_hint: Label
## Scale cards: the steps in a row, refilled when the current step changes.
var steps_row: HFlowContainer
var steps_cache := ""
## Collection cards: the member list, refilled by refresh().
var members_box: VBoxContainer
var members_cache := ""
@ -19,6 +23,8 @@ func _init(p_card: TableCard) -> void:
func clear() -> void:
var_value = null
var_hint = null
steps_row = null
steps_cache = ""
members_box = null
members_cache = ""
@ -40,6 +46,12 @@ func make_variable_body(build: bool) -> Control:
var_value.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
var_value.mouse_filter = Control.MOUSE_FILTER_PASS
v.add_child(var_value)
if table.is_scale():
steps_row = HFlowContainer.new()
steps_row.add_theme_constant_override("h_separation", 3)
steps_row.add_theme_constant_override("v_separation", 3)
steps_row.mouse_filter = Control.MOUSE_FILTER_IGNORE
v.add_child(steps_row)
var_hint = Style.make_label("", Style.body(true), 12, Style.MUTED)
var_hint.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
var_hint.mouse_filter = Control.MOUSE_FILTER_IGNORE
@ -174,3 +186,26 @@ func refresh() -> void:
var_hint.text = hint
var_hint.add_theme_color_override("font_color", Style.DANGER_INK if str(d["error"]) != "" else Style.MUTED)
var_hint.visible = hint != ""
if is_instance_valid(steps_row):
_refresh_steps(str(d["text"]))
## The steps as small chips, the one named `current` filled in.
func _refresh_steps(current: String) -> void:
var steps := card.table.steps
var key := "%s|%s" % [current, "\n".join(steps)]
if key == steps_cache:
return
steps_cache = key
InspectorKit.clear(steps_row)
var at := Scales.position_of(steps, current) - 1
for k in steps.size():
var on := k == at
var chip := PanelContainer.new()
chip.mouse_filter = Control.MOUSE_FILTER_IGNORE
var bg := Style.box(Style.VALUE_BG if on else Color(0, 0, 0, 0), 4, [5, 1, 5, 1])
chip.add_theme_stylebox_override("panel", Style.bordered(bg, 1, Style.VALUE_BORDER if on else Style.RULE))
var l := Style.make_label(str(steps[k]), Style.body_bold(true) if on else Style.body(true), 11, Style.VALUE_INK if on else Style.MUTED)
l.mouse_filter = Control.MOUSE_FILTER_IGNORE
chip.add_child(l)
steps_row.add_child(chip)

View file

@ -57,6 +57,8 @@ static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray:
var err := _initial_error(str(s.get("initial", t.initial)), str(s.get("var_type", t.var_type)))
if err != "":
out.append("Starting value: " + err)
if str(s.get("var_type", t.var_type)) == RollTable.VAR_SCALE and s.has("steps") and Scales.clean(s["steps"]).size() < 2:
out.append("A scale needs at least two steps, one per line.")
return out
@ -163,6 +165,7 @@ static func _apply_kind(t: RollTable, s: Dictionary) -> void:
if RollTable.VAR_TYPES.has(vt):
t.var_type = vt
t.initial = str(s.get("initial", t.initial)).strip_edges()
_apply_scale(t, s)
RollTable.KIND_ROUTER:
var cases: Array = s.get("cases", [])
for i in mini(cases.size(), t.entries.size()):
@ -174,6 +177,19 @@ static func _apply_kind(t: RollTable, s: Dictionary) -> void:
t.entries[0].text = str(s["template"])
## A scale card's steps (from `s`, else the defaults when it has none) and a
## starting value that is one of them (else the first step).
static func _apply_scale(t: RollTable, s: Dictionary) -> void:
if not t.is_scale():
return
if s.has("steps"):
t.steps = Scales.clean(s["steps"])
if t.steps.is_empty():
t.steps = ScaleFields.default_steps()
if Scales.position_of(t.steps, Builder.unquote(t.initial)) == 0:
t.initial = ScaleFields.initial_text(t.steps[0])
## 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

View file

@ -9,12 +9,12 @@ extends Button
signal value_chosen(name: String)
const GROUPS := ["", "Variables", "Collections", "Other values", "Roll values"]
const KIND_WORDS := {"number": "number", "text": "text", "list": "list", "collection": "collection"}
const KIND_WORDS := {"number": "number", "text": "text", "list": "list", "collection": "collection", "scale": "scale"}
var main: Main
## The chosen value's name ("@luck", "@skill_*", "tier"), or "".
var value := ""
## Kinds offered ([] for all): "number", "text", "list", "collection".
## Kinds offered ([] for all): "number", "text", "list", "collection", "scale".
var kinds: Array = []
## Extra items listed first: Array of {name, label, kind?}.
var extras: Array = []