TableTower/core/roll_table.gd

451 lines
14 KiB
GDScript3
Raw Normal View History

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 also accept a full expression in `dice` ("2d6 + dm(@end)",
## "@terms"). Anything that isn't plain dice is evaluated with Expr; values
## past the lowest or highest range clamp to that range, and chances aren't
## known (chance() is 0, has_chances() false).
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 KINDS: Array[String] = [KIND_ROLL, KIND_CHOICE, KIND_LOOP, KIND_VARIABLE, KIND_SHEET, KIND_ROUTER]
## 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"]
const VAR_TYPES: Array[String] = ["number", "text", "list"]
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] = []
## Dice expression for ranged tables, e.g. "1d100", "2d6", "1d8+2", or any
## expression such as "2d6 + dm(@end)".
var dice: String = DEFAULT_DICE
## 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"
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 = ""
## 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 = ""
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").
## 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.
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"
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"))
return t
## 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
## Rolls the ranged table's dice. Returns {"value": int, "error": String}.
func roll_value(ctx: RollContext) -> Dictionary:
if not is_expr_dice():
return {"value": dice_obj().roll(ctx.rng), "error": ""}
var r := Expr.evaluate(dice, ctx)
if r["error"] != "":
return {"value": 0, "error": r["error"]}
return {"value": Expr.as_int(r, 0), "error": ""}
## Label for the dice: "d100", "2d6", "1d8+2". Plain tables label by entry
## count; expression dice show the expression.
func dice_label() -> String:
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 rolled (1 on plain tables). For expression dice,
## the lowest range start.
func min_value() -> int:
if not is_ranged():
return 1
if is_expr_dice():
return _range_span().x
return dice_obj().min_value()
## Highest value that can be rolled. Plain tables: the entry count. For
## expression dice, the highest range end.
func die_size() -> int:
if is_ranged():
if is_expr_dice():
return _range_span().y
return dice_obj().max_value()
return entries.size()
## Vector2i(lowest range start, highest range end) over ranged entries.
func _range_span() -> Vector2i:
var lo := 0
var hi := 0
var first := true
for e in entries:
if not e.has_range:
continue
if first:
lo = e.range_lo
hi = e.range_hi
first = false
else:
lo = mini(lo, e.range_lo)
hi = maxi(hi, e.range_hi)
return Vector2i(lo, hi)
func total_weight() -> int:
var w := 0
for e in entries:
w += maxi(0, e.weight)
return w
## Formats a die value the way printed tables do: d100 values are two digits
## and 100 is written "00".
func fmt(value: int) -> String:
var two_digit := (dice_obj().is_d100() and not is_expr_dice()) if is_ranged() else entries.size() == 100
if two_digit:
return "00" if value == 100 else "%02d" % value
return str(value)
func num_label(e: TableEntry, index: int) -> String:
if not e.has_range:
return fmt(index + 1)
if is_expr_dice():
var span := _range_span()
var ranged := 0
for x in entries:
if x.has_range:
ranged += 1
if ranged > 1:
if e.range_lo == span.x:
return "≤%s" % fmt(e.range_hi)
if e.range_hi == span.y:
return "%s+" % fmt(e.range_lo)
if e.range_lo == e.range_hi:
return fmt(e.range_lo)
return "%s–%s" % [fmt(e.range_lo), fmt(e.range_hi)]
## 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. 0 for expression dice, whose
## chances can't be known (see has_chances()).
func chance(e: TableEntry) -> float:
if is_ranged():
if not e.has_range or is_expr_dice():
return 0.0
return dice_obj().probability_between(e.range_lo, e.range_hi)
var total := total_weight()
return float(maxi(0, e.weight)) / float(total) if total > 0 else 0.0
## True when the entry can come up at all.
func can_come_up(e: TableEntry) -> bool:
if is_ranged():
return e.has_range and (is_expr_dice() or chance(e) > 0.0)
return e.weight > 0
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
## Like entry_index_for(), but a value below the lowest range or above the
## highest one lands on that end range (expression dice).
func entry_index_clamped(value: int) -> int:
var span := _range_span()
return entry_index_for(clampi(value, span.x, span.y))
func find_entry(eid: String) -> TableEntry:
for e in entries:
if e.id == eid:
return e
return null
## Describes gaps, overlaps and out-of-span ranges in a ranged table, or "" when clean.
## Expression dice have no fixed span, so only gaps between ranges and
## overlaps are reported.
func range_problems() -> String:
if not is_ranged():
return ""
var lo := min_value()
var hi := die_size()
if hi - lo > 100000:
return "The ranges span too many values to check."
var hits := PackedInt32Array()
hits.resize(maxi(0, hi - lo + 1))
var outside := PackedStringArray()
for e in entries:
if not e.has_range:
continue
for v in range(maxi(lo, e.range_lo), mini(hi, e.range_hi) + 1):
hits[v - lo] += 1
if e.range_lo < lo or e.range_hi > hi:
outside.append("%s–%s" % [fmt(e.range_lo), fmt(e.range_hi)])
var gaps := _runs(hits, lo, hi, func(h: int) -> bool: return h == 0)
var overlaps := _runs(hits, lo, hi, func(h: int) -> bool: return h > 1)
var parts := PackedStringArray()
if gaps != "":
parts.append("No result for %s." % gaps)
if overlaps != "":
parts.append("%s matches more than one result." % overlaps)
if not outside.is_empty():
parts.append("%s is outside %s–%s." % [", ".join(outside), fmt(lo), fmt(hi)])
return " ".join(parts)
func _runs(hits: PackedInt32Array, lo: int, n: int, test: Callable) -> String:
var out := PackedStringArray()
var start := -1
for v in range(lo, n + 2):
var on: bool = v <= n and test.call(hits[v - lo])
if on and start < 0:
start = v
elif not on and start >= 0:
out.append(fmt(start) if start == v - 1 else "%s–%s" % [fmt(start), fmt(v - 1)])
start = -1
return ", ".join(out)
## 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 is_ranged():
d["dice"] = dice
if card_mode:
d["card_mode"] = true
if deck_empty != "reshuffle":
d["deck_empty"] = deck_empty
if kind == KIND_CHOICE:
if choice != "pick":
d["choice"] = choice
if prompt != "":
d["prompt"] = prompt
if save_as != "":
d["save_as"] = save_as
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
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))
if d.has("dice"):
t.dice = str(d["dice"])
elif int(d.get("die", 0)) > 1:
t.dice = "1d%d" % int(d["die"])
t.card_mode = bool(d.get("card_mode", false))
t.deck_empty = "stop" if str(d.get("deck_empty", "reshuffle")) == "stop" else "reshuffle"
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.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", ""), "")
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)