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 @_ (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" 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] = [] ## 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] = [] ## 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 "" 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: 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 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: 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: 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". 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)