TableTower/core/roll_table.gd
RobinFiredrake ef1dc846d1 Adjust later rolls: Never below / Never above on ranged cards
RollTable.roll_floor and roll_ceiling (numbers or values) limit a ranged
roll's total after its modifier (RollRange.limit). An earlier result's
change (e.g. @atmo_min = 7) can thereby raise or cap a later card's roll.
The inspector's Limits rows take a number or a value; the Why trace says
'raised to 7 (never below Atmo min)'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 19:15:09 -06:00

569 lines
20 KiB
GDScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class_name RollTable
extends RefCounted
## A named list of entries placed on the board.
##
## Plain tables pick by entry weight (6 equal entries = d6). If any entry has a
## range, the table becomes a ranged dice table (1d100 by default, or any dice
## expression) where the probability mass of each range sets its chance.
##
## Every table has a `kind` (docs/LOGIC.md §1): "roll" (the default), "choice",
## "loop", "variable", "sheet" or "router", with the per-kind fields below
## (a router's cases are its entries, each with an entry-level `when`). Use create()
## for a well-formed card of each kind.
##
## Ranged tables may add a modifier to the roll (`dice_mod`, e.g. "@luck"),
## and also accept a full expression in `dice` ("2d6 + dm(@end)", "@terms").
## With either, a total past the lowest or highest range counts as that end
## result. Chances are known for a modifier (given its value) but not for an
## expression (chance() is 0, has_chances() false). The numbers live in
## RollRange.
const DEFAULT_DICE := "1d100"
const KIND_ROLL := "roll"
const KIND_CHOICE := "choice"
const KIND_LOOP := "loop"
const KIND_VARIABLE := "variable"
const KIND_SHEET := "sheet"
const KIND_ROUTER := "router"
const KIND_CHECK := "check"
const KINDS: Array[String] = [KIND_ROLL, KIND_CHOICE, KIND_LOOP, KIND_VARIABLE, KIND_SHEET, KIND_ROUTER, KIND_CHECK]
## A new router's first case condition (an even chance, so both cases can come up).
const ROUTER_DEFAULT_WHEN := "1d6 >= 4"
const CHOICES: Array[String] = ["pick", "number", "text"]
const LOOPS: Array[String] = ["times", "while", "until"]
## 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]
## Check cards (docs/PLAIN.md §4.1): success when the total is >= ("ge") or
## <= ("le") the target.
const CHECK_CMPS: Array[String] = ["ge", "le"]
const CHECK_DEFAULT_DICE := "2d6"
const CHECK_DEFAULT_TARGET := "8"
var id: String = ""
var name: String = ""
var position: Vector2 = Vector2.ZERO
var collapsed: bool = false
## Longer description (may contain BBCode).
var details: String = ""
var tags: Array[String] = []
## The card's own colour ("#hex") for its frame and header; "" = the theme's.
var color: String = ""
## The size the user dragged the card to: its width in Play (Build adds a
## little), and the height of its results list, which then scrolls. 0 = automatic.
var width: float = 0.0
var list_height: float = 0.0
## Ranged tables: the total never goes below / above these (numbers or
## expressions such as @atmo_min, often set by an earlier result). "" = none.
var roll_floor: String = ""
var roll_ceiling: String = ""
## Dice expression for ranged tables, e.g. "1d100", "2d6", "1d8+2", or any
## expression such as "2d6 + dm(@end)".
var dice: String = DEFAULT_DICE
## Ranged tables: the modifier added to the dice, an expression ("@luck",
## "-@fatigue", "dm(@str)", "2"), or "" for none.
var dice_mod: String = ""
## Card mode: entries are drawn without replacement until the deck is empty.
var card_mode: bool = false
## What happens when the deck runs out: "reshuffle" or "stop".
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] = []
## One of KINDS.
var kind: String = KIND_ROLL
## Choice cards: "pick", "number" or "text".
var choice: String = "pick"
## Choice cards: the question, BBCode with {@var} expansion.
var prompt: String = ""
## Choice cards: variable the answer is saved under ("@name" or a chain name).
var save_as: String = ""
## Pick choices: options from variables (docs/LOGIC.md §2a). "@prefix_*"
## gives one option per set variable with that prefix, "@list" one option per
## item of a list variable. "" for a fixed list. When it's set, entries[0] is
## the Chosen entry (it happens for whichever dynamic option is picked) and
## any other entries are fixed extras.
var options_from: String = ""
## Pick choices with options_from: an expression each candidate must pass,
## with the chain variables option, option_label and option_value bound.
var options_where: String = ""
## Number choices: bounds, as expressions.
var min_expr: String = "0"
var max_expr: String = "99"
## Loop cards: "times", "while" or "until", and the count or condition.
var loop_mode: String = "times"
var loop_expr: String = ""
## Variable cards: the variable's name (no "@"), its type and starting value
## (an expression).
var var_name: String = ""
var var_type: String = "number"
var initial: String = ""
## Check cards: the dice, the modifier and the target (expressions) and the
## comparison ("ge" or "le"). entries[0] is Success, entries[1] Failure.
var check_dice: String = CHECK_DEFAULT_DICE
var check_mod: String = ""
var check_cmp: String = "ge"
var check_target: String = CHECK_DEFAULT_TARGET
## Card inputs (any kind but variable): Array of {"name": String, "label":
## String, "default": String (an expression; "" reads as 0)}. While a pipe's
## subtree runs, each input is a chain value (the pipe's "with" value, or the
## default).
var inputs: Array = []
var _dice_cache: Dice = null
var _dice_cache_text: String = ""
var _dice_plain: bool = true
func _init(p_id: String = "", p_name: String = "") -> void:
id = p_id
name = p_name
## A well-formed card of any kind. `sub` picks the variant: the choice
## ("pick", "number", "text"), the loop mode ("times", "while", "until") or
## the variable type ("number", "text", "list", "collection").
## roll: four "Result N" entries · choice pick: three options ·
## choice number/text: one "Answer" entry · loop: "Each time" and
## "Afterwards" · variable: no entries · sheet: one template entry ·
## router: an "if …" case (when ROUTER_DEFAULT_WHEN) and an "Otherwise" case ·
## check: "Success" and "Failure" (2d6 vs 8) · variable "collection": the
## stem is the name's slug without a final "s" ("Skills" -> "skill").
static func create(p_kind: String, p_id: String, p_name: String, sub: String = "") -> RollTable:
var t := RollTable.new(p_id, p_name)
t.kind = p_kind if KINDS.has(p_kind) else KIND_ROLL
match t.kind:
KIND_ROLL:
for n in range(1, 5):
t.entries.append(TableEntry.new("e%d" % n, "Result %d" % n))
KIND_CHOICE:
t.choice = sub if CHOICES.has(sub) else "pick"
match t.choice:
"pick":
t.prompt = "Which one?"
for n in range(1, 4):
t.entries.append(TableEntry.new("e%d" % n, "Option %d" % n))
"number":
t.prompt = "How many?"
t.entries.append(TableEntry.new("e1", "Answer"))
"text":
t.prompt = "What is it?"
t.entries.append(TableEntry.new("e1", "Answer"))
KIND_LOOP:
t.loop_mode = sub if LOOPS.has(sub) else "times"
t.loop_expr = "3" if t.loop_mode == "times" else "i < 3"
t.entries.append(TableEntry.new("e1", "Each time"))
t.entries.append(TableEntry.new("e2", "Afterwards"))
KIND_VARIABLE:
t.var_type = sub if VAR_TYPES.has(sub) else "number"
t.var_name = JsonIO.slug(Formatter.strip_tags(p_name), "var") if p_name != "" else "var"
if t.var_type == VAR_COLLECTION and t.var_name.length() > 3 and t.var_name.ends_with("s") and not t.var_name.ends_with("ss"):
t.var_name = t.var_name.substr(0, t.var_name.length() - 1)
t.initial = "0" if t.var_type == "number" else ""
KIND_SHEET:
t.entries.append(TableEntry.new("e1", "[b]%s[/b]" % p_name))
KIND_ROUTER:
var first := TableEntry.new("e1", "if …")
first.when = ROUTER_DEFAULT_WHEN
t.entries.append(first)
t.entries.append(TableEntry.new("e2", "Otherwise"))
KIND_CHECK:
t.entries.append(TableEntry.new("e1", "Success"))
t.entries.append(TableEntry.new("e2", "Failure"))
return t
## True for a collection variable card.
func is_collection() -> bool:
return kind == KIND_VARIABLE and var_type == VAR_COLLECTION
## Names of the declared inputs, in order.
func input_names() -> Array[String]:
var out: Array[String] = []
for inp: Dictionary in inputs:
out.append(str(inp.get("name", "")))
return out
## The declared input called `name`, or {}.
func find_input(input_name: String) -> Dictionary:
for inp: Dictionary in inputs:
if str(inp.get("name", "")) == input_name:
return inp
return {}
## Cleans an "inputs" value from JSON or the UI: Array of {name, label,
## default} with names trimmed (a leading "@" dropped) and empty names left
## out. Numbers become expression text.
static func clean_inputs(v: Variant) -> Array:
var out: Array = []
if not (v is Array):
return out
for item: Variant in v:
var nm := ""
var label := ""
var def := ""
if item is Dictionary:
nm = str(item.get("name", "")) if item.get("name") != null else ""
label = str(item.get("label", "")) if item.get("label") != null else ""
def = expr_text(item.get("default", ""), "")
elif item is String:
nm = item
nm = nm.strip_edges().trim_prefix("@")
if nm == "":
continue
out.append({"name": nm, "label": label.strip_edges(), "default": def.strip_edges()})
return out
## True for a pick choice whose options come from variables (options_from).
func is_dynamic() -> bool:
return kind == KIND_CHOICE and choice == "pick" and options_from.strip_edges() != ""
## Index of the first fixed option on a pick choice: 1 when entries[0] is the
## Chosen entry of a dynamic card, else 0.
func fixed_start() -> int:
return 1 if is_dynamic() else 0
## Parses an options_from pattern: {"kind": "prefix" | "list" | "", "name":
## the prefix or list variable name without "@" and "*", "error": String}.
## "@skill_*" is a prefix, "@contacts" a list variable.
static func parse_options_from(src: String) -> Dictionary:
var s := src.strip_edges()
if s == "":
return {"kind": "", "name": "", "error": ""}
if not s.begins_with("@"):
return {"kind": "", "name": "", "error": "Write @prefix_* (each set variable with that prefix) or @list (each item of a list variable)"}
var prefix := s.ends_with("*")
var name := s.substr(1, s.length() - (2 if prefix else 1)).to_lower()
if name == "":
return {"kind": "", "name": "", "error": "Give a name after @, e.g. @skill_* or @contacts"}
if RegEx.create_from_string("^[a-z_][a-z0-9_]*$").search(name) == null:
return {"kind": "", "name": "", "error": "\"%s\" isn't a variable name (lowercase letters, digits and _)" % s}
return {"kind": "prefix" if prefix else "list", "name": name, "error": ""}
## "each @skill_* that's set, where option_value >= 1" (for previews and cards).
func options_description() -> String:
var p := parse_options_from(options_from)
var s := ""
match str(p["kind"]):
"prefix":
s = "each @%s* that's set" % p["name"]
"list":
s = "each item of @%s" % p["name"]
_:
s = options_from.strip_edges()
if options_where.strip_edges() != "":
s += ", where " + options_where.strip_edges()
return s
## Router cards: index of the first case that is an Otherwise case (empty
## `when`), or -1.
func otherwise_index() -> int:
for i in entries.size():
if entries[i].when.strip_edges() == "":
return i
return -1
func is_kind(k: String) -> bool:
return kind == k
func is_ranged() -> bool:
for e in entries:
if e.has_range:
return true
return false
## True when `dice` is a full expression rather than plain dice (ranged tables).
func is_expr_dice() -> bool:
dice_obj()
return is_ranged() and not _dice_plain
## The parsed dice expression (falls back to 1d100 if `dice` is invalid or an
## expression; see is_expr_dice()).
func dice_obj() -> Dice:
if _dice_cache == null or _dice_cache_text != dice:
var d := Dice.parse(dice)
_dice_plain = d.valid or dice.strip_edges() == ""
_dice_cache = d if d.valid else Dice.make(1, 100)
_dice_cache_text = dice
return _dice_cache
## The roll modifier, if any (see RollRange): true when dice_mod is set.
func has_mod() -> bool:
return dice_mod.strip_edges() != ""
## The whole roll as text: "1d20 + @luck", or the dice alone.
func roll_text() -> String:
return RollRange.join(dice, dice_mod)
## True when totals past the ends count as the end results (RollRange.clamps).
func clamps() -> bool:
return RollRange.clamps(self)
## Rolls the dice and adds the modifier. Returns {"value": int, "error": String}.
func roll_value(ctx: RollContext) -> Dictionary:
return RollRange.roll_value(self, ctx)
## Label for the dice: "d100", "2d6", "1d8+2". Plain tables label by entry
## count; expression dice show the expression.
func dice_label() -> String:
if kind == KIND_CHECK:
return check_dice.strip_edges()
if is_ranged():
return dice.strip_edges() if is_expr_dice() else dice_obj().label()
return "d%d" % die_size()
## Lowest value that can be shown or rolled (RollRange.min_value).
func min_value() -> int:
return RollRange.min_value(self)
## Highest value (RollRange.max_value). Plain tables: the entry count.
func die_size() -> int:
return RollRange.max_value(self)
func total_weight() -> int:
var w := 0
for e in entries:
w += maxi(0, e.weight)
return w
func fmt(value: int) -> String:
return RollRange.fmt(self, value)
func num_label(e: TableEntry, index: int) -> String:
return RollRange.num_label(self, e, index)
## False when chances can't be known (expression dice).
func has_chances() -> bool:
return not is_expr_dice()
## Chance (0–1) that a roll lands on this entry, with the modifier at `mod`.
func chance(e: TableEntry, mod: int = 0) -> float:
return RollRange.chance(self, e, mod)
## True when the entry can come up at all.
func can_come_up(e: TableEntry) -> bool:
return RollRange.can_come_up(self, e)
## The entry whose range holds `value` exactly, or -1.
func entry_index_for(value: int) -> int:
for i in entries.size():
var e := entries[i]
if e.has_range and value >= e.range_lo and value <= e.range_hi:
return i
return -1
## The entry a rolled total picks: past the ends counts as the end result on
## a table that clamps (RollRange.index_for).
func entry_index_clamped(value: int) -> int:
return RollRange.index_for(self, value)
func find_entry(eid: String) -> TableEntry:
for e in entries:
if e.id == eid:
return e
return null
## Gaps, overlaps and out-of-reach ranges, or "" when clean (RollRange.problems).
## The result an empty Deck-mode card gives when it waits for Shuffle.
func empty_text() -> String:
return deck_empty_text if deck_empty_text.strip_edges() != "" else "Empty"
func range_problems() -> String:
return RollRange.problems(self)
## A variable card's starting value: {"value", "error"}. An empty `initial`
## gives 0 for numbers and "" otherwise. For text and list variables, plain
## words that aren't an expression ("Aslan") are taken as they are.
func initial_value(ctx: RollContext) -> Dictionary:
var src := initial.strip_edges()
if src == "":
return {"value": 0 if var_type == "number" else "", "error": ""}
if var_type != "number" and _looks_literal(src):
return {"value": src, "error": ""}
var r := Expr.evaluate(src, ctx)
if r["error"] != "":
return {"value": 0 if var_type == "number" else "", "error": r["error"]}
return r
static func _looks_literal(src: String) -> bool:
if src.begins_with("\"") or src.begins_with("'") or src.contains("@") or src.contains("("):
return false
return RegEx.create_from_string("^[^+\\-*/%=<>!&|]*$").search(src) != null and not src.is_valid_float()
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
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
## Expression fields may arrive as JSON numbers: 3.0 -> "3".
static func expr_text(v: Variant, fallback: String) -> String:
if v == null:
return fallback
if v is float or v is int:
return Expr.format_value(v)
return str(v)