TableTower/core/roll_context.gd

303 lines
12 KiB
GDScript3
Raw Normal View History

class_name RollContext
extends RefCounted
## State for one top-level roll: chain variables, the collection's persistent
## variables, the RNG, the current depth and the hooks back into the roller.
##
## Create one per top-level roll and share it with every table rolled in that
## chain (inline references and pipes alike).
##
## [b]Hooks the roller must set:[/b]
## - [member resolve_table]: [code]func(name_or_id: String) -> String[/code]. Returns
## the table id, or "" when there is no such table. It should match the id
## exactly or the name case-insensitively, ignoring BBCode in names;
## [method normalize_name] does the name cleanup.
## - [member roll_table]: [code]func(table_id: String, depth: int) -> Dictionary[/code].
## Rolls the table at the given depth and returns a result node.
##
## [b]Node contract for roll_table:[/b]
## - Returns [code]{}[/code] (empty) if the table doesn't exist; it is then shown
## with the missing-table marker.
## - Otherwise the node must have [code]"summary": String[/code], the BBCode text
## that replaces the reference inline (normally the node's expanded entry text).
## It may contain internal [url] markers from deeper expansions.
## - Every other key (table, entry, value, children, stop, ...) belongs to the
## roller; TextExpander only collects the nodes in its "children" output.
## - When the roller itself stops (depth limit, empty table), it still returns a
## node whose summary explains why, for example [method TextExpander.deep_marker].
## - roll_table may change [member depth] while it runs; TextExpander restores it.
##
## [b]Logic cards[/b] (docs/LOGIC.md): the context also carries the prompt hook
## for choice cards, the action counter and limit, the tree built so far
## ([member root]) and the board, for variable cards and display names.
## Variable values are Variants: int, float or String.
const DEFAULT_MAX_DEPTH := 32
## Most actions (a table rolled or answered, or one loop pass) one top-level
## roll may take.
const DEFAULT_MAX_ACTIONS := 10000
## Chain variables: name (no "@") -> value (String, int or float). Fresh for
## every top-level roll. The roller sets "answer" and "i".
var chain_vars: Dictionary = {}
## The collection's persistent variables, owned and saved elsewhere:
## name (without the "@") -> {"value": Variant, "source": table_id}.
## This is the caller's Dictionary itself, not a copy, so saves show up there.
var persistent_vars: Dictionary = {}
## True once save() has written a persistent variable in this roll, so the caller
## knows local state needs saving.
var persistent_changed: bool = false
## Depth of the text currently being expanded. References in that text are
## rolled at this depth. The roller sets it (depth + 1 for an entry's text).
var depth: int = 0
## References at a depth greater than this show the "chain too deep" marker.
var max_depth: int = DEFAULT_MAX_DEPTH
var rng: RandomNumberGenerator = null
## func(name_or_id: String) -> String (table id or "").
var resolve_table: Callable = Callable()
## func(table_id: String, depth: int) -> Dictionary (a result node).
var roll_table: Callable = Callable()
## Coroutine form of roll_table, used by TextExpander.expand_async so that a
## reference into a choice card can prompt.
## func(table_id: String, depth: int) -> Dictionary
var roll_table_async: Callable = Callable()
## The board being rolled (variable cards, display names). May be null.
var board: TowerBoard = null
## Choice-card hook: func(request: Dictionary) -> Variant, awaited by the
## roller. Not set (the default) means the headless answers: Random for a pick,
## min for a number, "" for text. See docs/LOGIC.md §8 and Roller.ask().
var prompt: Callable = Callable()
## Actions taken so far in this top-level roll, and the limit.
var actions: int = 0
var max_actions: int = DEFAULT_MAX_ACTIONS
## Why the roll stopped early, "" while it runs normally: the action-limit
## message or "Cancelled". Once set, the roller unwinds and keeps what it has.
var halted: String = ""
## The result tree of the current top-level roll, filled in while it runs, so
## a UI can show the steps so far while a prompt is open (Roller.progress()).
var root: Dictionary = {}
## Nesting of running roller chains (internal to Roller).
var running: int = 0
## While true the roller never awaits the prompt hook (sync Roller.roll()).
var no_prompt: bool = false
## While an Array, every die Expr or a ranged table rolls appends its face
## here (the roller sets it around a roll to record "nat" and the why trace).
## null (the default) records nothing.
var faces: Variant = null
var _decl: Dictionary = {}
var _decl_built := false
func _init(p_persistent: Dictionary = {}, p_rng: RandomNumberGenerator = null) -> void:
persistent_vars = p_persistent
rng = p_rng if p_rng != null else RandomNumberGenerator.new()
## True for names that start with "@" (persistent variables).
static func is_persistent(name: String) -> bool:
return name.strip_edges().begins_with("@")
## Saves a value. Names starting with "@" go to the persistent variables
## (stored without the "@", with the source table id); others to the chain.
## Whole floats are stored as ints.
func save(name: String, value: Variant, source_id: String = "") -> void:
var n: String = name.strip_edges()
value = Expr.normalize(value)
if n.begins_with("@"):
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 != "":
chain_vars[n] = value
## Saves a result (a thread's or column's "save as", a choice's answer, an
## inline [[Table -> @x]]): like save(), except that a variable declared as a
## list keeps its items and gains the new ones, so repeated rolls collect.
func save_result(name: String, value: Variant, source_id: String = "") -> void:
var n := name.strip_edges()
var card := declared(n) if n.begins_with("@") else null
if card == null or card.var_type != "list":
save(n, value, source_id)
return
var list: Variant = get_value(n)
for item in Expr.list_items(Formatter.strip_tags(Expr.format_value(value))):
list = Effects.list_with(list, item)
save(n, list if list != null else "", source_id)
## Returns the saved value as display text (numbers without ".0"), or null
## when the variable isn't set. "@name" reads a persistent variable, "name" a
## chain variable.
func lookup(name: String) -> Variant:
var v: Variant = get_value(name)
return null if v == null else Expr.format_value(v)
## The saved value itself (int, float or String), or null when it isn't set.
func get_value(name: String) -> Variant:
var n: String = name.strip_edges()
if n.begins_with("@"):
var entry: Variant = persistent_vars.get(n.substr(1))
if entry is Dictionary:
return Expr.normalize((entry as Dictionary).get("value", ""))
return Expr.normalize(entry)
if chain_vars.has(n):
return Expr.normalize(chain_vars[n])
return null
## Forgets a variable ("@name" or a chain variable name).
func erase(name: String) -> void:
var n: String = name.strip_edges()
if n.begins_with("@"):
if persistent_vars.erase(n.substr(1)):
persistent_changed = true
else:
chain_vars.erase(n)
## How many board variables are set whose names start with `prefix` (a leading
## "@" and a trailing "*" are ignored).
func count_vars(prefix: String) -> int:
var p := _prefix(prefix)
var k := 0
for name: String in persistent_vars:
if name.begins_with(p):
k += 1
return k
## Board variables whose names start with `prefix`, sorted by label: Array of
## {name (no "@"), label (the part after the prefix, title-cased, "_" read as a
## space), value}.
func list_vars(prefix: String) -> Array[Dictionary]:
return RollContext.vars_with_prefix(persistent_vars, prefix)
## list_vars() for a plain variables Dictionary (name -> {value, source}), for
## UI code without a roll context.
static func vars_with_prefix(vars: Dictionary, prefix: String) -> Array[Dictionary]:
var p := _prefix(prefix)
var out: Array[Dictionary] = []
for name: String in vars:
if not name.begins_with(p):
continue
var rest := name.substr(p.length())
var raw: Variant = vars[name]
var value: Variant = (raw as Dictionary).get("value", "") if raw is Dictionary else raw
out.append({"name": name, "label": pretty_name(rest if rest != "" else name),
"value": Expr.normalize(value)})
out.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
return str(a["label"]).naturalnocasecmp_to(str(b["label"])) < 0)
return out
## The {@prefix_*} text: "Gun Combat 1, Pilot 0".
func list_text(prefix: String) -> String:
var parts := PackedStringArray()
for v in list_vars(prefix):
var shown := Expr.format_value(v["value"])
parts.append(str(v["label"]) if shown == "" else "%s %s" % [v["label"], shown])
return ", ".join(parts)
## "gun_combat" -> "Gun Combat".
static func pretty_name(name: String) -> String:
var words := PackedStringArray()
for w in name.replace("_", " ").strip_edges().split(" ", false):
words.append(w.substr(0, 1).to_upper() + w.substr(1))
return " ".join(words)
## Display name of a board variable for effect logs: the variable card's name
## when a card declares it, else the name title-cased ("skill_pilot" ->
## "Skill Pilot"). `name` may start with "@".
func display_name(name: String) -> String:
var n := name.strip_edges().trim_prefix("@")
var card := declared(n)
if card != null and Formatter.strip_tags(card.name).strip_edges() != "":
return Formatter.strip_tags(card.name).strip_edges()
return pretty_name(n)
## The variable card that declares board variable `name` (no "@"), or null.
func declared(name: String) -> RollTable:
if not _decl_built:
_decl_built = true
_decl.clear()
if board != null:
for t in board.tables:
if t.kind == RollTable.KIND_VARIABLE and t.var_name != "" and t.var_type != RollTable.VAR_COLLECTION and not _decl.has(t.var_name):
_decl[t.var_name] = t
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("")
var out: Array[String] = []
for k: String in _decl:
out.append(k)
return out
## Call after the board's variable cards change.
func forget_declarations() -> void:
_decl_built = false
static func _prefix(prefix: String) -> String:
return prefix.strip_edges().trim_prefix("@").trim_suffix("*")
## Calls resolve_table, returning "" if the hook isn't set.
func resolve(name_or_id: String) -> String:
if not resolve_table.is_valid():
return ""
return str(resolve_table.call(name_or_id))
## Calls roll_table at the current depth and restores depth afterwards.
## Returns {} if the hook isn't set or the roller returned something that isn't
## a Dictionary.
func roll(table_id: String) -> Dictionary:
if not roll_table.is_valid():
return {}
var d: int = depth
var result: Variant = roll_table.call(table_id, d)
depth = d
return result as Dictionary if result is Dictionary else {}
## Coroutine form of roll(): uses roll_table_async when it's set, else
## roll_table. Restores depth afterwards.
func roll_async(table_id: String) -> Dictionary:
if not roll_table_async.is_valid():
return roll(table_id)
var d: int = depth
var result: Variant = await roll_table_async.call(table_id, d)
depth = d
return result as Dictionary if result is Dictionary else {}
## Lowercase, trimmed, BBCode-free form of a table name, for matching
## [[references]] against names: normalize_name("[b]Gems[/b] ") == "gems".
static func normalize_name(name: String) -> String:
return Formatter.strip_tags(name).strip_edges().to_lower()