- Card threads: a port on each card's bottom edge. Plain runs after any result (once the result's own threads finish); Otherwise runs only when no thread of the result ran. Saved as card_threads (LOGIC.md 3g). - Typing on long cards no longer rebuilds the inspector or the card per key (~175 ms -> ~7 ms). Timing tool: tests/perf_typing.gd. - "+ Add result" scrolls to the new row and focuses it. - Mouse wheel zooms; Shift+wheel pans sideways; scrolling lists keep it. - "SPREAD" caption over the switcher; Morgan's first-run welcome. - docs/MECHANICS.md: checklist of table mechanics for planning. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
392 lines
14 KiB
GDScript
392 lines
14 KiB
GDScript
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"
|
||
## 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"]
|
||
const CHECK_DEFAULT_DICE := "2d6"
|
||
const CHECK_DEFAULT_TARGET := "8"
|
||
## The id of a card's outlet (CardThreads), so its threads have pipe keys.
|
||
const OUTLET_ID := "_card"
|
||
|
||
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 = ""
|
||
## Ranged even while no result has a range (an empty card switched to Ranged).
|
||
## Results with ranges make a card ranged either way (is_ranged).
|
||
var ranged: bool = false
|
||
## How Build edits the ranges: RangeWeights.WEIGHTS or RangeWeights.RANGES.
|
||
## Cards made before this setting existed load as Ranges, so nothing moves.
|
||
var range_edit: String = "ranges"
|
||
## Ranges mode: rows put themselves back in roll order after edits and drags.
|
||
var auto_sort: bool = true
|
||
## 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] = []
|
||
## Holds the card threads (CardThreads): a row that is never rolled or shown.
|
||
var outlet: TableEntry = TableEntry.new(OUTLET_ID, "")
|
||
## 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
|
||
## Cards with columns: when not "", the result reads as the column texts joined
|
||
## with this ("Ash" + " " + "Canyons" = "Ash Canyons") instead of "1st Part:
|
||
## Ash · 2nd Part: Canyons", and that phrase is what a thread saves.
|
||
var column_join: String = ""
|
||
|
||
## 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 = ""
|
||
## Scale variables: the ordered steps, lowest first.
|
||
var steps: Array[String] = []
|
||
## A cost to roll this card (RollCosts): the value ("@luck") and the amount
|
||
## taken away each time. Empty = free.
|
||
var cost_value: String = ""
|
||
var cost_amount: String = ""
|
||
## List cards: true when the list keeps repeats (an item added every time, in
|
||
## order); false adds an item only if it isn't there yet.
|
||
var list_repeats := false
|
||
## Ledger cards: the entries, [{name, start}] (LedgerMembers).
|
||
var members: Array = []
|
||
## 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 (RollTableFactory).
|
||
static func create(p_kind: String, p_id: String, p_name: String, sub: String = "") -> RollTable: return RollTableFactory.create(p_kind, p_id, p_name, sub)
|
||
|
||
|
||
## 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
|
||
|
||
|
||
## 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 (RollTableIO.clean_inputs).
|
||
static func clean_inputs(v: Variant) -> Array: return RollTableIO.clean_inputs(v)
|
||
|
||
|
||
## 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", "name", "error"} (RollChoice).
|
||
static func parse_options_from(src: String) -> Dictionary: return RollChoice.parse_options_from(src)
|
||
## "each @skill_* that's set, where option_value >= 1" (RollChoice).
|
||
func options_description() -> String: return RollChoice.options_description(self)
|
||
|
||
|
||
## 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:
|
||
if ranged:
|
||
return true
|
||
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:
|
||
if eid == OUTLET_ID:
|
||
return outlet
|
||
for e in entries:
|
||
if e.id == eid:
|
||
return e
|
||
return null
|
||
|
||
|
||
## Every row that threads leave from: the results, then the outlet when the
|
||
## card has card threads. Don't change the returned array.
|
||
func thread_sources() -> Array[TableEntry]:
|
||
if outlet.pipes.is_empty():
|
||
return entries
|
||
var out := entries.duplicate()
|
||
out.append(outlet)
|
||
return out
|
||
|
||
|
||
## 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"
|
||
|
||
|
||
## Gaps, overlaps and out-of-reach ranges, or "" when clean (RollRange.problems).
|
||
func range_problems() -> String: return RollRange.problems(self)
|
||
|
||
|
||
## A variable card's starting value: {"value", "error"} (RollLive).
|
||
func initial_value(ctx: RollContext) -> Dictionary: return RollLive.initial_value(self, ctx)
|
||
## True for plain words that aren't an expression (RollLive.looks_literal).
|
||
static func _looks_literal(src: String) -> bool: return RollLive.looks_literal(src)
|
||
|
||
|
||
func to_dict() -> Dictionary: return RollTableIO.to_dict(self)
|
||
|
||
|
||
static func from_dict(d: Dictionary) -> RollTable: return RollTableIO.from_dict(d)
|
||
|
||
|
||
## Expression fields may arrive as JSON numbers: 3.0 -> "3" (RollTableIO).
|
||
static func expr_text(v: Variant, fallback: String) -> String: return RollTableIO.expr_text(v, fallback)
|