Size audit: split roll_table, roller and tower_board

New helpers: BoardGroups (group nesting and membership), BoardFileIO
(migrate, atomic writes), RollNodes (result-node helpers), RollLive (live
values and starting values) and RollTableFactory (new cards). RollPipes now
holds the pipe and pause frames, RollChoice reads options_from, and
RollTableIO cleans inputs. The original files keep one-line delegators.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
RobinFiredrake 2026-11-14 13:19:54 -06:00
parent 4f8b3c7934
commit 63929a9fc2
16 changed files with 672 additions and 545 deletions

57
core/board_file_io.gd Normal file
View file

@ -0,0 +1,57 @@
class_name BoardFileIO
extends RefCounted
## Board files on disk: upgrading old file versions (migrate) and writing
## text safely through a temp file. TowerBoard hands this work to here.
## Upgrades a parsed file to TowerBoard.FORMAT_VERSION, one version step at a
## time. To add a version, bump FORMAT_VERSION and add a _migrate_N_to_N1 step here.
static func migrate(data: Dictionary) -> Dictionary:
var version: int = int(data.get("format_version", 1))
while version < TowerBoard.FORMAT_VERSION:
match version:
1:
data = _migrate_1_to_2(data)
_:
break
version += 1
data["format_version"] = version
return data
## Version 1 had no id or name; they are filled in by whoever imports the file.
static func _migrate_1_to_2(data: Dictionary) -> Dictionary:
data["format_version"] = 2
if not data.has("id"):
data["id"] = ""
if not data.has("name"):
data["name"] = ""
return data
## Writes text to path via a temp file and a rename, so a crash can't leave a
## half-written file. Creates the folder if needed.
static func write_text_atomic(path: String, text: String) -> Error:
var dir := path.get_base_dir()
if not DirAccess.dir_exists_absolute(dir):
var mk := DirAccess.make_dir_recursive_absolute(dir)
if mk != OK:
return mk
var tmp := path + ".tmp"
var file := FileAccess.open(tmp, FileAccess.WRITE)
if file == null:
return FileAccess.get_open_error()
file.store_string(text)
var write_error := file.get_error()
file.close()
if write_error != OK:
DirAccess.remove_absolute(tmp)
return write_error
var err := DirAccess.rename_absolute(tmp, path)
if err != OK and FileAccess.file_exists(path):
# Some platforms won't rename over an existing file.
DirAccess.remove_absolute(path)
err = DirAccess.rename_absolute(tmp, path)
if err != OK:
DirAccess.remove_absolute(tmp)
return err

View file

@ -0,0 +1 @@
uid://bx1lxbnni7hsu

180
core/board_groups.gd Normal file
View file

@ -0,0 +1,180 @@
class_name BoardGroups
extends RefCounted
## Group cards on a board: nesting groups inside each other, putting tables
## in and out of groups, and moving, ungrouping or deleting whole groups.
## TowerBoard's group methods hand their work to the functions here.
## The groups sitting directly inside group `gid`.
static func child_groups(board: TowerBoard, gid: String) -> Array[TableGroup]:
var out: Array[TableGroup] = []
for group in board.groups:
if group.parent == gid and gid != "":
out.append(group)
return out
## Every table inside a group, its inner groups' tables included.
static func tables_in(board: TowerBoard, gid: String) -> Array[String]:
var out: Array[String] = []
var group := board.get_group(gid)
if group == null:
return out
out.append_array(group.members)
for child in child_groups(board, gid):
out.append_array(tables_in(board, child.id))
return out
## The group and every group inside it, outermost first.
static func groups_in(board: TowerBoard, gid: String) -> Array[TableGroup]:
var out: Array[TableGroup] = []
var group := board.get_group(gid)
if group == null:
return out
out.append(group)
for child in child_groups(board, gid):
out.append_array(groups_in(board, child.id))
return out
## The outermost collapsed group around `group` (not `group` itself), or null
## when nothing around it is collapsed.
static func hidden_by(board: TowerBoard, group: TableGroup) -> TableGroup:
var out: TableGroup = null
var outer := board.get_group(group.parent)
while outer != null:
if outer.collapsed:
out = outer
outer = board.get_group(outer.parent)
return out
## How many groups `group` sits inside.
static func depth_of(board: TowerBoard, group: TableGroup) -> int:
var count := 0
var outer := board.get_group(group.parent)
while outer != null and count < board.groups.size():
count += 1
outer = board.get_group(outer.parent)
return count
## Puts group `gid` inside `parent_id` ("" = the spread). False when that would
## put a group inside itself.
static func set_group_parent(board: TowerBoard, gid: String, parent_id: String) -> bool:
var group := board.get_group(gid)
if group == null:
return false
var outer := board.get_group(parent_id)
while outer != null:
if outer.id == gid:
return false
outer = board.get_group(outer.parent)
group.parent = parent_id
return true
## Makes a group of the given tables (taking them out of any other group).
static func add_group(board: TowerBoard, group_name: String, member_ids: Array, gid: String = "") -> TableGroup:
var group := TableGroup.new(gid if gid != "" else TowerBoard.new_id("g"), group_name)
board.groups.append(group)
for table_id: Variant in member_ids:
add_to_group(board, str(table_id), group.id)
return group
## Puts a table in a group, taking it out of its old one. False if either is missing.
static func add_to_group(board: TowerBoard, table_id: String, gid: String) -> bool:
var group := board.get_group(gid)
if group == null or board.get_table(table_id) == null:
return false
var old := board.group_of(table_id)
if old == group:
return true
if old:
old.members.erase(table_id)
group.members.append(table_id)
return true
## Takes a table out of its group, if it has one.
static func remove_from_group(board: TowerBoard, table_id: String) -> void:
var group := board.group_of(table_id)
if group:
group.members.erase(table_id)
## Removes the group only; its cards and inner groups move up to the group
## around it (or onto the spread).
static func ungroup(board: TowerBoard, gid: String) -> void:
var group := board.get_group(gid)
if group == null:
return
var outer := board.get_group(group.parent)
for child in child_groups(board, gid):
child.parent = group.parent
if outer:
for table_id in group.members:
if not outer.members.has(table_id):
outer.members.append(table_id)
for i in range(board.groups.size() - 1, -1, -1):
if board.groups[i].id == gid:
board.groups.remove_at(i)
## Removes the group, its inner groups and every table in them. Returns the
## removed table ids.
static func delete_group(board: TowerBoard, gid: String) -> Array[String]:
var gone: Array[String] = []
if board.get_group(gid) == null:
return gone
gone.assign(tables_in(board, gid))
for inner in groups_in(board, gid):
board.groups.erase(inner)
for table_id in gone:
board.remove_table(table_id)
return gone
## Moves a group's frame, its inner groups and every table in them by `delta`.
static func move_group(board: TowerBoard, gid: String, delta: Vector2) -> void:
for group in groups_in(board, gid):
group.position += delta
for table_id in group.members:
var table := board.get_table(table_id)
if table:
table.position += delta
## Drops members that aren't tables, keeps each table in its first group only,
## and gives groups unique ids. Empty groups are kept (they can be refilled).
static func clean_groups(board: TowerBoard) -> void:
var table_ids := {}
for table in board.tables:
table_ids[table.id] = true
var taken := {}
var group_ids := {}
for group in board.groups:
if group.id == "" or group_ids.has(group.id):
group.id = TowerBoard.new_id("g")
group_ids[group.id] = true
var keep: Array[String] = []
for member in group.members:
if table_ids.has(member) and not taken.has(member):
taken[member] = true
keep.append(member)
group.members = keep
# Parents must exist and never loop back.
for group in board.groups:
if group.parent != "" and (not group_ids.has(group.parent) or group.parent == group.id):
group.parent = ""
for group in board.groups:
var seen := {group.id: true}
var outer := board.get_group(group.parent)
while outer != null:
if seen.has(outer.id):
group.parent = ""
break
seen[outer.id] = true
outer = board.get_group(outer.parent)

1
core/board_groups.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://81xq5r5axa01

View file

@ -288,3 +288,39 @@ static func _answered(t: RollTable, f: Dictionary, ctx: RollContext, stack: Arra
"kind": RollTable.KIND_CHOICE, "answer": value}
Roller._attach(f, node, ctx)
await Roller._enter(node, f, ctx, stack, false)
# ---------- Reading options_from (RollTable delegates here) ----------
## 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 pattern := src.strip_edges()
if pattern == "":
return {"kind": "", "name": "", "error": ""}
if not pattern.begins_with("@"):
return {"kind": "", "name": "", "error": "Write @prefix_* (each set variable with that prefix) or @list (each item of a list variable)"}
var prefix := pattern.ends_with("*")
var var_name := pattern.substr(1, pattern.length() - (2 if prefix else 1)).to_lower()
if var_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(var_name) == null:
return {"kind": "", "name": "", "error": "\"%s\" isn't a variable name (lowercase letters, digits and _)" % pattern}
return {"kind": "prefix" if prefix else "list", "name": var_name, "error": ""}
## "each @skill_* that's set, where option_value >= 1" (for previews and cards).
static func options_description(table: RollTable) -> String:
var parsed := parse_options_from(table.options_from)
var text := ""
match str(parsed["kind"]):
"prefix":
text = "each @%s* that's set" % parsed["name"]
"list":
text = "each item of @%s" % parsed["name"]
_:
text = table.options_from.strip_edges()
if table.options_where.strip_edges() != "":
text += ", where " + table.options_where.strip_edges()
return text

78
core/roll_live.gd Normal file
View file

@ -0,0 +1,78 @@
class_name RollLive
extends RefCounted
## Live values for cards on the board: variable cards' starting values, the
## value a variable card shows right now, and a sheet card's text filled in
## with current values. Roller's and RollTable's matching functions hand
## their work to here.
## A variable card that says "starts at …" gives its variable that value
## the first time a roll needs it: before a top-level roll, each declared
## variable that isn't set yet and has a starting value is set to it (and
## saved like any other change). Variables with no starting value stay unset,
## and collections are left alone.
static func apply_starting_values(board: TowerBoard, ctx: RollContext) -> void:
if board == null:
return
for table in board.tables:
if table.kind != RollTable.KIND_VARIABLE or table.is_collection() or table.var_name == "":
continue
if table.initial.strip_edges() == "" or ctx.get_value("@" + table.var_name) != null:
continue
var start := table.initial_value(ctx)
if str(start.get("error", "")) == "":
ctx.save("@" + table.var_name, start["value"], table.id)
## A context for showing values live (variable and sheet cards, previews):
## nothing is rolled or saved through it by the caller's intent, but dice in
## expressions still roll. `persistent` is the collection's variables.
static func live_context(board: TowerBoard, persistent: Dictionary) -> RollContext:
return Roller.new_context(board, RandomNumberGenerator.new(), persistent, {})
## Live display of a variable card: its current value as text, or its
## starting value (marked) when it isn't set yet. A collection shows its set
## members ("Gun Combat 1, Pilot 0"; set is false when there are none).
## Returns {"text": String, "set": bool, "error": String}.
static func variable_display(board: TowerBoard, persistent: Dictionary, table: RollTable) -> Dictionary:
var ctx := live_context(board, persistent)
if table.is_collection():
var listed := ctx.list_text(table.var_name + "_")
return {"text": listed, "set": listed != "", "error": ""}
var value: Variant = ctx.get_value("@" + table.var_name)
if value != null:
return {"text": Expr.format_value(value), "set": true, "error": ""}
var start := table.initial_value(ctx)
return {"text": Expr.format_value(start["value"]), "set": false, "error": str(start["error"])}
## 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.
static func initial_value(table: RollTable, ctx: RollContext) -> Dictionary:
var src := table.initial.strip_edges()
if src == "":
return {"value": 0 if table.var_type == "number" else "", "error": ""}
if table.var_type != "number" and looks_literal(src):
return {"value": src, "error": ""}
var result := Expr.evaluate(src, ctx)
if result["error"] != "":
return {"value": 0 if table.var_type == "number" else "", "error": result["error"]}
return result
## True for plain words that aren't an expression ("Aslan"): no quotes, no
## "@", no brackets, no operators, and not a number.
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()
## Live rendering of a sheet card's template with current values (BBCode with
## internal markers; [[references]] read as table names, nothing is rolled).
static func render_sheet(board: TowerBoard, persistent: Dictionary, table: RollTable) -> String:
if table.entries.is_empty():
return ""
return TextExpander.render(table.entries[0].text, live_context(board, persistent))

1
core/roll_live.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://bud06wjypp8dn

61
core/roll_nodes.gd Normal file
View file

@ -0,0 +1,61 @@
class_name RollNodes
extends RefCounted
## Small helpers that build the Roller's result nodes: a stop node, hanging a
## node under its parent, counting actions against the limit, and adding
## effect-log lines and why-trace facts. Roller._stop, _attach, _take_action,
## _log and _why hand their work to the functions here.
## A node that says why the chain couldn't continue (`why` is its summary).
static func stop(table: RollTable, why: String, extra: Dictionary = {}) -> Dictionary:
var node := {"table": table, "stop": why, "summary": why, "children": []}
node.merge(extra, true)
return node
## Hangs `node` under the frame's parent, with the frame's save name and card
## inputs. A top-level node also becomes ctx.root.
static func attach(frame: Dictionary, node: Dictionary, ctx: RollContext) -> void:
if str(frame.get("save", "")) != "":
node["save_as"] = frame["save"]
if frame.has("inputs"):
node["inputs"] = frame["inputs"]
var facts: Array = frame["pre_why"]
if node.has("why"):
facts.append_array(node["why"])
node["why"] = facts
add_log(node, frame["pre_log"])
(frame["parent"]["children"] as Array).append(node)
if frame.get("top", false):
ctx.root = node
## Counts one action, or stops the roll at the limit (attaching the marker
## under `frame.parent`). Returns false when the roll has to stop.
static func take_action(frame: Dictionary, table: RollTable, ctx: RollContext) -> bool:
if ctx.actions >= ctx.max_actions:
var message := Roller.limit_text(ctx.max_actions)
attach(frame, stop(table, message, {"limit": true}), ctx)
ctx.halted = message
return false
ctx.actions += 1
return true
## Appends why-trace facts to a node's "why".
static func add_why(node: Dictionary, facts: Array) -> void:
if facts.is_empty():
return
if not node.has("why"):
node["why"] = facts
else:
(node["why"] as Array).append_array(facts)
## Appends effect-log lines to a node's "effects".
static func add_log(node: Dictionary, lines: Array) -> void:
if lines.is_empty():
return
if not node.has("effects"):
node["effects"] = []
(node["effects"] as Array).append_array(lines)

1
core/roll_nodes.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://c4ew0gu64j7vn

View file

@ -1,8 +1,8 @@
class_name RollPipes
extends RefCounted
## Pipe snapshots and card inputs for the Roller: what an entry's pipes do
## (pipe_plan()), the values they pass, and binding a card's inputs for the
## subtree it runs.
## (pipe_plan()), the values they pass, binding a card's inputs for the
## subtree it runs, and the pipe and pause frames on the Roller's work stack.
## The snapshot of an entry's pipes, taken once after the entry's effects ran
@ -123,3 +123,75 @@ static func restore(f: Dictionary, ctx: RollContext) -> void:
ctx.chain_vars[nm] = pair[1]
else:
ctx.chain_vars.erase(nm)
# ---------- Pipe frames on the Roller's work stack ----------
## Snapshots a result's threads (pipe_plan) and queues the ones that run,
## last first so they run in order.
static func queue_pipes(node: Dictionary, ctx: RollContext, stack: Array, depth: int) -> void:
var entry: TableEntry = node["entry"]
var log: Array = []
var why: Array = []
var plan := pipe_plan(entry, ctx, log, why)
Roller._log(node, log)
Roller._why(node, why)
for k in range(plan.size() - 1, -1, -1):
var item: Dictionary = plan[k]
if not item["run"]:
continue
var target: String = item["to"]
var frame := {"op": Roller.OP_PIPE, "node": node, "entry": entry, "to": target, "left": int(item["count"]),
"save": entry.save_for(target), "depth": depth}
if item.has("with"):
frame["with"] = item["with"]
if entry.dice_for(target) != "":
frame["dice"] = entry.dice_for(target)
if not entry.reroll_for(target).is_empty():
frame["reroll"] = entry.reroll_for(target)
var mode := entry.combine_for(target)
if mode != "all" and int(item["count"]) > 1:
# Runs after every repeat: combines them (RollCombine).
stack.append({"op": Roller.OP_COMBINE, "node": node, "to": target, "mode": mode, "save": frame["save"],
"start": (node["children"] as Array).size(), "depth": depth})
frame["no_follow"] = true
frame["save"] = ""
stack.append(frame)
if entry.pipe_pause.has(target):
# Runs first: waits for the player before the thread above it.
stack.append({"op": Roller.OP_PAUSE, "node": node, "to": target, "depth": depth})
## A paused thread: asks the player (kind "pause") whether to go on. Stopping
## drops the thread waiting under this frame and marks the result.
static func do_pause(board: TowerBoard, frame: Dictionary, ctx: RollContext, stack: Array) -> void:
var table := board.get_table(str(frame["to"]))
var node: Dictionary = frame["node"]
var request := {"kind": "pause", "table_id": str(frame["to"]), "title": table.name if table else str(frame["to"]),
"prompt": "Continue to %s?" % Formatter.strip_tags(table.name if table else str(frame["to"])),
"from": Formatter.strip_tags((node["table"] as RollTable).name)}
var reply: Variant = await RollChoice.ask(ctx, request)
if reply == true:
return
if not stack.is_empty() and int((stack.back() as Dictionary)["op"]) == Roller.OP_PIPE:
stack.pop_back()
node["stopped_before"] = str(frame["to"])
## One run of a pipe: pushes itself back (while runs are left) and then a
## roll frame for the target table, so the target rolls first.
static func do_pipe(board: TowerBoard, frame: Dictionary, stack: Array) -> void:
if int(frame["left"]) <= 0:
return
var table := board.get_table(str(frame["to"]))
if table == null or table.kind == RollTable.KIND_VARIABLE:
return
frame["left"] = int(frame["left"]) - 1
stack.append(frame)
var roll_frame := {"op": Roller.OP_ROLL, "id": frame["to"], "parent": frame["node"], "save": frame["save"], "depth": frame["depth"]}
for key in ["with", "dice", "reroll"]:
if frame.has(key):
roll_frame[key] = frame[key]
if frame.get("no_follow", false):
roll_frame["no_follow"] = true
stack.append(roll_frame)

View file

@ -142,58 +142,8 @@ func _init(p_id: String = "", p_name: String = "") -> void:
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
## 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.
@ -242,28 +192,8 @@ func find_input(input_name: String) -> Dictionary:
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
## 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).
@ -277,38 +207,10 @@ 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
## 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
@ -354,18 +256,15 @@ func has_mod() -> bool:
## The whole roll as text: "1d20 + @luck", or the dice alone.
func roll_text() -> String:
return RollRange.join(dice, dice_mod)
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)
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)
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
@ -379,13 +278,11 @@ func dice_label() -> String:
## Lowest value that can be shown or rolled (RollRange.min_value).
func min_value() -> int:
return RollRange.min_value(self)
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 die_size() -> int: return RollRange.max_value(self)
func total_weight() -> int:
@ -395,12 +292,10 @@ func total_weight() -> int:
return w
func fmt(value: int) -> String:
return RollRange.fmt(self, value)
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)
func num_label(e: TableEntry, index: int) -> String: return RollRange.num_label(self, e, index)
## False when chances can't be known (expression dice).
@ -409,13 +304,11 @@ func has_chances() -> bool:
## 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)
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)
func can_come_up(e: TableEntry) -> bool: return RollRange.can_come_up(self, e)
## The entry whose range holds `value` exactly, or -1.
@ -429,8 +322,7 @@ func entry_index_for(value: int) -> int:
## 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 entry_index_clamped(value: int) -> int: return RollRange.index_for(self, value)
func find_entry(eid: String) -> TableEntry:
@ -440,48 +332,26 @@ func find_entry(eid: String) -> TableEntry:
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
## Gaps, overlaps and out-of-reach ranges, or "" when clean (RollRange.problems).
func range_problems() -> String: return RollRange.problems(self)
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()
## 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)
func to_dict() -> Dictionary: return RollTableIO.to_dict(self)
static func from_dict(d: Dictionary) -> RollTable:
return RollTableIO.from_dict(d)
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)
## 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)

View file

@ -0,0 +1,72 @@
class_name RollTableFactory
extends RefCounted
## Makes new, ready-to-use cards of every kind (RollTable.create hands its
## work to here). Each kind starts with sensible entries and settings, so a
## fresh card already rolls or asks something.
## 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", "scale").
## 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(kind: String, id: String, card_name: String, sub: String = "") -> RollTable:
var table := RollTable.new(id, card_name)
table.kind = kind if RollTable.KINDS.has(kind) else RollTable.KIND_ROLL
match table.kind:
RollTable.KIND_ROLL:
for n in range(1, 5):
table.entries.append(TableEntry.new("e%d" % n, "Result %d" % n))
RollTable.KIND_CHOICE:
_fill_choice(table, sub)
RollTable.KIND_LOOP:
table.loop_mode = sub if RollTable.LOOPS.has(sub) else "times"
table.loop_expr = "3" if table.loop_mode == "times" else "i < 3"
table.entries.append(TableEntry.new("e1", "Each time"))
table.entries.append(TableEntry.new("e2", "Afterwards"))
RollTable.KIND_VARIABLE:
_fill_variable(table, card_name, sub)
RollTable.KIND_SHEET:
table.entries.append(TableEntry.new("e1", "[b]%s[/b]" % card_name))
RollTable.KIND_ROUTER:
var first := TableEntry.new("e1", "if …")
first.when = RollTable.ROUTER_DEFAULT_WHEN
table.entries.append(first)
table.entries.append(TableEntry.new("e2", "Otherwise"))
RollTable.KIND_CHECK:
table.entries.append(TableEntry.new("e1", "Success"))
table.entries.append(TableEntry.new("e2", "Failure"))
return table
## A choice card: its question and its starting options or answer.
static func _fill_choice(table: RollTable, sub: String) -> void:
table.choice = sub if RollTable.CHOICES.has(sub) else "pick"
match table.choice:
"pick":
table.prompt = "Which one?"
for n in range(1, 4):
table.entries.append(TableEntry.new("e%d" % n, "Option %d" % n))
"number":
table.prompt = "How many?"
table.entries.append(TableEntry.new("e1", "Answer"))
"text":
table.prompt = "What is it?"
table.entries.append(TableEntry.new("e1", "Answer"))
## A variable card: its type, its name (from the card name) and its start.
static func _fill_variable(table: RollTable, card_name: String, sub: String) -> void:
table.var_type = sub if RollTable.VAR_TYPES.has(sub) else "number"
table.var_name = JsonIO.slug(Formatter.strip_tags(card_name), "var") if card_name != "" else "var"
var stem := table.var_name
if table.var_type == RollTable.VAR_COLLECTION and stem.length() > 3 and stem.ends_with("s") and not stem.ends_with("ss"):
table.var_name = stem.substr(0, stem.length() - 1)
table.initial = "0" if table.var_type == "number" else ""
if table.var_type == RollTable.VAR_SCALE:
table.steps.assign(["Low", "Medium", "High"])
table.initial = "Low"

View file

@ -0,0 +1 @@
uid://beg2f63ux4nmx

View file

@ -177,3 +177,36 @@ static func clean_columns(v: Variant) -> Array:
o["when"] = when.strip_edges()
out.append(o)
return out
## 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(value: Variant) -> Array:
var out: Array = []
if not (value is Array):
return out
for item: Variant in value:
var input_name := ""
var label := ""
var default_text := ""
if item is Dictionary:
input_name = str(item.get("name", "")) if item.get("name") != null else ""
label = str(item.get("label", "")) if item.get("label") != null else ""
default_text = expr_text(item.get("default", ""), "")
elif item is String:
input_name = item
input_name = input_name.strip_edges().trim_prefix("@")
if input_name == "":
continue
out.append({"name": input_name, "label": label.strip_edges(), "default": default_text.strip_edges()})
return out
## Expression fields may arrive as JSON numbers: 3.0 -> "3".
static func expr_text(value: Variant, fallback: String) -> String:
if value == null:
return fallback
if value is float or value is int:
return Expr.format_value(value)
return str(value)

View file

@ -34,9 +34,11 @@ extends RefCounted
## never recurse in GDScript, so chains of thousands of steps are fine. Only
## inline [[references]] nest (at most RollContext.max_depth deep).
##
## The parts: RollPipes (pipe snapshots, card inputs), RollCards (plain picks,
## routers, checks, loops), RollChoice (choice cards), RollTree (reading the
## result tree, lit keys) and RollLint (static board checks).
## The parts: RollPipes (pipe snapshots, card inputs, pipe and pause frames),
## RollCards (plain picks, routers, checks, loops), RollChoice (choice cards),
## RollNodes (building result nodes), RollLive (live values for variable and
## sheet cards), RollTree (reading the result tree, lit keys) and RollLint
## (static board checks).
##
## roll_async() is the main entry point. It awaits ctx.prompt for choice cards
## and fills in ctx.root as it goes. roll() is the plain form: it never waits
@ -136,22 +138,8 @@ static func roll_async(board: TowerBoard, table_id: String, ctx: RollContext, de
return await _chain(board, table_id, depth, ctx)
## A variable card that says "starts at …" gives its variable that value
## the first time a roll needs it: before a top-level roll, each declared
## variable that isn't set yet and has a starting value is set to it (and
## saved like any other change). Variables with no starting value stay unset,
## and collections are left alone.
static func apply_starting_values(board: TowerBoard, ctx: RollContext) -> void:
if board == null:
return
for t in board.tables:
if t.kind != RollTable.KIND_VARIABLE or t.is_collection() or t.var_name == "":
continue
if t.initial.strip_edges() == "" or ctx.get_value("@" + t.var_name) != null:
continue
var r := t.initial_value(ctx)
if str(r.get("error", "")) == "":
ctx.save("@" + t.var_name, r["value"], t.id)
## Sets declared variables to their starting values (RollLive).
static func apply_starting_values(board: TowerBoard, ctx: RollContext) -> void: RollLive.apply_starting_values(board, ctx)
## The steps of the tree built so far (ctx.root), e.g. while a prompt is open.
@ -191,7 +179,7 @@ static func _chain(board: TowerBoard, table_id: String, depth: int, ctx: RollCon
OP_ROLL:
await _do_roll(board, f, ctx, stack)
OP_PIPE:
_do_pipe(board, f, ctx, stack)
RollPipes.do_pipe(board, f, stack)
OP_LOOP:
await RollCards.do_loop(f, ctx, stack)
OP_RESTORE:
@ -199,9 +187,9 @@ static func _chain(board: TowerBoard, table_id: String, depth: int, ctx: RollCon
OP_COMBINE:
var keep: Dictionary = await RollCombine.run(f, ctx)
if not keep.is_empty():
_queue_pipes(keep, ctx, stack, int(f["depth"]))
RollPipes.queue_pipes(keep, ctx, stack, int(f["depth"]))
OP_PAUSE:
await _do_pause(board, f, ctx, stack)
await RollPipes.do_pause(board, f, ctx, stack)
# A halted roll leaves frames behind: put back any card inputs they hid.
while not stack.is_empty():
var rest: Dictionary = stack.pop_back()
@ -212,37 +200,13 @@ static func _chain(board: TowerBoard, table_id: String, depth: int, ctx: RollCon
return kids[0] if not kids.is_empty() else {}
static func _stop(t: RollTable, why: String, extra: Dictionary = {}) -> Dictionary:
var node := {"table": t, "stop": why, "summary": why, "children": []}
node.merge(extra, true)
return node
static func _attach(f: Dictionary, node: Dictionary, ctx: RollContext) -> void:
if str(f.get("save", "")) != "":
node["save_as"] = f["save"]
if f.has("inputs"):
node["inputs"] = f["inputs"]
var facts: Array = f["pre_why"]
if node.has("why"):
facts.append_array(node["why"])
node["why"] = facts
_log(node, f["pre_log"])
(f["parent"]["children"] as Array).append(node)
if f.get("top", false):
ctx.root = node
## Counts one action, or stops the roll at the limit (attaching the marker
## under `f.parent`). Returns false when the roll has to stop.
static func _take_action(f: Dictionary, t: RollTable, ctx: RollContext) -> bool:
if ctx.actions >= ctx.max_actions:
var msg := limit_text(ctx.max_actions)
_attach(f, _stop(t, msg, {"limit": true}), ctx)
ctx.halted = msg
return false
ctx.actions += 1
return true
# Node helpers (RollNodes); the other roll parts call these too.
static func _stop(t: RollTable, why: String, extra: Dictionary = {}) -> Dictionary: return RollNodes.stop(t, why, extra)
static func _attach(f: Dictionary, node: Dictionary, ctx: RollContext) -> void: RollNodes.attach(f, node, ctx)
## Counts one action, or stops the roll at the limit. False when it has to stop.
static func _take_action(f: Dictionary, t: RollTable, ctx: RollContext) -> bool: return RollNodes.take_action(f, t, ctx)
static func _why(node: Dictionary, facts: Array) -> void: RollNodes.add_why(node, facts)
static func _log(node: Dictionary, lines: Array) -> void: RollNodes.add_log(node, lines)
static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: Array) -> void:
@ -331,127 +295,18 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr
# one that's kept follows its threads.
if f.get("no_follow", false):
return
_queue_pipes(node, ctx, stack, depth)
RollPipes.queue_pipes(node, ctx, stack, depth)
## Snapshots a result's threads (RollPipes.pipe_plan) and queues the ones
## that run, last first so they run in order.
static func _queue_pipes(node: Dictionary, ctx: RollContext, stack: Array, depth: int) -> void:
var e: TableEntry = node["entry"]
var log: Array = []
var why: Array = []
var plan := RollPipes.pipe_plan(e, ctx, log, why)
_log(node, log)
_why(node, why)
for k in range(plan.size() - 1, -1, -1):
var item: Dictionary = plan[k]
if not item["run"]:
continue
var p: String = item["to"]
var fr := {"op": OP_PIPE, "node": node, "entry": e, "to": p, "left": int(item["count"]), "save": e.save_for(p), "depth": depth}
if item.has("with"):
fr["with"] = item["with"]
if e.dice_for(p) != "":
fr["dice"] = e.dice_for(p)
if not e.reroll_for(p).is_empty():
fr["reroll"] = e.reroll_for(p)
var mode := e.combine_for(p)
if mode != "all" and int(item["count"]) > 1:
# Runs after every repeat: combines them (RollCombine).
stack.append({"op": OP_COMBINE, "node": node, "to": p, "mode": mode, "save": fr["save"],
"start": (node["children"] as Array).size(), "depth": depth})
fr["no_follow"] = true
fr["save"] = ""
stack.append(fr)
if e.pipe_pause.has(p):
# Runs first: waits for the player before the thread above it.
stack.append({"op": OP_PAUSE, "node": node, "to": p, "depth": depth})
## A context for showing values live (variable and sheet cards, previews; RollLive).
static func live_context(board: TowerBoard, persistent: Dictionary) -> RollContext: return RollLive.live_context(board, persistent)
## A variable card's live value: {"text", "set", "error"} (RollLive).
static func variable_display(board: TowerBoard, persistent: Dictionary, t: RollTable) -> Dictionary: return RollLive.variable_display(board, persistent, t)
## A sheet card's template rendered with current values (RollLive).
static func render_sheet(board: TowerBoard, persistent: Dictionary, t: RollTable) -> String: return RollLive.render_sheet(board, persistent, t)
## Appends why-trace facts to a node's "why".
static func _why(node: Dictionary, facts: Array) -> void:
if facts.is_empty():
return
if not node.has("why"):
node["why"] = facts
else:
(node["why"] as Array).append_array(facts)
## Appends effect-log lines to a node's "effects".
static func _log(node: Dictionary, lines: Array) -> void:
if lines.is_empty():
return
if not node.has("effects"):
node["effects"] = []
(node["effects"] as Array).append_array(lines)
## A paused thread: asks the player (kind "pause") whether to go on. Stopping
## drops the thread waiting under this frame and marks the result.
static func _do_pause(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: Array) -> void:
var t := board.get_table(str(f["to"]))
var node: Dictionary = f["node"]
var req := {"kind": "pause", "table_id": str(f["to"]), "title": t.name if t else str(f["to"]),
"prompt": "Continue to %s?" % Formatter.strip_tags(t.name if t else str(f["to"])),
"from": Formatter.strip_tags((node["table"] as RollTable).name)}
var reply: Variant = await RollChoice.ask(ctx, req)
if reply == true:
return
if not stack.is_empty() and int((stack.back() as Dictionary)["op"]) == OP_PIPE:
stack.pop_back()
node["stopped_before"] = str(f["to"])
static func _do_pipe(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: Array) -> void:
if int(f["left"]) <= 0:
return
var t := board.get_table(str(f["to"]))
if t == null or t.kind == RollTable.KIND_VARIABLE:
return
f["left"] = int(f["left"]) - 1
stack.append(f)
var fr := {"op": OP_ROLL, "id": f["to"], "parent": f["node"], "save": f["save"], "depth": f["depth"]}
for key in ["with", "dice", "reroll"]:
if f.has(key):
fr[key] = f[key]
if f.get("no_follow", false):
fr["no_follow"] = true
stack.append(fr)
## A context for showing values live (variable and sheet cards, previews):
## nothing is rolled or saved through it by the caller's intent, but dice in
## expressions still roll. `persistent` is the collection's variables.
static func live_context(board: TowerBoard, persistent: Dictionary) -> RollContext:
return new_context(board, RandomNumberGenerator.new(), persistent, {})
## Live display of a variable card: its current value as text, or its
## starting value (marked) when it isn't set yet. A collection shows its set
## members ("Gun Combat 1, Pilot 0"; set is false when there are none).
## Returns {"text": String, "set": bool, "error": String}.
static func variable_display(board: TowerBoard, persistent: Dictionary, t: RollTable) -> Dictionary:
var ctx := live_context(board, persistent)
if t.is_collection():
var listed := ctx.list_text(t.var_name + "_")
return {"text": listed, "set": listed != "", "error": ""}
var v: Variant = ctx.get_value("@" + t.var_name)
if v != null:
return {"text": Expr.format_value(v), "set": true, "error": ""}
var r := t.initial_value(ctx)
return {"text": Expr.format_value(r["value"]), "set": false, "error": str(r["error"])}
## Live rendering of a sheet card's template with current values (BBCode with
## internal markers; [[references]] read as table names, nothing is rolled).
static func render_sheet(board: TowerBoard, persistent: Dictionary, t: RollTable) -> String:
if t.entries.is_empty():
return ""
return TextExpander.render(t.entries[0].text, live_context(board, persistent))
# ---------- Delegators (the parts live in RollPipes, RollCards, RollChoice, RollTree, RollLint) ----------
# ---------- Delegators (the parts live in RollChoice, RollTree, RollLint) ----------
## The default text of a dynamic card's Chosen entry (RollChoice.CHOSEN).
const CHOSEN := RollChoice.CHOSEN

View file

@ -164,204 +164,36 @@ func page_uses(pid: String) -> int:
return n
# ----- Nested groups -----
func child_groups(gid: String) -> Array[TableGroup]:
var out: Array[TableGroup] = []
for g in groups:
if g.parent == gid and gid != "":
out.append(g)
return out
# ----- Nested groups (the work happens in BoardGroups) -----
func child_groups(gid: String) -> Array[TableGroup]: return BoardGroups.child_groups(self, gid)
## Every table inside a group, its inner groups' tables included.
func tables_in(gid: String) -> Array[String]:
var out: Array[String] = []
var g := get_group(gid)
if g == null:
return out
out.append_array(g.members)
for c in child_groups(gid):
out.append_array(tables_in(c.id))
return out
func tables_in(gid: String) -> Array[String]: return BoardGroups.tables_in(self, gid)
## The group and every group inside it, outermost first.
func groups_in(gid: String) -> Array[TableGroup]:
var out: Array[TableGroup] = []
var g := get_group(gid)
if g == null:
return out
out.append(g)
for c in child_groups(gid):
out.append_array(groups_in(c.id))
return out
## The outermost collapsed group around `g` (not `g` itself), or null when
## nothing around it is collapsed.
func hidden_by(g: TableGroup) -> TableGroup:
var out: TableGroup = null
var p := get_group(g.parent)
while p != null:
if p.collapsed:
out = p
p = get_group(p.parent)
return out
func groups_in(gid: String) -> Array[TableGroup]: return BoardGroups.groups_in(self, gid)
## The outermost collapsed group around `g` (not `g` itself), or null.
func hidden_by(g: TableGroup) -> TableGroup: return BoardGroups.hidden_by(self, g)
## How many groups `g` sits inside.
func depth_of(g: TableGroup) -> int:
var n := 0
var p := get_group(g.parent)
while p != null and n < groups.size():
n += 1
p = get_group(p.parent)
return n
## Puts group `gid` inside `parent_id` ("" = the spread). False when that would
## put a group inside itself.
func set_group_parent(gid: String, parent_id: String) -> bool:
var g := get_group(gid)
if g == null:
return false
var p := get_group(parent_id)
while p != null:
if p.id == gid:
return false
p = get_group(p.parent)
g.parent = parent_id
return true
func depth_of(g: TableGroup) -> int: return BoardGroups.depth_of(self, g)
## Puts group `gid` inside `parent_id` ("" = the spread). False if it would loop.
func set_group_parent(gid: String, parent_id: String) -> bool: return BoardGroups.set_group_parent(self, gid, parent_id)
## Makes a group of the given tables (taking them out of any other group).
func add_group(gname: String, member_ids: Array, gid: String = "") -> TableGroup:
var g := TableGroup.new(gid if gid != "" else new_id("g"), gname)
groups.append(g)
for tid: Variant in member_ids:
add_to_group(str(tid), g.id)
return g
func add_group(gname: String, member_ids: Array, gid: String = "") -> TableGroup: return BoardGroups.add_group(self, gname, member_ids, gid)
## Puts a table in a group, taking it out of its old one. False if either is missing.
func add_to_group(table_id: String, gid: String) -> bool:
var g := get_group(gid)
if g == null or get_table(table_id) == null:
return false
var old := group_of(table_id)
if old == g:
return true
if old:
old.members.erase(table_id)
g.members.append(table_id)
return true
func remove_from_group(table_id: String) -> void:
var g := group_of(table_id)
if g:
g.members.erase(table_id)
## Removes the group only; its cards and inner groups move up to the group
## around it (or onto the spread).
func ungroup(gid: String) -> void:
var g := get_group(gid)
if g == null:
return
var outer := get_group(g.parent)
for c in child_groups(gid):
c.parent = g.parent
if outer:
for tid in g.members:
if not outer.members.has(tid):
outer.members.append(tid)
for i in range(groups.size() - 1, -1, -1):
if groups[i].id == gid:
groups.remove_at(i)
## Removes the group, its inner groups and every table in them. Returns the
## removed table ids.
func delete_group(gid: String) -> Array[String]:
var gone: Array[String] = []
if get_group(gid) == null:
return gone
gone.assign(tables_in(gid))
for inner in groups_in(gid):
groups.erase(inner)
for tid in gone:
remove_table(tid)
return gone
func add_to_group(table_id: String, gid: String) -> bool: return BoardGroups.add_to_group(self, table_id, gid)
func remove_from_group(table_id: String) -> void: BoardGroups.remove_from_group(self, table_id)
## Removes the group only; its cards and inner groups move up a level.
func ungroup(gid: String) -> void: BoardGroups.ungroup(self, gid)
## Removes the group, its inner groups and every table in them. Returns the table ids.
func delete_group(gid: String) -> Array[String]: return BoardGroups.delete_group(self, gid)
## Moves a group's frame, its inner groups and every table in them by `delta`.
func move_group(gid: String, delta: Vector2) -> void:
for g in groups_in(gid):
g.position += delta
for tid in g.members:
var t := get_table(tid)
if t:
t.position += delta
func move_group(gid: String, delta: Vector2) -> void: BoardGroups.move_group(self, gid, delta)
## Drops bad members, keeps each table in one group, and makes group ids unique.
func clean_groups() -> void: BoardGroups.clean_groups(self)
## Drops members that aren't tables, keeps each table in its first group only,
## and gives groups unique ids. Empty groups are kept (they can be refilled).
func clean_groups() -> void:
var ids := {}
for t in tables:
ids[t.id] = true
var taken := {}
var gids := {}
for g in groups:
if g.id == "" or gids.has(g.id):
g.id = new_id("g")
gids[g.id] = true
var keep: Array[String] = []
for m in g.members:
if ids.has(m) and not taken.has(m):
taken[m] = true
keep.append(m)
g.members = keep
# Parents must exist and never loop back.
for g in groups:
if g.parent != "" and (not gids.has(g.parent) or g.parent == g.id):
g.parent = ""
for g in groups:
var seen := {g.id: true}
var p := get_group(g.parent)
while p != null:
if seen.has(p.id):
g.parent = ""
break
seen[p.id] = true
p = get_group(p.parent)
## Upgrades a parsed file to FORMAT_VERSION, one version step at a time.
## To add a version, bump FORMAT_VERSION and add a _migrate_N_to_N1 step here.
static func migrate(d: Dictionary) -> Dictionary:
var v: int = int(d.get("format_version", 1))
while v < FORMAT_VERSION:
match v:
1:
d = _migrate_1_to_2(d)
_:
break
v += 1
d["format_version"] = v
return d
## Version 1 had no id or name; they are filled in by whoever imports the file.
static func _migrate_1_to_2(d: Dictionary) -> Dictionary:
d["format_version"] = 2
if not d.has("id"):
d["id"] = ""
if not d.has("name"):
d["name"] = ""
return d
## Upgrades a parsed file to FORMAT_VERSION (BoardFileIO.migrate).
static func migrate(d: Dictionary) -> Dictionary: return BoardFileIO.migrate(d)
func to_dict() -> Dictionary:
@ -424,32 +256,8 @@ func load_dict(src: Dictionary) -> bool:
return true
## Writes text to path via a temp file and a rename, so a crash can't leave a
## half-written file. Creates the folder if needed.
static func write_text_atomic(path: String, text: String) -> Error:
var dir := path.get_base_dir()
if not DirAccess.dir_exists_absolute(dir):
var mk := DirAccess.make_dir_recursive_absolute(dir)
if mk != OK:
return mk
var tmp := path + ".tmp"
var f := FileAccess.open(tmp, FileAccess.WRITE)
if f == null:
return FileAccess.get_open_error()
f.store_string(text)
var werr := f.get_error()
f.close()
if werr != OK:
DirAccess.remove_absolute(tmp)
return werr
var err := DirAccess.rename_absolute(tmp, path)
if err != OK and FileAccess.file_exists(path):
# Some platforms won't rename over an existing file.
DirAccess.remove_absolute(path)
err = DirAccess.rename_absolute(tmp, path)
if err != OK:
DirAccess.remove_absolute(tmp)
return err
## Writes text to path via a temp file and a rename (BoardFileIO).
static func write_text_atomic(path: String, text: String) -> Error: return BoardFileIO.write_text_atomic(path, text)
func save(path: String = SAVE_PATH) -> bool: