Compare commits
39 commits
5592c3d134
...
f6b1f644f0
| Author | SHA1 | Date | |
|---|---|---|---|
| f6b1f644f0 | |||
| 168a326002 | |||
| 2ed91e7acd | |||
| a2f0d3a016 | |||
| 77d262e969 | |||
| de942d57ee | |||
| a4688c1a4b | |||
| 0ec50cc1fc | |||
| bd077ebadc | |||
| 05508e1c05 | |||
| bc2936cf15 | |||
| 323e033d88 | |||
| a7fb931bb4 | |||
| 983d2bd839 | |||
| 3f13bc181c | |||
| 6a460d17eb | |||
| 22d3613364 | |||
| 8592c9c059 | |||
| 1162f9150d | |||
| 4db69cee86 | |||
| b96fc02c0b | |||
| 83800c2f0e | |||
| c341790d1a | |||
| ac85122541 | |||
| 9d550408d8 | |||
| 3aeb98c2fd | |||
| 9a0d97e924 | |||
| edb49fce27 | |||
| d9638500ba | |||
| ff76e56daf | |||
| b604553364 | |||
| f47f659ff4 | |||
| ad264cd2f0 | |||
| 0ed2ba553b | |||
| dba3f6514e | |||
| 63929a9fc2 | |||
| 4f8b3c7934 | |||
| 6027173ca3 | |||
| c03657c2a1 |
204 changed files with 5816 additions and 3250 deletions
131
core/board_checks.gd
Normal file
131
core/board_checks.gd
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
class_name BoardChecks
|
||||
extends RefCounted
|
||||
## Checks a board without rolling anything: bad expressions and effects,
|
||||
## range gaps, threads to missing tables, choice cards with no options and
|
||||
## endless cycles. Also picks the tables worth starting a test from.
|
||||
## BoardTester delegates here.
|
||||
|
||||
|
||||
## Problems found without rolling anything. Array of {kind, table_id,
|
||||
## entry_id ("" for the card), table (display name), text}, in board order.
|
||||
## kinds: expression, effect, range, cycle, missing_pipe, empty_choice, pipes,
|
||||
## check (check cards: bad dice, modifier or target, missing results) and
|
||||
## inputs (card inputs and pipe "with" values; see Roller.lint_inputs()).
|
||||
## Items from Roller.lint_pipes() also carry its "level" when it has one
|
||||
## ("error" or "hint").
|
||||
static func static_checks(board: TowerBoard) -> Array[Dictionary]:
|
||||
var out: Array[Dictionary] = []
|
||||
var add := func(kind: String, table: RollTable, entry_id: String, text: String) -> void:
|
||||
out.append({"kind": kind, "table_id": table.id, "entry_id": entry_id, "table": Formatter.strip_tags(table.name), "text": text})
|
||||
for table in board.tables:
|
||||
_check_table(board, table, add)
|
||||
for id in Roller.endless_cycles(board):
|
||||
var table := board.get_table(id)
|
||||
add.call("cycle", table, "", "Can never finish: every result leads back into an endless cycle.")
|
||||
_add_lint(board, out, add)
|
||||
return out
|
||||
|
||||
|
||||
## The checks for one card and its results; `add` records each problem.
|
||||
static func _check_table(board: TowerBoard, table: RollTable, add: Callable) -> void:
|
||||
var expr := func(what: String, src: String, entry_id: String = "") -> void:
|
||||
if src.strip_edges() == "":
|
||||
return
|
||||
var err := Expr.check(src)
|
||||
if err != "":
|
||||
add.call("expression", table, entry_id, "%s \"%s\": %s" % [what, src, err])
|
||||
if table.is_expr_dice():
|
||||
expr.call("Dice", table.dice)
|
||||
if table.is_ranged():
|
||||
expr.call("Modifier", table.dice_mod)
|
||||
if table.is_ranged():
|
||||
var range_problem := table.range_problems()
|
||||
if range_problem != "":
|
||||
add.call("range", table, "", range_problem)
|
||||
match table.kind:
|
||||
RollTable.KIND_LOOP:
|
||||
expr.call("Repeat rule", table.loop_expr)
|
||||
RollTable.KIND_CHOICE:
|
||||
if table.choice == "pick" and table.entries.is_empty():
|
||||
add.call("empty_choice", table, "", "Choice card has no options.")
|
||||
if table.choice == "number":
|
||||
expr.call("Minimum", table.min_expr)
|
||||
expr.call("Maximum", table.max_expr)
|
||||
_check_braces(table.prompt, func(src: String) -> void: expr.call("Prompt", src))
|
||||
RollTable.KIND_VARIABLE:
|
||||
var init := table.initial.strip_edges()
|
||||
if table.var_type == "number" and init != "" and not init.is_valid_float():
|
||||
expr.call("Initial value", init)
|
||||
for entry in table.entries:
|
||||
_check_braces(entry.text, func(src: String) -> void: expr.call("Text", src, entry.id))
|
||||
for problem in Effects.validate(entry.effects):
|
||||
add.call("effect", table, entry.id, "Change \"%s\": %s" % [problem["src"], problem["error"]])
|
||||
for target in entry.pipes:
|
||||
if board.get_table(target) == null:
|
||||
add.call("missing_pipe", table, entry.id, "Thread to a table that doesn't exist (%s)." % target)
|
||||
var count_expr := entry.count_expr(target)
|
||||
if count_expr != "":
|
||||
expr.call("Thread count", count_expr, entry.id)
|
||||
|
||||
|
||||
## Adds the items from Roller.lint_pipes(), when the Roller has it.
|
||||
static func _add_lint(board: TowerBoard, out: Array[Dictionary], add: Callable) -> void:
|
||||
var roller: GDScript = Roller
|
||||
var has_lint := false
|
||||
for method in roller.get_script_method_list():
|
||||
if method["name"] == "lint_pipes":
|
||||
has_lint = true
|
||||
if not has_lint:
|
||||
return
|
||||
var lint: Variant = roller.call("lint_pipes", board)
|
||||
if not (lint is Array):
|
||||
return
|
||||
for item: Variant in lint:
|
||||
var table: RollTable = null
|
||||
var entry_id := ""
|
||||
var text := str(item)
|
||||
var lint_kind := "pipes"
|
||||
var level := ""
|
||||
if item is Dictionary:
|
||||
var details: Dictionary = item
|
||||
table = board.get_table(str(details.get("table_id", details.get("table", ""))))
|
||||
entry_id = str(details.get("entry_id", details.get("entry", "")))
|
||||
text = str(details.get("text", details.get("message", details.get("problem", text))))
|
||||
lint_kind = str(details.get("kind", "pipes"))
|
||||
level = str(details.get("level", ""))
|
||||
if table == null:
|
||||
table = RollTable.new("", "")
|
||||
add.call(lint_kind, table, entry_id, text)
|
||||
if level != "":
|
||||
out.back()["level"] = level
|
||||
|
||||
|
||||
## Calls `on_expr(src)` for each `{= expr}` in the text.
|
||||
static func _check_braces(text: String, on_expr: Callable) -> void:
|
||||
var brace_re := RegEx.create_from_string("\\{=([^}]*)\\}")
|
||||
for found in brace_re.search_all(text):
|
||||
on_expr.call(found.get_string(1))
|
||||
|
||||
|
||||
## Tables worth starting a test from: not variable cards, with nothing piping
|
||||
## into them and nothing referencing them by [[name]]. If `last_rolled` is a
|
||||
## table it comes first (even if it isn't a root). Ids in board order.
|
||||
static func start_candidates(board: TowerBoard, last_rolled: String = "") -> Array[String]:
|
||||
var used := {}
|
||||
for table in board.tables:
|
||||
for entry in table.entries:
|
||||
for pipe in entry.pipes:
|
||||
used[pipe] = true
|
||||
for ref in Roller.ref_targets(board, entry.text):
|
||||
used[ref] = true
|
||||
for ref in Roller.ref_targets(board, table.prompt):
|
||||
used[ref] = true
|
||||
var out: Array[String] = []
|
||||
for table in board.tables:
|
||||
if table.kind != RollTable.KIND_VARIABLE and not used.has(table.id):
|
||||
out.append(table.id)
|
||||
var last_table := board.get_table(last_rolled)
|
||||
if last_table != null and last_table.kind != RollTable.KIND_VARIABLE:
|
||||
out.erase(last_table.id)
|
||||
out.push_front(last_table.id)
|
||||
return out
|
||||
1
core/board_checks.gd.uid
Normal file
1
core/board_checks.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://burrp8dm7hha0
|
||||
57
core/board_file_io.gd
Normal file
57
core/board_file_io.gd
Normal 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
|
||||
1
core/board_file_io.gd.uid
Normal file
1
core/board_file_io.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bx1lxbnni7hsu
|
||||
180
core/board_groups.gd
Normal file
180
core/board_groups.gd
Normal 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
1
core/board_groups.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://81xq5r5axa01
|
||||
96
core/board_report_text.gd
Normal file
96
core/board_report_text.gd
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
class_name BoardReportText
|
||||
extends RefCounted
|
||||
## Turns a board test's results into plain text lines: the static problems
|
||||
## and the simulation report (runs, halts, errors, dead ends, tables never
|
||||
## reached ...). Used by the Test board window and tools/simulate_board.gd.
|
||||
## BoardTester delegates here.
|
||||
|
||||
|
||||
## True when no run hit an error, a dead end or the action limit.
|
||||
static func is_clean(report: Dictionary) -> bool:
|
||||
return (report["errors"] as Array).is_empty() and (report["dead_ends"] as Array).is_empty() \
|
||||
and not (report["halted"] as Dictionary).has("Action limit")
|
||||
|
||||
|
||||
## The static problems as text lines (for the CLI's --check and Copy report).
|
||||
static func format_problems(problems: Array, list: int = 40) -> PackedStringArray:
|
||||
var out := PackedStringArray()
|
||||
out.append("Static problems: %d" % problems.size())
|
||||
for i in mini(list, problems.size()):
|
||||
var problem: Dictionary = problems[i]
|
||||
var where: String = "%s (%s)" % [problem["table"], problem["table_id"]]
|
||||
if str(problem["entry_id"]) != "":
|
||||
where += ", result " + str(problem["entry_id"])
|
||||
out.append(" %s: %s" % [where, problem["text"]])
|
||||
if problems.size() > list:
|
||||
out.append(" ... and %d more" % (problems.size() - list))
|
||||
return out
|
||||
|
||||
|
||||
## The simulation report as text; `list` caps each section's lines.
|
||||
static func format_report(report: Dictionary, list: int = 40, show_sheet: bool = true) -> String:
|
||||
var out := PackedStringArray()
|
||||
var actions: Dictionary = report["actions"]
|
||||
out.append("Runs: %d completed: %d prompts per run: %.1f" % [report["runs"], report["completed"], report["prompts_mean"]])
|
||||
var halt_parts := PackedStringArray()
|
||||
for reason: String in report["halted"]:
|
||||
halt_parts.append("%s %d" % [reason, report["halted"][reason]])
|
||||
out.append("Halted: %s" % (", ".join(halt_parts) if not halt_parts.is_empty() else "none"))
|
||||
out.append("Actions: max %d, mean %.1f, p95 %d" % [actions["max"], actions["mean"], actions["p95"]])
|
||||
var longest: Dictionary = report.get("longest", {})
|
||||
if not (longest.get("top", []) as Array).is_empty():
|
||||
var parts := PackedStringArray()
|
||||
for hit: Dictionary in longest["top"]:
|
||||
parts.append("%s %d" % [hit["table"], hit["count"]])
|
||||
out.append("Longest run (#%d) most-rolled tables: %s" % [longest["run"], ", ".join(parts)])
|
||||
var track: Dictionary = report.get("track", {})
|
||||
for name: String in track:
|
||||
var stats: Dictionary = track[name]
|
||||
if int(stats["n"]) == 0:
|
||||
out.append("@%s: never a number" % name)
|
||||
else:
|
||||
out.append("@%s: min %s, mean %.1f, max %s (%d runs)" % [name, Expr.format_value(stats["min"]), stats["sum"] / stats["n"], Expr.format_value(stats["max"]), stats["n"]])
|
||||
_section(out, "Change / expression errors", report["errors"], list, func(item: Dictionary) -> String:
|
||||
return "%dx %s, result \"%s\": %s" % [item["count"], item["table"], item["entry"], item["text"]])
|
||||
_section(out, "Dead ends (rolls that stopped)", report["dead_ends"], list, func(item: Dictionary) -> String:
|
||||
return "%dx %s: %s" % [item["count"], item["table"], item["text"]])
|
||||
_section(out, "Unset variables, missing tables and {= } errors in text", report["unset_markers"], list, func(item: Dictionary) -> String:
|
||||
return "%dx %s, result \"%s\": %s" % [item["count"], item["table"], item["entry"], item["text"]])
|
||||
var unreached: Array = report["unreached"]
|
||||
out.append("Tables never reached: %d" % unreached.size())
|
||||
for i in mini(list, unreached.size()):
|
||||
out.append(" " + str(unreached[i]))
|
||||
if unreached.size() > list:
|
||||
out.append(" ... and %d more" % (unreached.size() - list))
|
||||
_unchosen_lines(out, report["unchosen"], list)
|
||||
if show_sheet:
|
||||
out.append("Sample final sheet%s:" % (" (" + str(report["sample_halted"]) + ")" if str(report["sample_halted"]) != "" else ""))
|
||||
out.append(str(report["sample_sheet"]) if str(report["sample_sheet"]) != "" else " (no sheet card was reached)")
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
## The "Results never chosen" lines: {table id: [entry texts]}.
|
||||
static func _unchosen_lines(out: PackedStringArray, unchosen: Dictionary, list: int) -> void:
|
||||
var entry_count := 0
|
||||
for table_id: String in unchosen:
|
||||
entry_count += (unchosen[table_id] as Array).size()
|
||||
out.append("Results never chosen: %d in %d reached cards" % [entry_count, unchosen.size()])
|
||||
var shown := 0
|
||||
for table_id: String in unchosen:
|
||||
if shown >= list:
|
||||
out.append(" ... and %d more tables" % (unchosen.size() - shown))
|
||||
break
|
||||
var items: Array = unchosen[table_id]
|
||||
var names := PackedStringArray()
|
||||
for i in mini(4, items.size()):
|
||||
names.append("\"%s\"" % items[i])
|
||||
out.append(" %s: %d (%s%s)" % [table_id, items.size(), ", ".join(names), ", ..." if items.size() > 4 else ""])
|
||||
shown += 1
|
||||
|
||||
|
||||
static func _section(out: PackedStringArray, title: String, items: Array, list: int, fmt: Callable) -> void:
|
||||
out.append("%s: %d" % [title, items.size()])
|
||||
for i in mini(list, items.size()):
|
||||
out.append(" " + str(fmt.call(items[i])))
|
||||
if items.size() > list:
|
||||
out.append(" ... and %d more" % (items.size() - list))
|
||||
1
core/board_report_text.gd.uid
Normal file
1
core/board_report_text.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dnt3w5wbp4rb4
|
||||
|
|
@ -248,119 +248,17 @@ func report() -> Dictionary:
|
|||
}
|
||||
|
||||
|
||||
# ---------- Static checks ----------
|
||||
# ---------- Static checks (BoardChecks) ----------
|
||||
|
||||
## Problems found without rolling anything. Array of {kind, table_id,
|
||||
## entry_id ("" for the card), table (display name), text}, in board order.
|
||||
## kinds: expression, effect, range, cycle, missing_pipe, empty_choice, pipes,
|
||||
## check (check cards: bad dice, modifier or target, missing results) and
|
||||
## inputs (card inputs and pipe "with" values; see Roller.lint_inputs()).
|
||||
## Items from Roller.lint_pipes() also carry its "level" when it has one
|
||||
## ("error" or "hint").
|
||||
static func static_checks(b: TowerBoard) -> Array[Dictionary]:
|
||||
var out: Array[Dictionary] = []
|
||||
var add := func(kind: String, t: RollTable, eid: String, text: String) -> void:
|
||||
out.append({"kind": kind, "table_id": t.id, "entry_id": eid, "table": Formatter.strip_tags(t.name), "text": text})
|
||||
for t in b.tables:
|
||||
var expr := func(what: String, src: String, eid: String = "") -> void:
|
||||
if src.strip_edges() == "":
|
||||
return
|
||||
var err := Expr.check(src)
|
||||
if err != "":
|
||||
add.call("expression", t, eid, "%s \"%s\": %s" % [what, src, err])
|
||||
if t.is_expr_dice():
|
||||
expr.call("Dice", t.dice)
|
||||
if t.is_ranged():
|
||||
expr.call("Modifier", t.dice_mod)
|
||||
if t.is_ranged():
|
||||
var rp := t.range_problems()
|
||||
if rp != "":
|
||||
add.call("range", t, "", rp)
|
||||
match t.kind:
|
||||
RollTable.KIND_LOOP:
|
||||
expr.call("Repeat rule", t.loop_expr)
|
||||
RollTable.KIND_CHOICE:
|
||||
if t.choice == "pick" and t.entries.is_empty():
|
||||
add.call("empty_choice", t, "", "Choice card has no options.")
|
||||
if t.choice == "number":
|
||||
expr.call("Minimum", t.min_expr)
|
||||
expr.call("Maximum", t.max_expr)
|
||||
_check_braces(t.prompt, func(src: String) -> void: expr.call("Prompt", src))
|
||||
RollTable.KIND_VARIABLE:
|
||||
var init := t.initial.strip_edges()
|
||||
if t.var_type == "number" and init != "" and not init.is_valid_float():
|
||||
expr.call("Initial value", init)
|
||||
for e in t.entries:
|
||||
_check_braces(e.text, func(src: String) -> void: expr.call("Text", src, e.id))
|
||||
for p in Effects.validate(e.effects):
|
||||
add.call("effect", t, e.id, "Change \"%s\": %s" % [p["src"], p["error"]])
|
||||
for target in e.pipes:
|
||||
if b.get_table(target) == null:
|
||||
add.call("missing_pipe", t, e.id, "Thread to a table that doesn't exist (%s)." % target)
|
||||
var ce := e.count_expr(target)
|
||||
if ce != "":
|
||||
expr.call("Thread count", ce, e.id)
|
||||
for id in Roller.endless_cycles(b):
|
||||
var t := b.get_table(id)
|
||||
add.call("cycle", t, "", "Can never finish: every result leads back into an endless cycle.")
|
||||
var roller: GDScript = Roller
|
||||
var has_lint := false
|
||||
for m in roller.get_script_method_list():
|
||||
if m["name"] == "lint_pipes":
|
||||
has_lint = true
|
||||
if has_lint:
|
||||
var lint: Variant = roller.call("lint_pipes", b)
|
||||
if lint is Array:
|
||||
for item: Variant in lint:
|
||||
var t: RollTable = null
|
||||
var eid := ""
|
||||
var text := str(item)
|
||||
var lkind := "pipes"
|
||||
var level := ""
|
||||
if item is Dictionary:
|
||||
var d: Dictionary = item
|
||||
t = b.get_table(str(d.get("table_id", d.get("table", ""))))
|
||||
eid = str(d.get("entry_id", d.get("entry", "")))
|
||||
text = str(d.get("text", d.get("message", d.get("problem", text))))
|
||||
lkind = str(d.get("kind", "pipes"))
|
||||
level = str(d.get("level", ""))
|
||||
if t == null:
|
||||
t = RollTable.new("", "")
|
||||
add.call(lkind, t, eid, text)
|
||||
if level != "":
|
||||
out.back()["level"] = level
|
||||
return out
|
||||
## Problems found without rolling anything (BoardChecks.static_checks lists
|
||||
## the item keys and kinds).
|
||||
static func static_checks(board_to_check: TowerBoard) -> Array[Dictionary]:
|
||||
return BoardChecks.static_checks(board_to_check)
|
||||
|
||||
|
||||
## Calls `f(src)` for each `{= expr}` in the text.
|
||||
static func _check_braces(text: String, f: Callable) -> void:
|
||||
var re := RegEx.create_from_string("\\{=([^}]*)\\}")
|
||||
for m in re.search_all(text):
|
||||
f.call(m.get_string(1))
|
||||
|
||||
|
||||
## Tables worth starting a test from: not variable cards, with nothing piping
|
||||
## into them and nothing referencing them by [[name]]. If `last_rolled` is a
|
||||
## table it comes first (even if it isn't a root). Ids in board order.
|
||||
static func start_candidates(b: TowerBoard, last_rolled: String = "") -> Array[String]:
|
||||
var used := {}
|
||||
for t in b.tables:
|
||||
for e in t.entries:
|
||||
for p in e.pipes:
|
||||
used[p] = true
|
||||
for r in Roller.ref_targets(b, e.text):
|
||||
used[r] = true
|
||||
for r in Roller.ref_targets(b, t.prompt):
|
||||
used[r] = true
|
||||
var out: Array[String] = []
|
||||
for t in b.tables:
|
||||
if t.kind != RollTable.KIND_VARIABLE and not used.has(t.id):
|
||||
out.append(t.id)
|
||||
var lr := b.get_table(last_rolled)
|
||||
if lr != null and lr.kind != RollTable.KIND_VARIABLE:
|
||||
out.erase(lr.id)
|
||||
out.push_front(lr.id)
|
||||
return out
|
||||
## Tables worth starting a test from (BoardChecks.start_candidates).
|
||||
static func start_candidates(board_to_check: TowerBoard, last_rolled: String = "") -> Array[String]:
|
||||
return BoardChecks.start_candidates(board_to_check, last_rolled)
|
||||
|
||||
|
||||
# ---------- Answers and report text ----------
|
||||
|
|
@ -392,87 +290,17 @@ static func answer(req: Dictionary, rng: RandomNumberGenerator, prefer: RegEx =
|
|||
|
||||
## True when no run hit an error, a dead end or the action limit.
|
||||
static func is_clean(r: Dictionary) -> bool:
|
||||
return (r["errors"] as Array).is_empty() and (r["dead_ends"] as Array).is_empty() \
|
||||
and not (r["halted"] as Dictionary).has("Action limit")
|
||||
return BoardReportText.is_clean(r)
|
||||
|
||||
|
||||
## The static problems as text lines (for the CLI's --check and Copy report).
|
||||
## The static problems as text lines (BoardReportText.format_problems).
|
||||
static func format_problems(problems: Array, list: int = 40) -> PackedStringArray:
|
||||
var out := PackedStringArray()
|
||||
out.append("Static problems: %d" % problems.size())
|
||||
for k in mini(list, problems.size()):
|
||||
var p: Dictionary = problems[k]
|
||||
var where: String = "%s (%s)" % [p["table"], p["table_id"]]
|
||||
if str(p["entry_id"]) != "":
|
||||
where += ", result " + str(p["entry_id"])
|
||||
out.append(" %s: %s" % [where, p["text"]])
|
||||
if problems.size() > list:
|
||||
out.append(" ... and %d more" % (problems.size() - list))
|
||||
return out
|
||||
return BoardReportText.format_problems(problems, list)
|
||||
|
||||
|
||||
## The report as text (BoardReportText.format_report).
|
||||
static func format_report(r: Dictionary, list: int = 40, show_sheet: bool = true) -> String:
|
||||
var out := PackedStringArray()
|
||||
var a: Dictionary = r["actions"]
|
||||
out.append("Runs: %d completed: %d prompts per run: %.1f" % [r["runs"], r["completed"], r["prompts_mean"]])
|
||||
var hl := PackedStringArray()
|
||||
for k: String in r["halted"]:
|
||||
hl.append("%s %d" % [k, r["halted"][k]])
|
||||
out.append("Halted: %s" % (", ".join(hl) if not hl.is_empty() else "none"))
|
||||
out.append("Actions: max %d, mean %.1f, p95 %d" % [a["max"], a["mean"], a["p95"]])
|
||||
var lg: Dictionary = r.get("longest", {})
|
||||
if not (lg.get("top", []) as Array).is_empty():
|
||||
var parts := PackedStringArray()
|
||||
for x: Dictionary in lg["top"]:
|
||||
parts.append("%s %d" % [x["table"], x["count"]])
|
||||
out.append("Longest run (#%d) most-rolled tables: %s" % [lg["run"], ", ".join(parts)])
|
||||
var tr: Dictionary = r.get("track", {})
|
||||
for name: String in tr:
|
||||
var t: Dictionary = tr[name]
|
||||
if int(t["n"]) == 0:
|
||||
out.append("@%s: never a number" % name)
|
||||
else:
|
||||
out.append("@%s: min %s, mean %.1f, max %s (%d runs)" % [name, Expr.format_value(t["min"]), t["sum"] / t["n"], Expr.format_value(t["max"]), t["n"]])
|
||||
_section(out, "Change / expression errors", r["errors"], list, func(e: Dictionary) -> String:
|
||||
return "%dx %s, result \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]])
|
||||
_section(out, "Dead ends (rolls that stopped)", r["dead_ends"], list, func(e: Dictionary) -> String:
|
||||
return "%dx %s: %s" % [e["count"], e["table"], e["text"]])
|
||||
_section(out, "Unset variables, missing tables and {= } errors in text", r["unset_markers"], list, func(e: Dictionary) -> String:
|
||||
return "%dx %s, result \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]])
|
||||
var un: Array = r["unreached"]
|
||||
out.append("Tables never reached: %d" % un.size())
|
||||
for k in mini(list, un.size()):
|
||||
out.append(" " + str(un[k]))
|
||||
if un.size() > list:
|
||||
out.append(" ... and %d more" % (un.size() - list))
|
||||
var uc: Dictionary = r["unchosen"]
|
||||
var n_entries := 0
|
||||
for k: String in uc:
|
||||
n_entries += (uc[k] as Array).size()
|
||||
out.append("Results never chosen: %d in %d reached cards" % [n_entries, uc.size()])
|
||||
var shown := 0
|
||||
for k: String in uc:
|
||||
if shown >= list:
|
||||
out.append(" ... and %d more tables" % (uc.size() - shown))
|
||||
break
|
||||
var items: Array = uc[k]
|
||||
var names := PackedStringArray()
|
||||
for x in mini(4, items.size()):
|
||||
names.append("\"%s\"" % items[x])
|
||||
out.append(" %s: %d (%s%s)" % [k, items.size(), ", ".join(names), ", ..." if items.size() > 4 else ""])
|
||||
shown += 1
|
||||
if show_sheet:
|
||||
out.append("Sample final sheet%s:" % (" (" + str(r["sample_halted"]) + ")" if str(r["sample_halted"]) != "" else ""))
|
||||
out.append(str(r["sample_sheet"]) if str(r["sample_sheet"]) != "" else " (no sheet card was reached)")
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
static func _section(out: PackedStringArray, title: String, items: Array, list: int, fmt: Callable) -> void:
|
||||
out.append("%s: %d" % [title, items.size()])
|
||||
for k in mini(list, items.size()):
|
||||
out.append(" " + str(fmt.call(items[k])))
|
||||
if items.size() > list:
|
||||
out.append(" ... and %d more" % (items.size() - list))
|
||||
return BoardReportText.format_report(r, list, show_sheet)
|
||||
|
||||
|
||||
static func _sorted_by_count(list: Array) -> Array:
|
||||
|
|
|
|||
279
core/builder.gd
279
core/builder.gd
|
|
@ -36,9 +36,6 @@ const _CMP_OF := {"=": "eq", "==": "eq", "!=": "ne", ">=": "ge", "<=": "le", ">"
|
|||
## Chain values the engine sets, with what sets them.
|
||||
const CHAIN_NAMES := ["answer", "option", "i", "total", "nat", "effect"]
|
||||
|
||||
static var _dice_re: RegEx = null
|
||||
static var _num_re: RegEx = null
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- effects
|
||||
|
||||
|
|
@ -225,279 +222,39 @@ static func _value(g: Array, k: int) -> String:
|
|||
|
||||
# ---------------------------------------------------------------- tokens
|
||||
|
||||
## Splits a rule into tokens: Array of {"t": type, "s": text}, or [] when it
|
||||
## can't (an unclosed quote or bracket, a stray character, "2x"). Types:
|
||||
## "var" (@name, lowercased, or @[expr] as written), "prefix" (@name_*),
|
||||
## "name" (a chain name or function), "num", "dice" (2d6, D3, 2D), "str" (a
|
||||
## quoted text, quotes included), "op" (+ - * / % ( ) , = == != < <= > >=),
|
||||
## "kw" (and, or, not; && || ! are read as these).
|
||||
## Splits a rule into tokens (RuleTokens.tokenize): Array of {"t": type,
|
||||
## "s": text}, or [] when it can't.
|
||||
static func tokens(src: String) -> Array:
|
||||
var out: Array = []
|
||||
var i := 0
|
||||
var n := src.length()
|
||||
while i < n:
|
||||
var c := src[i]
|
||||
if c == " " or c == "\t" or c == "\n":
|
||||
i += 1
|
||||
continue
|
||||
if c == "\"" or c == "'":
|
||||
var j := i + 1
|
||||
while j < n and src[j] != c:
|
||||
if src[j] == "\\":
|
||||
j += 1
|
||||
j += 1
|
||||
if j >= n:
|
||||
return []
|
||||
out.append({"t": "str", "s": src.substr(i, j - i + 1)})
|
||||
i = j + 1
|
||||
continue
|
||||
if c == "@":
|
||||
if i + 1 < n and src[i + 1] == "[":
|
||||
var close := Expr.bracket_end(src, i + 1)
|
||||
if close < 0:
|
||||
return []
|
||||
out.append({"t": "var", "s": "@[%s]" % src.substr(i + 2, close - i - 2).strip_edges()})
|
||||
i = close + 1
|
||||
continue
|
||||
var j2 := i + 1
|
||||
while j2 < n and _is_word(src[j2]):
|
||||
j2 += 1
|
||||
var nm := src.substr(i + 1, j2 - i - 1).to_lower()
|
||||
if nm == "" or nm[0].is_valid_int():
|
||||
return []
|
||||
if j2 < n and src[j2] == "*":
|
||||
out.append({"t": "prefix", "s": "@%s*" % nm})
|
||||
i = j2 + 1
|
||||
else:
|
||||
out.append({"t": "var", "s": "@" + nm})
|
||||
i = j2
|
||||
continue
|
||||
if _is_word(c):
|
||||
var j3 := i
|
||||
while j3 < n and (_is_word(src[j3]) or (src[j3] == "." and j3 + 1 < n and src[j3 + 1].is_valid_int())):
|
||||
j3 += 1
|
||||
var w := src.substr(i, j3 - i)
|
||||
i = j3
|
||||
if _num().search(w) != null:
|
||||
out.append({"t": "num", "s": w})
|
||||
elif _dice().search(w) != null and w.length() > 1:
|
||||
out.append({"t": "dice", "s": w})
|
||||
elif w[0].is_valid_int():
|
||||
return []
|
||||
elif ["and", "or", "not"].has(w.to_lower()) and w == w.to_lower():
|
||||
out.append({"t": "kw", "s": w})
|
||||
else:
|
||||
out.append({"t": "name", "s": w})
|
||||
continue
|
||||
var two := src.substr(i, 2)
|
||||
if two in [">=", "<=", "!=", "=="]:
|
||||
out.append({"t": "op", "s": two})
|
||||
i += 2
|
||||
continue
|
||||
if two == "&&" or two == "||":
|
||||
out.append({"t": "kw", "s": "and" if two == "&&" else "or"})
|
||||
i += 2
|
||||
continue
|
||||
if c == "!":
|
||||
out.append({"t": "kw", "s": "not"})
|
||||
i += 1
|
||||
continue
|
||||
if c in ["+", "-", "*", "/", "%", "(", ")", ",", "=", "<", ">"]:
|
||||
out.append({"t": "op", "s": c})
|
||||
i += 1
|
||||
continue
|
||||
return []
|
||||
return out
|
||||
return RuleTokens.tokenize(src)
|
||||
|
||||
|
||||
static func _is_word(c: String) -> bool:
|
||||
return c == "_" or c.is_valid_int() or (c.to_lower() != c.to_upper())
|
||||
static func _is_word(ch: String) -> bool:
|
||||
return RuleTokens.is_word(ch)
|
||||
|
||||
|
||||
static func _dice() -> RegEx:
|
||||
if _dice_re == null:
|
||||
_dice_re = RegEx.create_from_string("^(\\d*)[dD](\\d*)$")
|
||||
return _dice_re
|
||||
|
||||
|
||||
static func _num() -> RegEx:
|
||||
if _num_re == null:
|
||||
_num_re = RegEx.create_from_string("^\\d+(\\.\\d+)?$")
|
||||
return _num_re
|
||||
|
||||
|
||||
## [count, sides] of a dice token ("2d6" -> [2, 6], "D3" -> [1, 3], "2D" ->
|
||||
## [2, 6]), or [].
|
||||
## [count, sides] of a dice token (RuleTokens.dice_parts), or [].
|
||||
static func dice_parts(word: String) -> Array:
|
||||
var m := _dice().search(word)
|
||||
if m == null or word.length() < 2:
|
||||
return []
|
||||
var a := m.get_string(1)
|
||||
var b := m.get_string(2)
|
||||
return [int(a) if a != "" else 1, int(b) if b != "" else 6]
|
||||
return RuleTokens.dice_parts(word)
|
||||
|
||||
|
||||
## True when `s` is one quoted text literal ("Aslan" or 'Aslan').
|
||||
static func is_text_literal(s: String) -> bool:
|
||||
var t := tokens(s.strip_edges())
|
||||
return t.size() == 1 and t[0]["t"] == "str"
|
||||
## True when `text` is one quoted text literal ("Aslan" or 'Aslan').
|
||||
static func is_text_literal(text: String) -> bool:
|
||||
return RuleTokens.is_text_literal(text)
|
||||
|
||||
|
||||
## A quoted literal's text: "\"Aslan\"" -> "Aslan" (\" and \\ unescaped).
|
||||
## Anything else comes back as it is.
|
||||
static func unquote(s: String) -> String:
|
||||
s = s.strip_edges()
|
||||
if s.length() < 2 or not ((s.begins_with("\"") and s.ends_with("\"")) or (s.begins_with("'") and s.ends_with("'"))):
|
||||
return s
|
||||
var inner := s.substr(1, s.length() - 2)
|
||||
var out := ""
|
||||
var k := 0
|
||||
while k < inner.length():
|
||||
var ch := inner[k]
|
||||
if ch == "\\" and k + 1 < inner.length():
|
||||
k += 1
|
||||
ch = inner[k]
|
||||
out += ch
|
||||
k += 1
|
||||
return out
|
||||
## A quoted literal's text (RuleTokens.unquote).
|
||||
static func unquote(text: String) -> String:
|
||||
return RuleTokens.unquote(text)
|
||||
|
||||
|
||||
## Text as a double-quoted literal, escaping \ and ".
|
||||
static func quote(s: String) -> String:
|
||||
return "\"%s\"" % s.replace("\\", "\\\\").replace("\"", "\\\"")
|
||||
static func quote(text: String) -> String:
|
||||
return RuleTokens.quote(text)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- values
|
||||
|
||||
## Every value the board uses, for value pickers: Array of {"name", "label",
|
||||
## "kind", "source"} with optional extras, variable cards first, then
|
||||
## collections, then the rest in board order, then chain names. One item per
|
||||
## name (the first source wins).
|
||||
## name "@luck" (board value), "@skill_*" (a collection), "tier" (chain)
|
||||
## label Describe.label(name, board)
|
||||
## kind "number", "text", "list", "collection" or "scale"
|
||||
## source "variable" (a variable card), "collection", "effect" (an effect
|
||||
## target), "save_as" (a pipe's or choice's save_as, or
|
||||
## [[Table -> name]]), "input" (a card input), "read" (only read by
|
||||
## a rule), "chain" (answer, option, i, total, nat, effect)
|
||||
## table_id the card that declares, sets or reads it first
|
||||
## collection on members of a collection: its pattern ("@skill_*")
|
||||
## Chain names are listed only when the board has a card that sets them
|
||||
## (answer: number/text choices; option: options from variables; i: loops;
|
||||
## nat: roll tables and checks; total/effect: checks).
|
||||
## Every value the board uses, for value pickers (BuilderValues.known_values
|
||||
## lists the item keys).
|
||||
static func known_values(board: TowerBoard) -> Array[Dictionary]:
|
||||
var out: Array[Dictionary] = []
|
||||
if board == null:
|
||||
return out
|
||||
var seen := {}
|
||||
var stems: Array = [] # [stem, pattern]
|
||||
var add := func(name: String, kind: String, source: String, tid: String) -> void:
|
||||
if name == "" or seen.has(name):
|
||||
return
|
||||
seen[name] = true
|
||||
var item := {"name": name, "label": Describe.label(name, board), "kind": kind, "source": source, "table_id": tid}
|
||||
if name.begins_with("@") and not name.ends_with("*"):
|
||||
for sp: Array in stems:
|
||||
if name.begins_with("@" + str(sp[0]) + "_") and name.length() > str(sp[0]).length() + 2:
|
||||
item["collection"] = sp[1]
|
||||
break
|
||||
out.append(item)
|
||||
for t in board.tables:
|
||||
if t.kind == RollTable.KIND_VARIABLE and t.var_name != "" and not t.is_collection():
|
||||
add.call("@" + t.var_name, t.var_type, "variable", t.id)
|
||||
for t in board.tables:
|
||||
if t.is_collection() and t.var_name != "":
|
||||
stems.append([t.var_name, "@%s_*" % t.var_name])
|
||||
stems.sort_custom(func(a: Array, b: Array) -> bool: return str(a[0]).length() > str(b[0]).length())
|
||||
for t in board.tables:
|
||||
if t.is_collection() and t.var_name != "":
|
||||
add.call("@%s_*" % t.var_name, "collection", "collection", t.id)
|
||||
var reads: Array = []
|
||||
var chain := {}
|
||||
for t in board.tables:
|
||||
for col: Dictionary in t.columns:
|
||||
if str(col.get("save_as", "")) != "":
|
||||
add.call(_value_name(str(col["save_as"])), "text", "save_as", t.id)
|
||||
reads.append([str(col.get("when", "")), t.id])
|
||||
match t.kind:
|
||||
RollTable.KIND_CHOICE:
|
||||
if t.choice != "pick":
|
||||
chain["answer"] = true
|
||||
if t.save_as != "":
|
||||
add.call(_value_name(t.save_as), "number" if t.choice == "number" else "text", "save_as", t.id)
|
||||
else:
|
||||
if t.is_dynamic():
|
||||
chain["option"] = true
|
||||
if t.save_as != "":
|
||||
add.call(_value_name(t.save_as), "text", "save_as", t.id)
|
||||
reads.append([t.options_where, t.id])
|
||||
reads.append([t.min_expr, t.id])
|
||||
reads.append([t.max_expr, t.id])
|
||||
RollTable.KIND_LOOP:
|
||||
chain["i"] = true
|
||||
reads.append([t.loop_expr, t.id])
|
||||
RollTable.KIND_CHECK:
|
||||
chain["nat"] = true
|
||||
chain["total"] = true
|
||||
chain["effect"] = true
|
||||
reads.append([t.check_dice, t.id])
|
||||
reads.append([t.check_mod, t.id])
|
||||
reads.append([t.check_target, t.id])
|
||||
RollTable.KIND_ROLL:
|
||||
chain["nat"] = true
|
||||
if t.is_expr_dice():
|
||||
reads.append([t.dice, t.id])
|
||||
if t.has_mod():
|
||||
reads.append([t.dice_mod, t.id])
|
||||
for inp: Dictionary in t.inputs:
|
||||
add.call(str(inp.get("name", "")), _kind_of_expr(str(inp.get("default", ""))), "input", t.id)
|
||||
for e in t.entries:
|
||||
for m in parse_effects(e.effects):
|
||||
if not m["ok"]:
|
||||
continue
|
||||
var v := str(m["var"])
|
||||
if v.begins_with("@[") or v.ends_with("*"):
|
||||
continue
|
||||
var k := "number"
|
||||
match str(m["op"]):
|
||||
"append", "remove":
|
||||
k = "list"
|
||||
"set":
|
||||
k = "text" if is_text_literal(str(m["amount"])) else "number"
|
||||
add.call(v, k, "effect", t.id)
|
||||
if m["op"] != "reset":
|
||||
reads.append([str(m["amount"]), t.id])
|
||||
for p in e.pipes:
|
||||
var sv := e.save_for(p)
|
||||
if sv != "":
|
||||
add.call(_value_name(sv), "text", "save_as", t.id)
|
||||
reads.append([e.when_for(p), t.id])
|
||||
reads.append([e.count_expr(p), t.id])
|
||||
var w := e.with_for(p)
|
||||
for nm: String in w:
|
||||
reads.append([str(w[nm]), t.id])
|
||||
for ref in JsonIO.find_refs(e.text):
|
||||
if str(ref["var"]) != "":
|
||||
add.call(_value_name(str(ref["var"])), "text", "save_as", t.id)
|
||||
reads.append([e.when, t.id])
|
||||
reads.append([e.show_if, t.id])
|
||||
for r: Array in reads:
|
||||
var src := str(r[0]).strip_edges()
|
||||
if src == "" or not src.contains("@"):
|
||||
continue
|
||||
for tk: Dictionary in tokens(src):
|
||||
if tk["t"] == "var" and not str(tk["s"]).begins_with("@["):
|
||||
add.call(str(tk["s"]), "number", "read", str(r[1]))
|
||||
for nm: String in CHAIN_NAMES:
|
||||
if chain.has(nm):
|
||||
add.call(nm, "text" if nm == "option" else "number", "chain", "")
|
||||
return out
|
||||
|
||||
|
||||
static func _value_name(s: String) -> String:
|
||||
var t := s.strip_edges()
|
||||
return "@" + t.substr(1).to_lower() if t.begins_with("@") else t
|
||||
|
||||
|
||||
static func _kind_of_expr(src: String) -> String:
|
||||
return "text" if is_text_literal(src) else "number"
|
||||
return BuilderValues.known_values(board)
|
||||
|
|
|
|||
153
core/builder_values.gd
Normal file
153
core/builder_values.gd
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
class_name BuilderValues
|
||||
extends RefCounted
|
||||
## Finds every value a board uses (variable cards, collections, effect
|
||||
## targets, saved answers, card inputs, values rules only read, and chain
|
||||
## names), so value pickers can offer them. Builder.known_values() delegates
|
||||
## here.
|
||||
|
||||
|
||||
## Every value the board uses, for value pickers: Array of {"name", "label",
|
||||
## "kind", "source"} with optional extras, variable cards first, then
|
||||
## collections, then the rest in board order, then chain names. One item per
|
||||
## name (the first source wins).
|
||||
## name "@luck" (board value), "@skill_*" (a collection), "tier" (chain)
|
||||
## label Describe.label(name, board)
|
||||
## kind "number", "text", "list", "collection" or "scale"
|
||||
## source "variable" (a variable card), "collection", "effect" (an effect
|
||||
## target), "save_as" (a pipe's or choice's save_as, or
|
||||
## [[Table -> name]]), "input" (a card input), "read" (only read by
|
||||
## a rule), "chain" (answer, option, i, total, nat, effect)
|
||||
## table_id the card that declares, sets or reads it first
|
||||
## collection on members of a collection: its pattern ("@skill_*")
|
||||
## Chain names are listed only when the board has a card that sets them
|
||||
## (answer: number/text choices; option: options from variables; i: loops;
|
||||
## nat: roll tables and checks; total/effect: checks).
|
||||
static func known_values(board: TowerBoard) -> Array[Dictionary]:
|
||||
var out: Array[Dictionary] = []
|
||||
if board == null:
|
||||
return out
|
||||
var seen := {}
|
||||
var stems: Array = [] # [stem, pattern]
|
||||
var add := func(name: String, kind: String, source: String, table_id: String) -> void:
|
||||
if name == "" or seen.has(name):
|
||||
return
|
||||
seen[name] = true
|
||||
var item := {"name": name, "label": Describe.label(name, board), "kind": kind, "source": source, "table_id": table_id}
|
||||
if name.begins_with("@") and not name.ends_with("*"):
|
||||
for stem_pair: Array in stems:
|
||||
if name.begins_with("@" + str(stem_pair[0]) + "_") and name.length() > str(stem_pair[0]).length() + 2:
|
||||
item["collection"] = stem_pair[1]
|
||||
break
|
||||
out.append(item)
|
||||
for table in board.tables:
|
||||
if table.kind == RollTable.KIND_VARIABLE and table.var_name != "" and not table.is_collection():
|
||||
add.call("@" + table.var_name, table.var_type, "variable", table.id)
|
||||
for table in board.tables:
|
||||
if table.is_collection() and table.var_name != "":
|
||||
stems.append([table.var_name, "@%s_*" % table.var_name])
|
||||
stems.sort_custom(func(left: Array, right: Array) -> bool: return str(left[0]).length() > str(right[0]).length())
|
||||
for table in board.tables:
|
||||
if table.is_collection() and table.var_name != "":
|
||||
add.call("@%s_*" % table.var_name, "collection", "collection", table.id)
|
||||
var reads: Array = []
|
||||
var chain := {}
|
||||
for table in board.tables:
|
||||
_add_table_values(table, add, reads, chain)
|
||||
for read: Array in reads:
|
||||
var src := str(read[0]).strip_edges()
|
||||
if src == "" or not src.contains("@"):
|
||||
continue
|
||||
for token: Dictionary in RuleTokens.tokenize(src):
|
||||
if token["t"] == "var" and not str(token["s"]).begins_with("@["):
|
||||
add.call(str(token["s"]), "number", "read", str(read[1]))
|
||||
for name: String in Builder.CHAIN_NAMES:
|
||||
if chain.has(name):
|
||||
add.call(name, "text" if name == "option" else "number", "chain", "")
|
||||
return out
|
||||
|
||||
|
||||
## One card's values: calls `add` for what it sets, appends [rule, table id]
|
||||
## to `reads` for every rule it reads, and marks in `chain` which chain
|
||||
## names it sets.
|
||||
static func _add_table_values(table: RollTable, add: Callable, reads: Array, chain: Dictionary) -> void:
|
||||
for col: Dictionary in table.columns:
|
||||
if str(col.get("save_as", "")) != "":
|
||||
add.call(_value_name(str(col["save_as"])), "text", "save_as", table.id)
|
||||
reads.append([str(col.get("when", "")), table.id])
|
||||
match table.kind:
|
||||
RollTable.KIND_CHOICE:
|
||||
if table.choice != "pick":
|
||||
chain["answer"] = true
|
||||
if table.save_as != "":
|
||||
add.call(_value_name(table.save_as), "number" if table.choice == "number" else "text", "save_as", table.id)
|
||||
else:
|
||||
if table.is_dynamic():
|
||||
chain["option"] = true
|
||||
if table.save_as != "":
|
||||
add.call(_value_name(table.save_as), "text", "save_as", table.id)
|
||||
reads.append([table.options_where, table.id])
|
||||
reads.append([table.min_expr, table.id])
|
||||
reads.append([table.max_expr, table.id])
|
||||
RollTable.KIND_LOOP:
|
||||
chain["i"] = true
|
||||
reads.append([table.loop_expr, table.id])
|
||||
RollTable.KIND_CHECK:
|
||||
chain["nat"] = true
|
||||
chain["total"] = true
|
||||
chain["effect"] = true
|
||||
reads.append([table.check_dice, table.id])
|
||||
reads.append([table.check_mod, table.id])
|
||||
reads.append([table.check_target, table.id])
|
||||
RollTable.KIND_ROLL:
|
||||
chain["nat"] = true
|
||||
if table.is_expr_dice():
|
||||
reads.append([table.dice, table.id])
|
||||
if table.has_mod():
|
||||
reads.append([table.dice_mod, table.id])
|
||||
for inp: Dictionary in table.inputs:
|
||||
add.call(str(inp.get("name", "")), _kind_of_expr(str(inp.get("default", ""))), "input", table.id)
|
||||
for entry in table.entries:
|
||||
_add_entry_values(table, entry, add, reads)
|
||||
|
||||
|
||||
## One result's values: its effect targets, saved pipe answers and
|
||||
## [[Table -> name]] saves, and the rules it reads.
|
||||
static func _add_entry_values(table: RollTable, entry: TableEntry, add: Callable, reads: Array) -> void:
|
||||
for model in Builder.parse_effects(entry.effects):
|
||||
if not model["ok"]:
|
||||
continue
|
||||
var target := str(model["var"])
|
||||
if target.begins_with("@[") or target.ends_with("*"):
|
||||
continue
|
||||
var kind := "number"
|
||||
match str(model["op"]):
|
||||
"append", "remove":
|
||||
kind = "list"
|
||||
"set":
|
||||
kind = "text" if RuleTokens.is_text_literal(str(model["amount"])) else "number"
|
||||
add.call(target, kind, "effect", table.id)
|
||||
if model["op"] != "reset":
|
||||
reads.append([str(model["amount"]), table.id])
|
||||
for pipe in entry.pipes:
|
||||
var save_name := entry.save_for(pipe)
|
||||
if save_name != "":
|
||||
add.call(_value_name(save_name), "text", "save_as", table.id)
|
||||
reads.append([entry.when_for(pipe), table.id])
|
||||
reads.append([entry.count_expr(pipe), table.id])
|
||||
var with_values := entry.with_for(pipe)
|
||||
for name: String in with_values:
|
||||
reads.append([str(with_values[name]), table.id])
|
||||
for ref in JsonIO.find_refs(entry.text):
|
||||
if str(ref["var"]) != "":
|
||||
add.call(_value_name(str(ref["var"])), "text", "save_as", table.id)
|
||||
reads.append([entry.when, table.id])
|
||||
reads.append([entry.show_if, table.id])
|
||||
|
||||
|
||||
static func _value_name(text: String) -> String:
|
||||
var trimmed := text.strip_edges()
|
||||
return "@" + trimmed.substr(1).to_lower() if trimmed.begins_with("@") else trimmed
|
||||
|
||||
|
||||
static func _kind_of_expr(src: String) -> String:
|
||||
return "text" if RuleTokens.is_text_literal(src) else "number"
|
||||
1
core/builder_values.gd.uid
Normal file
1
core/builder_values.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bol1fdcr805ca
|
||||
127
core/describe.gd
127
core/describe.gd
|
|
@ -14,10 +14,6 @@ extends RefCounted
|
|||
## Longest phrase before falling back to the original text (or a cut).
|
||||
const MAX_LEN := 90
|
||||
const MINUS := "−"
|
||||
const _CHAIN_LABELS := {"answer": "Answer", "i": "Pass", "nat": "Natural roll", "total": "Total",
|
||||
"effect": "Effect", "option": "Chosen option", "option_label": "Chosen option",
|
||||
"option_value": "Chosen value"}
|
||||
const _OPS := {"*": "×", "/": "÷", "-": MINUS, "==": "=", "!=": "≠", ">=": "≥", "<=": "≤"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- labels
|
||||
|
|
@ -54,65 +50,13 @@ static func label(name: String, board: TowerBoard) -> String:
|
|||
return _label(name, _labels(board))
|
||||
|
||||
|
||||
## Label table for a board: {"vars": {name: label}, "stems": [[stem, label]]
|
||||
## longest first, "inputs": {name: label}, "scales": {name: steps}}.
|
||||
## Label table for a board (see DescribeLabels.build).
|
||||
static func _labels(board: TowerBoard) -> Dictionary:
|
||||
var vars := {}
|
||||
var scales := {}
|
||||
var stems: Array = []
|
||||
var inputs := {}
|
||||
if board != null:
|
||||
for t in board.tables:
|
||||
if t.kind == RollTable.KIND_VARIABLE and t.var_name != "":
|
||||
var lab := Formatter.strip_tags(t.name).strip_edges()
|
||||
if t.var_type == RollTable.VAR_COLLECTION:
|
||||
stems.append([t.var_name, lab if lab != "" else RollContext.pretty_name(t.var_name)])
|
||||
elif lab != "" and not vars.has(t.var_name):
|
||||
vars[t.var_name] = lab
|
||||
if t.is_scale() and not scales.has(t.var_name):
|
||||
scales[t.var_name] = t.steps
|
||||
for inp: Dictionary in t.inputs:
|
||||
var il := str(inp.get("label", "")).strip_edges()
|
||||
if il != "" and not inputs.has(str(inp.get("name", ""))):
|
||||
inputs[str(inp.get("name", ""))] = il
|
||||
stems.sort_custom(func(a: Array, b: Array) -> bool: return str(a[0]).length() > str(b[0]).length())
|
||||
return {"vars": vars, "stems": stems, "inputs": inputs, "scales": scales}
|
||||
return DescribeLabels.build(board)
|
||||
|
||||
|
||||
static func _label(name: String, L: Dictionary) -> String:
|
||||
var n := name.strip_edges()
|
||||
if n.begins_with("@["):
|
||||
return "Chosen value"
|
||||
if n.begins_with("@"):
|
||||
n = n.substr(1).to_lower()
|
||||
if n.ends_with("*"):
|
||||
var stem := n.trim_suffix("*").trim_suffix("_")
|
||||
for sp: Array in L["stems"]:
|
||||
if sp[0] == stem:
|
||||
return sp[1]
|
||||
return "%s values" % RollContext.pretty_name(stem)
|
||||
if L["vars"].has(n):
|
||||
return L["vars"][n]
|
||||
for sp: Array in L["stems"]:
|
||||
var pre := str(sp[0]) + "_"
|
||||
if n.begins_with(pre) and n.length() > pre.length():
|
||||
return RollContext.pretty_name(n.substr(pre.length()))
|
||||
return RollContext.pretty_name(n)
|
||||
if L["inputs"].has(n):
|
||||
return L["inputs"][n]
|
||||
if _CHAIN_LABELS.has(n):
|
||||
return _CHAIN_LABELS[n]
|
||||
return RollContext.pretty_name(n)
|
||||
|
||||
|
||||
## The collection a value belongs to ({"stem", "label"}) or {}.
|
||||
static func _collection_of(name: String, L: Dictionary) -> Dictionary:
|
||||
var n := name.strip_edges().trim_prefix("@").to_lower()
|
||||
for sp: Array in L["stems"]:
|
||||
var pre := str(sp[0]) + "_"
|
||||
if n.begins_with(pre):
|
||||
return {"stem": sp[0], "label": sp[1]}
|
||||
return {}
|
||||
return DescribeLabels.lookup(name, L)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- effects
|
||||
|
|
@ -307,70 +251,7 @@ static func dice(expr: String, board: TowerBoard) -> String:
|
|||
|
||||
|
||||
static func _expr(expr: String, L: Dictionary) -> String:
|
||||
var src := expr.strip_edges()
|
||||
if src == "":
|
||||
return ""
|
||||
var toks := Builder.tokens(src)
|
||||
if toks.is_empty():
|
||||
return src
|
||||
var pieces: Array = [] # [kind, text]; kinds: val fn op neg ( ) ,
|
||||
var k := 0
|
||||
while k < toks.size():
|
||||
var tk: Dictionary = toks[k]
|
||||
var t := str(tk["t"])
|
||||
var s := str(tk["s"])
|
||||
var prevk := str(pieces.back()[0]) if not pieces.is_empty() else ""
|
||||
# dm(x) with one value inside: "X modifier".
|
||||
if t == "name" and s == "dm" and k + 3 < toks.size() and toks[k + 1]["s"] == "(" and toks[k + 3]["s"] == ")" \
|
||||
and ["var", "name", "num"].has(str(toks[k + 2]["t"])):
|
||||
pieces.append(["val", _value(str(toks[k + 2]["s"]), L) + " modifier"])
|
||||
k += 4
|
||||
continue
|
||||
k += 1
|
||||
match t:
|
||||
"dice":
|
||||
var dp := Builder.dice_parts(s)
|
||||
if int(dp[0]) == 1:
|
||||
pieces.append(["val", "d%d" % int(dp[1])])
|
||||
else:
|
||||
pieces.append(["val", "%dd%d" % [int(dp[0]), int(dp[1])]])
|
||||
"var", "prefix":
|
||||
pieces.append(["val", _label(s, L)])
|
||||
"name":
|
||||
if k < toks.size() and toks[k]["s"] == "(":
|
||||
pieces.append(["fn", s])
|
||||
else:
|
||||
pieces.append(["val", _value(s, L)])
|
||||
"num":
|
||||
pieces.append(["val", s])
|
||||
"str":
|
||||
pieces.append(["val", Builder.unquote(s)])
|
||||
"kw":
|
||||
pieces.append(["op", s])
|
||||
_:
|
||||
if s == "(" or s == ")" or s == ",":
|
||||
pieces.append([s, s])
|
||||
elif s == "-" and (prevk == "" or prevk == "op" or prevk == "(" or prevk == "," or prevk == "neg"):
|
||||
pieces.append(["neg", MINUS])
|
||||
else:
|
||||
pieces.append(["op", _OPS.get(s, s)])
|
||||
var out := ""
|
||||
var prev := ""
|
||||
for pc: Array in pieces:
|
||||
var kind := str(pc[0])
|
||||
var space := false
|
||||
match kind:
|
||||
"op":
|
||||
space = out != ""
|
||||
"val", "fn":
|
||||
space = prev in ["op", ",", "val", ")"]
|
||||
"(", "neg":
|
||||
space = prev in ["op", ","]
|
||||
if space:
|
||||
out += " "
|
||||
out += str(pc[1])
|
||||
prev = kind
|
||||
return _short(out, src)
|
||||
return DescribeDice.words(expr, L)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- helpers
|
||||
|
|
|
|||
|
|
@ -61,6 +61,8 @@ static func pipe(entry: TableEntry, target_id: String, board: TowerBoard) -> Str
|
|||
parts.append("×" + Describe._expr(ce, L))
|
||||
elif entry.count_for(target_id) != 1:
|
||||
parts.append("×%d" % entry.count_for(target_id))
|
||||
if entry.pipe_distinct.has(target_id) and (ce != "" or entry.count_for(target_id) != 1):
|
||||
parts.append("no repeats")
|
||||
if entry.dice_for(target_id) != "":
|
||||
parts.append("with " + entry.dice_for(target_id))
|
||||
var again := entry.reroll_for(target_id)
|
||||
|
|
|
|||
90
core/describe_dice.gd
Normal file
90
core/describe_dice.gd
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
class_name DescribeDice
|
||||
extends RefCounted
|
||||
## Turns a dice or count expression into plain words for Describe:
|
||||
## "2d6 + dm(@str)" -> "2d6 + Strength modifier", "1d6 + tier" -> "d6 + Tier".
|
||||
## It reads the expression as tokens (small pieces such as "2d6", "+", "@str"),
|
||||
## swaps each piece for its words, then joins them with tidy spacing.
|
||||
## Describe.dice() and Describe._expr() delegate here.
|
||||
|
||||
## Maths signs shown as their print forms ("−" is Describe.MINUS).
|
||||
const OPS := {"*": "×", "/": "÷", "-": "−", "==": "=", "!=": "≠", ">=": "≥", "<=": "≤"}
|
||||
|
||||
|
||||
## The expression in words, using a label table from DescribeLabels.build().
|
||||
## Text that can't be read comes back as it is.
|
||||
static func words(expr: String, labels: Dictionary) -> String:
|
||||
var source := expr.strip_edges()
|
||||
if source == "":
|
||||
return ""
|
||||
var tokens := Builder.tokens(source)
|
||||
if tokens.is_empty():
|
||||
return source
|
||||
return Describe._short(_join(_pieces(tokens, labels)), source)
|
||||
|
||||
|
||||
## Each token as a [kind, text] piece; kinds: val fn op neg ( ) ,
|
||||
static func _pieces(tokens: Array, labels: Dictionary) -> Array:
|
||||
var pieces: Array = []
|
||||
var index := 0
|
||||
while index < tokens.size():
|
||||
var token: Dictionary = tokens[index]
|
||||
var token_type := str(token["t"])
|
||||
var token_text := str(token["s"])
|
||||
var prev_kind := str(pieces.back()[0]) if not pieces.is_empty() else ""
|
||||
# dm(x) with one value inside: "X modifier".
|
||||
if token_type == "name" and token_text == "dm" and index + 3 < tokens.size() \
|
||||
and tokens[index + 1]["s"] == "(" and tokens[index + 3]["s"] == ")" \
|
||||
and ["var", "name", "num"].has(str(tokens[index + 2]["t"])):
|
||||
pieces.append(["val", Describe._value(str(tokens[index + 2]["s"]), labels) + " modifier"])
|
||||
index += 4
|
||||
continue
|
||||
index += 1
|
||||
match token_type:
|
||||
"dice":
|
||||
var dice_parts := Builder.dice_parts(token_text)
|
||||
if int(dice_parts[0]) == 1:
|
||||
pieces.append(["val", "d%d" % int(dice_parts[1])])
|
||||
else:
|
||||
pieces.append(["val", "%dd%d" % [int(dice_parts[0]), int(dice_parts[1])]])
|
||||
"var", "prefix":
|
||||
pieces.append(["val", DescribeLabels.lookup(token_text, labels)])
|
||||
"name":
|
||||
if index < tokens.size() and tokens[index]["s"] == "(":
|
||||
pieces.append(["fn", token_text])
|
||||
else:
|
||||
pieces.append(["val", Describe._value(token_text, labels)])
|
||||
"num":
|
||||
pieces.append(["val", token_text])
|
||||
"str":
|
||||
pieces.append(["val", Builder.unquote(token_text)])
|
||||
"kw":
|
||||
pieces.append(["op", token_text])
|
||||
_:
|
||||
if token_text == "(" or token_text == ")" or token_text == ",":
|
||||
pieces.append([token_text, token_text])
|
||||
elif token_text == "-" and prev_kind in ["", "op", "(", ",", "neg"]:
|
||||
pieces.append(["neg", "−"])
|
||||
else:
|
||||
pieces.append(["op", OPS.get(token_text, token_text)])
|
||||
return pieces
|
||||
|
||||
|
||||
## Joins the pieces with a space where a reader expects one.
|
||||
static func _join(pieces: Array) -> String:
|
||||
var out := ""
|
||||
var prev := ""
|
||||
for piece: Array in pieces:
|
||||
var kind := str(piece[0])
|
||||
var space := false
|
||||
match kind:
|
||||
"op":
|
||||
space = out != ""
|
||||
"val", "fn":
|
||||
space = prev in ["op", ",", "val", ")"]
|
||||
"(", "neg":
|
||||
space = prev in ["op", ","]
|
||||
if space:
|
||||
out += " "
|
||||
out += str(piece[1])
|
||||
prev = kind
|
||||
return out
|
||||
1
core/describe_dice.gd.uid
Normal file
1
core/describe_dice.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://coms1uaipk7wn
|
||||
73
core/describe_labels.gd
Normal file
73
core/describe_labels.gd
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
class_name DescribeLabels
|
||||
extends RefCounted
|
||||
## Finds the plain-words name ("label") of a value for Describe. It builds a
|
||||
## lookup table from a board's cards once, then answers "what is @skill_pilot
|
||||
## called?" from it. Describe keeps one-line delegators, so callers use
|
||||
## Describe.label() and Describe._labels() as before.
|
||||
|
||||
## Names for values that come from the roll itself rather than a card.
|
||||
const CHAIN_LABELS := {"answer": "Answer", "i": "Pass", "nat": "Natural roll", "total": "Total",
|
||||
"effect": "Effect", "option": "Chosen option", "option_label": "Chosen option",
|
||||
"option_value": "Chosen value"}
|
||||
|
||||
|
||||
## Label table for a board: {"vars": {name: label}, "stems": [[stem, label]]
|
||||
## longest first, "inputs": {name: label}, "scales": {name: steps}}.
|
||||
static func build(board: TowerBoard) -> Dictionary:
|
||||
var vars := {}
|
||||
var scales := {}
|
||||
var stems: Array = []
|
||||
var inputs := {}
|
||||
if board != null:
|
||||
for table in board.tables:
|
||||
if table.kind == RollTable.KIND_VARIABLE and table.var_name != "":
|
||||
var card_label := Formatter.strip_tags(table.name).strip_edges()
|
||||
if table.var_type == RollTable.VAR_COLLECTION:
|
||||
stems.append([table.var_name, card_label if card_label != "" else RollContext.pretty_name(table.var_name)])
|
||||
elif card_label != "" and not vars.has(table.var_name):
|
||||
vars[table.var_name] = card_label
|
||||
if table.is_scale() and not scales.has(table.var_name):
|
||||
scales[table.var_name] = table.steps
|
||||
for input: Dictionary in table.inputs:
|
||||
var input_label := str(input.get("label", "")).strip_edges()
|
||||
if input_label != "" and not inputs.has(str(input.get("name", ""))):
|
||||
inputs[str(input.get("name", ""))] = input_label
|
||||
stems.sort_custom(func(first: Array, second: Array) -> bool: return str(first[0]).length() > str(second[0]).length())
|
||||
return {"vars": vars, "stems": stems, "inputs": inputs, "scales": scales}
|
||||
|
||||
|
||||
## The label of one value name, looked up in a table from build().
|
||||
static func lookup(name: String, labels: Dictionary) -> String:
|
||||
var value_name := name.strip_edges()
|
||||
if value_name.begins_with("@["):
|
||||
return "Chosen value"
|
||||
if value_name.begins_with("@"):
|
||||
value_name = value_name.substr(1).to_lower()
|
||||
if value_name.ends_with("*"):
|
||||
var stem := value_name.trim_suffix("*").trim_suffix("_")
|
||||
for stem_pair: Array in labels["stems"]:
|
||||
if stem_pair[0] == stem:
|
||||
return stem_pair[1]
|
||||
return "%s values" % RollContext.pretty_name(stem)
|
||||
if labels["vars"].has(value_name):
|
||||
return labels["vars"][value_name]
|
||||
for stem_pair: Array in labels["stems"]:
|
||||
var prefix := str(stem_pair[0]) + "_"
|
||||
if value_name.begins_with(prefix) and value_name.length() > prefix.length():
|
||||
return RollContext.pretty_name(value_name.substr(prefix.length()))
|
||||
return RollContext.pretty_name(value_name)
|
||||
if labels["inputs"].has(value_name):
|
||||
return labels["inputs"][value_name]
|
||||
if CHAIN_LABELS.has(value_name):
|
||||
return CHAIN_LABELS[value_name]
|
||||
return RollContext.pretty_name(value_name)
|
||||
|
||||
|
||||
## The collection a value belongs to ({"stem", "label"}) or {}.
|
||||
static func collection_of(name: String, labels: Dictionary) -> Dictionary:
|
||||
var value_name := name.strip_edges().trim_prefix("@").to_lower()
|
||||
for stem_pair: Array in labels["stems"]:
|
||||
var prefix := str(stem_pair[0]) + "_"
|
||||
if value_name.begins_with(prefix):
|
||||
return {"stem": stem_pair[0], "label": stem_pair[1]}
|
||||
return {}
|
||||
1
core/describe_labels.gd.uid
Normal file
1
core/describe_labels.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://ccf5jv2wu5gto
|
||||
|
|
@ -132,6 +132,12 @@ static func _why_roll(f: Dictionary, L: Dictionary, plain: bool) -> String:
|
|||
var total := Expr.format_value(f.get("total"))
|
||||
match str(f.get("pick", "dice")):
|
||||
"weighted":
|
||||
if f.has("from") and _nonzero(f.get("mod", 0)):
|
||||
var by := " for " + Describe._expr(str(f.get("mod_expr", "")).trim_prefix("-"), L) if str(f.get("mod_expr", "")) != "" else ""
|
||||
if not plain:
|
||||
return "roll %s: %s, moved %s rows = %s" % [f.get("dice", ""), Expr.format_value(f["from"]), _signed(f["mod"]).replace(Describe.MINUS, "-"), total]
|
||||
return "Rolled %s on %s, moved %s %s%s, to row %s" % [Expr.format_value(f["from"]), f.get("dice", ""),
|
||||
"down" if float(f["mod"]) > 0 else "up", _rows(absi(int(f["mod"]))), by, total]
|
||||
return "Rolled %s on %s" % [total, f.get("dice", "")] if plain else "roll %s: %s" % [f.get("dice", ""), total]
|
||||
"card":
|
||||
return "Drew card %s" % total if plain else "draw: card %s" % total
|
||||
|
|
@ -164,6 +170,10 @@ static func _why_roll(f: Dictionary, L: Dictionary, plain: bool) -> String:
|
|||
return s
|
||||
|
||||
|
||||
static func _rows(count: int) -> String:
|
||||
return "1 row" if count == 1 else "%d rows" % count
|
||||
|
||||
|
||||
static func _why_check(f: Dictionary, L: Dictionary, plain: bool) -> String:
|
||||
var faces := _faces(f.get("faces"))
|
||||
var nat := Expr.format_value(f.get("nat"))
|
||||
|
|
|
|||
|
|
@ -20,17 +20,17 @@ const OPS := ["+=", "-=", "*=", "/=", "="]
|
|||
|
||||
|
||||
## A comma-separated list with `item` added at the end (unless it's there
|
||||
## already, ignoring capitals) or, with `remove`, taken out. Returns the new
|
||||
## list text. Used by += / -= on lists and by saving a result into a list
|
||||
## value (RollContext.save_result()).
|
||||
static func list_with(list: Variant, item: String, remove: bool = false) -> String:
|
||||
## already, ignoring capitals; with `repeats`, every time) or, with `remove`,
|
||||
## taken out (the first match). Returns the new list text. Used by += / -= on
|
||||
## lists and by saving a result into a list value (RollContext.save_result()).
|
||||
static func list_with(list: Variant, item: String, remove: bool = false, repeats: bool = false) -> String:
|
||||
var items := Expr.list_items(list if list != null else "")
|
||||
var at := -1
|
||||
for k in items.size():
|
||||
if items[k].to_lower() == item.to_lower():
|
||||
at = k
|
||||
break
|
||||
if not remove and at < 0 and item != "":
|
||||
if not remove and (at < 0 or repeats) and item != "":
|
||||
items.append(item)
|
||||
elif remove and at >= 0:
|
||||
items.remove_at(at)
|
||||
|
|
@ -230,7 +230,7 @@ static func _assign(st: Dictionary, ctx: RollContext, source_id: String, facts:
|
|||
"+=", "-=":
|
||||
if as_list:
|
||||
var item := Expr.format_value(rhs).strip_edges()
|
||||
value = list_with(cur, item, op == "-=")
|
||||
value = list_with(cur, item, op == "-=", ctx.declared(target) != null and ctx.declared(target).list_repeats)
|
||||
line = "%s %s %s → %s" % [label, "+" if op == "+=" else "−", item, _shown(value)]
|
||||
else:
|
||||
var a: Variant = Expr.to_value(cur) if cur != null and str(cur).strip_edges() != "" else 0
|
||||
|
|
@ -323,7 +323,11 @@ static func _reset(target: String, ctx: RollContext, facts: Variant = null) -> D
|
|||
static func reset_one(name: String, ctx: RollContext) -> String:
|
||||
var card := ctx.declared(name)
|
||||
if card == null:
|
||||
ctx.erase("@" + name)
|
||||
var ledger_entry := LedgerMembers.find(ctx.board, name)
|
||||
if not ledger_entry.is_empty():
|
||||
ctx.save("@" + name, ledger_entry["start"], (ledger_entry["card"] as RollTable).id)
|
||||
else:
|
||||
ctx.erase("@" + name)
|
||||
return ""
|
||||
var r := card.initial_value(ctx)
|
||||
ctx.save("@" + name, r["value"], card.id)
|
||||
|
|
|
|||
220
core/expr.gd
220
core/expr.gd
|
|
@ -19,14 +19,10 @@ extends RefCounted
|
|||
const MAX_DICE := 100
|
||||
const MAX_SIDES := 1000
|
||||
|
||||
const _KEYWORDS := ["and", "or", "not", "in", "true", "false", "null", "if", "else",
|
||||
"PI", "TAU", "INF", "NAN", "self"]
|
||||
|
||||
## source text -> {expr: Expression or null, inputs: Array[String] (input
|
||||
## names in order), vars: Array of [kind, name] per input ("@" board, "" chain),
|
||||
## text_side: Array[bool] per input (an unset value reads as ""), error: String}
|
||||
static var _cache: Dictionary = {}
|
||||
static var _dice_re: RegEx = null
|
||||
static var _name_re: RegEx = null
|
||||
|
||||
|
||||
|
|
@ -280,7 +276,7 @@ static func roll_dice(n: int, sides: int, rng: RandomNumberGenerator) -> int:
|
|||
|
||||
## The rewritten source (for tests and debugging).
|
||||
static func rewrite(src: String) -> String:
|
||||
return str(_rewrite(src)["text"])
|
||||
return str(ExprRewriter.rewrite(src)["text"])
|
||||
|
||||
|
||||
static func _parsed(src: String) -> Dictionary:
|
||||
|
|
@ -290,7 +286,7 @@ static func _parsed(src: String) -> Dictionary:
|
|||
if src.strip_edges() == "":
|
||||
p["error"] = "Empty expression"
|
||||
else:
|
||||
var rw := _rewrite(src)
|
||||
var rw := ExprRewriter.rewrite(src)
|
||||
if rw["error"] != "":
|
||||
p["error"] = rw["error"]
|
||||
else:
|
||||
|
|
@ -308,215 +304,3 @@ static func _parsed(src: String) -> Dictionary:
|
|||
_cache.clear()
|
||||
_cache[src] = p
|
||||
return p
|
||||
|
||||
|
||||
## Rewrites the user's syntax into Godot Expression syntax. Returns {text,
|
||||
## inputs, vars, text_side, error}.
|
||||
static func _rewrite(src: String) -> Dictionary:
|
||||
var out := ""
|
||||
var inputs: Array = []
|
||||
var vars: Array = []
|
||||
var text_side: Array = []
|
||||
var slot := {} # "@name" / "name" -> input index
|
||||
# Open brackets: true for an indirect @[ (closes with ")"), false for a
|
||||
# plain "[".
|
||||
var brackets: Array[bool] = []
|
||||
var n_ind := 0
|
||||
# Tokens as [kind, text]: kind "str", "var", "op", "other" (for text_side).
|
||||
var toks: Array = []
|
||||
var lits: Array[String] = []
|
||||
var i := 0
|
||||
var n := src.length()
|
||||
while i < n:
|
||||
var c := src[i]
|
||||
if c == "\"" or c == "'":
|
||||
var j := i + 1
|
||||
while j < n and src[j] != c:
|
||||
if src[j] == "\\":
|
||||
j += 1
|
||||
j += 1
|
||||
if j >= n:
|
||||
return {"text": "", "inputs": [], "vars": [], "text_side": [], "error": "A text value is missing its closing quote"}
|
||||
var lit := src.substr(i, j - i + 1)
|
||||
# A placeholder: a step name beside a scale value becomes its number
|
||||
# (ExprBase._lit), worked out below once the variables are known.
|
||||
out += "\u0002%d\u0002" % lits.size()
|
||||
toks.append(["str", lit, lits.size()])
|
||||
lits.append(lit)
|
||||
i = j + 1
|
||||
continue
|
||||
if c == "@" and i + 1 < n and src[i + 1] == "[":
|
||||
# @[expr]: an indirect variable, read through _iv() (or _ivt() when
|
||||
# it sits beside text, so unset reads as "").
|
||||
out += "\u0001%d\u0001" % n_ind
|
||||
toks.append(["ivo", n_ind])
|
||||
brackets.append(true)
|
||||
n_ind += 1
|
||||
i += 2
|
||||
continue
|
||||
if c == "[":
|
||||
brackets.append(false)
|
||||
elif c == "]" and not brackets.is_empty():
|
||||
if brackets.pop_back():
|
||||
var id := -1
|
||||
var depth := 0
|
||||
for t in range(toks.size() - 1, -1, -1):
|
||||
if toks[t][0] == "ivc":
|
||||
depth += 1
|
||||
elif toks[t][0] == "ivo":
|
||||
if depth == 0:
|
||||
id = toks[t][1]
|
||||
break
|
||||
depth -= 1
|
||||
out += ")"
|
||||
toks.append(["ivc", id])
|
||||
i += 1
|
||||
continue
|
||||
if c == "@":
|
||||
var j := i + 1
|
||||
while j < n and _is_word(src[j]):
|
||||
j += 1
|
||||
var name := src.substr(i + 1, j - i - 1).to_lower()
|
||||
if name == "" or not _is_word_start(name[0]):
|
||||
return {"text": "", "inputs": [], "vars": [], "text_side": [], "error": "\"@\" must be followed by a variable name"}
|
||||
if j < n and src[j] == "*":
|
||||
# @prefix_* as an argument, e.g. count(@skill_*): the prefix as text.
|
||||
var lit := "\"%s\"" % name
|
||||
out += lit
|
||||
toks.append(["str", lit])
|
||||
i = j + 1
|
||||
continue
|
||||
var key := "@" + name
|
||||
if not slot.has(key):
|
||||
slot[key] = inputs.size()
|
||||
inputs.append("_v%d" % inputs.size())
|
||||
vars.append(["@", name])
|
||||
text_side.append(false)
|
||||
out += inputs[slot[key]]
|
||||
toks.append(["var", slot[key]])
|
||||
i = j
|
||||
continue
|
||||
if _is_word(c):
|
||||
var j := i
|
||||
while j < n and (_is_word(src[j]) or (src[j] == "." and j + 1 < n and src[j + 1].is_valid_int() and src.substr(i, j - i).is_valid_int())):
|
||||
j += 1
|
||||
var word := src.substr(i, j - i)
|
||||
var dice := _dice_of(word)
|
||||
if not dice.is_empty():
|
||||
if dice[0] < 1 or dice[0] > MAX_DICE or dice[1] < 1 or dice[1] > MAX_SIDES:
|
||||
return {"text": "", "inputs": [], "vars": [], "text_side": [], "error": "%s isn't a dice roll this can make" % word}
|
||||
out += "_d(%d, %d)" % [dice[0], dice[1]]
|
||||
toks.append(["other", word])
|
||||
elif word[0].is_valid_int():
|
||||
out += word
|
||||
toks.append(["other", word])
|
||||
else:
|
||||
# A function call, a keyword or a chain variable.
|
||||
var k := j
|
||||
while k < n and src[k] == " ":
|
||||
k += 1
|
||||
var is_call := k < n and src[k] == "("
|
||||
if word == "if" and is_call:
|
||||
# Spreadsheet-style if(condition, then, else). Both branches
|
||||
# are evaluated, so dice in either one are rolled.
|
||||
out += "_if"
|
||||
toks.append(["other", word])
|
||||
elif word == "if" or word == "else":
|
||||
# Godot's Expression parses "a if c else b" but returns the
|
||||
# wrong branch, so refuse it rather than give silent nonsense.
|
||||
return {"text": "", "inputs": [], "vars": [], "text_side": [],
|
||||
"error": "Write if(condition, then, else) instead of \"… if … else …\""}
|
||||
elif is_call or _KEYWORDS.has(word):
|
||||
out += word
|
||||
toks.append(["op" if word == "in" else "other", word])
|
||||
else:
|
||||
if not slot.has(word):
|
||||
slot[word] = inputs.size()
|
||||
inputs.append("_v%d" % inputs.size())
|
||||
vars.append(["", word])
|
||||
text_side.append(false)
|
||||
out += inputs[slot[word]]
|
||||
toks.append(["var", slot[word]])
|
||||
i = j
|
||||
continue
|
||||
if c == "=":
|
||||
var prev := src[i - 1] if i > 0 else ""
|
||||
var next := src[i + 1] if i + 1 < n else ""
|
||||
if next == "=":
|
||||
out += "=="
|
||||
toks.append(["op", "=="])
|
||||
i += 2
|
||||
continue
|
||||
if prev != "=" and prev != "!" and prev != "<" and prev != ">":
|
||||
out += "=="
|
||||
toks.append(["op", "=="])
|
||||
i += 1
|
||||
continue
|
||||
if c != " " and c != "\t" and c != "\n":
|
||||
toks.append(["op", c])
|
||||
out += c
|
||||
i += 1
|
||||
if brackets.has(true):
|
||||
return {"text": "", "inputs": [], "vars": [], "text_side": [], "error": "@[ is missing its closing ]"}
|
||||
# An indirect @[…] beside a text literal (or `in`) reads as "" when unset.
|
||||
var beside := func(u: int) -> bool:
|
||||
return u >= 0 and u < toks.size() and (toks[u][0] == "str" or (toks[u][0] == "op" and toks[u][1] == "in"))
|
||||
for t in toks.size():
|
||||
if toks[t][0] != "ivo":
|
||||
continue
|
||||
var id: int = toks[t][1]
|
||||
var close := t
|
||||
for u in range(t + 1, toks.size()):
|
||||
if toks[u][0] == "ivc" and toks[u][1] == id:
|
||||
close = u
|
||||
break
|
||||
var text_side_ind: bool = beside.call(t - 1) or beside.call(t - 2) or beside.call(close + 1) or beside.call(close + 2)
|
||||
out = out.replace("\u0001%d\u0001" % id, "_ivt(" if text_side_ind else "_iv(")
|
||||
# A variable directly beside a text literal (or `in`) reads as "" when unset.
|
||||
for t in toks.size():
|
||||
if toks[t][0] != "var":
|
||||
continue
|
||||
for d in [-2, -1, 1, 2]:
|
||||
var u: int = t + d
|
||||
if u < 0 or u >= toks.size():
|
||||
continue
|
||||
if toks[u][0] == "str" or (toks[u][0] == "op" and toks[u][1] == "in"):
|
||||
text_side[toks[t][1]] = true
|
||||
# Each text literal goes beside the nearest @variable (left first), so a
|
||||
# step name can read as its number when that variable is a scale.
|
||||
for t in toks.size():
|
||||
if toks[t][0] != "str" or (toks[t] as Array).size() < 3:
|
||||
continue
|
||||
var near := -1
|
||||
for d in range(1, toks.size()):
|
||||
for u: int in [t - d, t + d]:
|
||||
if near < 0 and u >= 0 and u < toks.size() and toks[u][0] == "var" and vars[toks[u][1]][0] == "@":
|
||||
near = toks[u][1]
|
||||
if near >= 0:
|
||||
break
|
||||
var lit_s: String = toks[t][1]
|
||||
var put := lit_s if near < 0 else "_lit(%d, %s)" % [near, lit_s]
|
||||
out = out.replace("\u0002%d\u0002" % toks[t][2], put)
|
||||
return {"text": out, "inputs": inputs, "vars": vars, "text_side": text_side, "error": ""}
|
||||
|
||||
|
||||
## [count, sides] for a dice word ("2d6", "d20", "3D", "D3", "2D"), or [].
|
||||
static func _dice_of(word: String) -> Array:
|
||||
if _dice_re == null:
|
||||
_dice_re = RegEx.create_from_string("^(\\d*)[dD](\\d*)$")
|
||||
var m := _dice_re.search(word)
|
||||
if m == null:
|
||||
return []
|
||||
var a := m.get_string(1)
|
||||
var b := m.get_string(2)
|
||||
if a == "" and b == "":
|
||||
return []
|
||||
return [int(a) if a != "" else 1, int(b) if b != "" else 6]
|
||||
|
||||
|
||||
static func _is_word(c: String) -> bool:
|
||||
return c == "_" or c.is_valid_int() or (c.to_lower() != c.to_upper())
|
||||
|
||||
|
||||
static func _is_word_start(c: String) -> bool:
|
||||
return c == "_" or (c.to_lower() != c.to_upper())
|
||||
|
|
|
|||
239
core/expr_rewriter.gd
Normal file
239
core/expr_rewriter.gd
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
class_name ExprRewriter
|
||||
extends RefCounted
|
||||
## Turns an expression as the user writes it (@luck >= 8, 2d6 + 1, @[option])
|
||||
## into text that Godot's Expression class can run. Board and chain
|
||||
## variables become numbered inputs (_v0, _v1 ...), dice become _d() calls,
|
||||
## a lone "=" becomes "==", and text beside a variable is marked so an unset
|
||||
## value reads as "". Expr calls this once per new expression and caches it.
|
||||
|
||||
const _KEYWORDS := ["and", "or", "not", "in", "true", "false", "null", "if", "else",
|
||||
"PI", "TAU", "INF", "NAN", "self"]
|
||||
|
||||
|
||||
## Rewrites the user's syntax into Godot Expression syntax. Returns {text,
|
||||
## inputs, vars, text_side, error}.
|
||||
static func rewrite(src: String) -> Dictionary:
|
||||
var out := ""
|
||||
var inputs: Array = []
|
||||
var vars: Array = []
|
||||
var text_side: Array = []
|
||||
var slot := {} # "@name" / "name" -> input index
|
||||
# Open brackets: true for an indirect @[ (closes with ")"), false for a
|
||||
# plain "[".
|
||||
var brackets: Array[bool] = []
|
||||
var indirect_count := 0
|
||||
# Tokens as [kind, text]: kind "str", "var", "op", "other" (for text_side).
|
||||
var toks: Array = []
|
||||
var lits: Array[String] = []
|
||||
var i := 0
|
||||
var src_len := src.length()
|
||||
while i < src_len:
|
||||
var ch := src[i]
|
||||
if ch == "\"" or ch == "'":
|
||||
var j := i + 1
|
||||
while j < src_len and src[j] != ch:
|
||||
if src[j] == "\\":
|
||||
j += 1
|
||||
j += 1
|
||||
if j >= src_len:
|
||||
return _fail("A text value is missing its closing quote")
|
||||
var lit := src.substr(i, j - i + 1)
|
||||
# A placeholder: a step name beside a scale value becomes its number
|
||||
# (ExprBase._lit), worked out below once the variables are known.
|
||||
out += "\u0002%d\u0002" % lits.size()
|
||||
toks.append(["str", lit, lits.size()])
|
||||
lits.append(lit)
|
||||
i = j + 1
|
||||
continue
|
||||
if ch == "@" and i + 1 < src_len and src[i + 1] == "[":
|
||||
# @[expr]: an indirect variable, read through _iv() (or _ivt() when
|
||||
# it sits beside text, so unset reads as "").
|
||||
out += "\u0001%d\u0001" % indirect_count
|
||||
toks.append(["ivo", indirect_count])
|
||||
brackets.append(true)
|
||||
indirect_count += 1
|
||||
i += 2
|
||||
continue
|
||||
if ch == "[":
|
||||
brackets.append(false)
|
||||
elif ch == "]" and not brackets.is_empty():
|
||||
if brackets.pop_back():
|
||||
out += ")"
|
||||
toks.append(["ivc", _open_indirect_id(toks)])
|
||||
i += 1
|
||||
continue
|
||||
if ch == "@":
|
||||
var j := i + 1
|
||||
while j < src_len and RuleTokens.is_word(src[j]):
|
||||
j += 1
|
||||
var name := src.substr(i + 1, j - i - 1).to_lower()
|
||||
if name == "" or not _is_word_start(name[0]):
|
||||
return _fail("\"@\" must be followed by a variable name")
|
||||
if j < src_len and src[j] == "*":
|
||||
# @prefix_* as an argument, e.g. count(@skill_*): the prefix as text.
|
||||
var lit := "\"%s\"" % name
|
||||
out += lit
|
||||
toks.append(["str", lit])
|
||||
i = j + 1
|
||||
continue
|
||||
var key := "@" + name
|
||||
if not slot.has(key):
|
||||
slot[key] = inputs.size()
|
||||
inputs.append("_v%d" % inputs.size())
|
||||
vars.append(["@", name])
|
||||
text_side.append(false)
|
||||
out += inputs[slot[key]]
|
||||
toks.append(["var", slot[key]])
|
||||
i = j
|
||||
continue
|
||||
if RuleTokens.is_word(ch):
|
||||
var j := i
|
||||
while j < src_len and (RuleTokens.is_word(src[j]) or (src[j] == "." and j + 1 < src_len and src[j + 1].is_valid_int() and src.substr(i, j - i).is_valid_int())):
|
||||
j += 1
|
||||
var word := src.substr(i, j - i)
|
||||
var dice := dice_of(word)
|
||||
if not dice.is_empty():
|
||||
if dice[0] < 1 or dice[0] > Expr.MAX_DICE or dice[1] < 1 or dice[1] > Expr.MAX_SIDES:
|
||||
return _fail("%s isn't a dice roll this can make" % word)
|
||||
out += "_d(%d, %d)" % [dice[0], dice[1]]
|
||||
toks.append(["other", word])
|
||||
elif word[0].is_valid_int():
|
||||
out += word
|
||||
toks.append(["other", word])
|
||||
else:
|
||||
# A function call, a keyword or a chain variable.
|
||||
var after := j
|
||||
while after < src_len and src[after] == " ":
|
||||
after += 1
|
||||
var is_call := after < src_len and src[after] == "("
|
||||
if word == "if" and is_call:
|
||||
# Spreadsheet-style if(condition, then, else). Both branches
|
||||
# are evaluated, so dice in either one are rolled.
|
||||
out += "_if"
|
||||
toks.append(["other", word])
|
||||
elif word == "if" or word == "else":
|
||||
# Godot's Expression parses "a if c else b" but returns the
|
||||
# wrong branch, so refuse it rather than give silent nonsense.
|
||||
return _fail("Write if(condition, then, else) instead of \"… if … else …\"")
|
||||
elif is_call or _KEYWORDS.has(word):
|
||||
out += word
|
||||
toks.append(["op" if word == "in" else "other", word])
|
||||
else:
|
||||
if not slot.has(word):
|
||||
slot[word] = inputs.size()
|
||||
inputs.append("_v%d" % inputs.size())
|
||||
vars.append(["", word])
|
||||
text_side.append(false)
|
||||
out += inputs[slot[word]]
|
||||
toks.append(["var", slot[word]])
|
||||
i = j
|
||||
continue
|
||||
if ch == "=":
|
||||
var prev := src[i - 1] if i > 0 else ""
|
||||
var next := src[i + 1] if i + 1 < src_len else ""
|
||||
if next == "=":
|
||||
out += "=="
|
||||
toks.append(["op", "=="])
|
||||
i += 2
|
||||
continue
|
||||
if prev != "=" and prev != "!" and prev != "<" and prev != ">":
|
||||
out += "=="
|
||||
toks.append(["op", "=="])
|
||||
i += 1
|
||||
continue
|
||||
if ch != " " and ch != "\t" and ch != "\n":
|
||||
toks.append(["op", ch])
|
||||
out += ch
|
||||
i += 1
|
||||
if brackets.has(true):
|
||||
return _fail("@[ is missing its closing ]")
|
||||
out = _place_indirect_reads(out, toks)
|
||||
_mark_text_side(toks, text_side)
|
||||
out = _place_literals(out, toks, vars)
|
||||
return {"text": out, "inputs": inputs, "vars": vars, "text_side": text_side, "error": ""}
|
||||
|
||||
|
||||
## [count, sides] for a dice word ("2d6", "d20", "3D", "D3", "2D"), or [].
|
||||
static func dice_of(word: String) -> Array:
|
||||
var found := RuleTokens.dice_regex().search(word)
|
||||
if found == null:
|
||||
return []
|
||||
var count_text := found.get_string(1)
|
||||
var sides_text := found.get_string(2)
|
||||
if count_text == "" and sides_text == "":
|
||||
return []
|
||||
return [int(count_text) if count_text != "" else 1, int(sides_text) if sides_text != "" else 6]
|
||||
|
||||
|
||||
static func _fail(message: String) -> Dictionary:
|
||||
return {"text": "", "inputs": [], "vars": [], "text_side": [], "error": message}
|
||||
|
||||
|
||||
## The id of the innermost indirect @[ that is still open in `toks`.
|
||||
static func _open_indirect_id(toks: Array) -> int:
|
||||
var depth := 0
|
||||
for tok_index in range(toks.size() - 1, -1, -1):
|
||||
if toks[tok_index][0] == "ivc":
|
||||
depth += 1
|
||||
elif toks[tok_index][0] == "ivo":
|
||||
if depth == 0:
|
||||
return toks[tok_index][1]
|
||||
depth -= 1
|
||||
return -1
|
||||
|
||||
|
||||
## True when the token at `tok_index` is a text literal or `in`.
|
||||
static func _is_text_token(toks: Array, tok_index: int) -> bool:
|
||||
return tok_index >= 0 and tok_index < toks.size() \
|
||||
and (toks[tok_index][0] == "str" or (toks[tok_index][0] == "op" and toks[tok_index][1] == "in"))
|
||||
|
||||
|
||||
## An indirect @[…] beside a text literal (or `in`) reads as "" when unset:
|
||||
## its placeholder becomes _ivt( there, and _iv( everywhere else.
|
||||
static func _place_indirect_reads(out: String, toks: Array) -> String:
|
||||
for tok_index in toks.size():
|
||||
if toks[tok_index][0] != "ivo":
|
||||
continue
|
||||
var id: int = toks[tok_index][1]
|
||||
var close := tok_index
|
||||
for other in range(tok_index + 1, toks.size()):
|
||||
if toks[other][0] == "ivc" and toks[other][1] == id:
|
||||
close = other
|
||||
break
|
||||
var beside_text := _is_text_token(toks, tok_index - 1) or _is_text_token(toks, tok_index - 2) \
|
||||
or _is_text_token(toks, close + 1) or _is_text_token(toks, close + 2)
|
||||
out = out.replace("\u0001%d\u0001" % id, "_ivt(" if beside_text else "_iv(")
|
||||
return out
|
||||
|
||||
|
||||
## A variable directly beside a text literal (or `in`) reads as "" when unset.
|
||||
static func _mark_text_side(toks: Array, text_side: Array) -> void:
|
||||
for tok_index in toks.size():
|
||||
if toks[tok_index][0] != "var":
|
||||
continue
|
||||
for offset in [-2, -1, 1, 2]:
|
||||
if _is_text_token(toks, tok_index + offset):
|
||||
text_side[toks[tok_index][1]] = true
|
||||
|
||||
|
||||
## Each text literal goes beside the nearest @variable (left first), so a
|
||||
## step name can read as its number when that variable is a scale.
|
||||
static func _place_literals(out: String, toks: Array, vars: Array) -> String:
|
||||
for tok_index in toks.size():
|
||||
if toks[tok_index][0] != "str" or (toks[tok_index] as Array).size() < 3:
|
||||
continue
|
||||
var near := -1
|
||||
for distance in range(1, toks.size()):
|
||||
for other: int in [tok_index - distance, tok_index + distance]:
|
||||
if near < 0 and other >= 0 and other < toks.size() and toks[other][0] == "var" and vars[toks[other][1]][0] == "@":
|
||||
near = toks[other][1]
|
||||
if near >= 0:
|
||||
break
|
||||
var lit_text: String = toks[tok_index][1]
|
||||
var put := lit_text if near < 0 else "_lit(%d, %s)" % [near, lit_text]
|
||||
out = out.replace("\u0002%d\u0002" % toks[tok_index][2], put)
|
||||
return out
|
||||
|
||||
|
||||
static func _is_word_start(ch: String) -> bool:
|
||||
return ch == "_" or (ch.to_lower() != ch.to_upper())
|
||||
1
core/expr_rewriter.gd.uid
Normal file
1
core/expr_rewriter.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://cm0xg4ul6rfm
|
||||
|
|
@ -20,6 +20,8 @@ const KNOWN_TAGS: Array[String] = [
|
|||
"table", "cell", "ul", "ol", "lb", "rb", "br", "hr", "lrm", "rlm", "lre", "rle",
|
||||
"lro", "rlo", "pdf", "alm", "lri", "rli", "fsi", "pdi", "zwj", "zwnj", "wj", "shy",
|
||||
"wave", "tornado", "shake", "fade", "rainbow", "pulse",
|
||||
# The app's own effects (ui/text_effects).
|
||||
"sparkle", "shimmer", "flash",
|
||||
]
|
||||
|
||||
## Tags that stand alone and never take a closing tag.
|
||||
|
|
|
|||
115
core/ledger_members.gd
Normal file
115
core/ledger_members.gd
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
class_name LedgerMembers
|
||||
extends RefCounted
|
||||
## A Ledger card's entries (in code: a collection variable card's `members`).
|
||||
## The card lists each entry's name and starting value, so they are saved in
|
||||
## the spread file and travel with copies, exports and imports. The entry's
|
||||
## current value is a saved value of the spread, @<stem>_<name>, like any
|
||||
## other value: these functions keep the two in step.
|
||||
##
|
||||
## A member is {"name": "climbing", "start": "0"}: the name is a slug (no
|
||||
## spaces) and the start is text (a number or words).
|
||||
|
||||
|
||||
## Cleans a "members" value from JSON or the UI: blank and repeated names are
|
||||
## dropped, names become slugs, starts become text.
|
||||
static func clean(value: Variant) -> Array:
|
||||
var out: Array = []
|
||||
if not (value is Array):
|
||||
return out
|
||||
var seen := {}
|
||||
for item: Variant in value:
|
||||
if not (item is Dictionary):
|
||||
continue
|
||||
var member_name := JsonIO.slug(str(item.get("name", "")), "")
|
||||
if member_name == "" or seen.has(member_name):
|
||||
continue
|
||||
seen[member_name] = true
|
||||
var start: Variant = item.get("start", "0")
|
||||
out.append({"name": member_name, "start": "" if start == null else Expr.format_value(start)})
|
||||
return out
|
||||
|
||||
|
||||
## The saved-value name of a card's member: "skill_climbing".
|
||||
static func value_name(card: RollTable, member_name: String) -> String:
|
||||
return "%s_%s" % [card.var_name, member_name]
|
||||
|
||||
|
||||
## Index of the member called `member_name` on `card`, or -1.
|
||||
static func index_of(card: RollTable, member_name: String) -> int:
|
||||
for i in card.members.size():
|
||||
if str(card.members[i]["name"]) == member_name:
|
||||
return i
|
||||
return -1
|
||||
|
||||
|
||||
## The starting value of a member, as a number when it looks like one.
|
||||
static func start_value(start: String) -> Variant:
|
||||
return Expr.to_value(start) if Expr.is_number(start) else start
|
||||
|
||||
|
||||
## The Ledger card that lists the saved value `name` ("skill_climbing" or
|
||||
## "@skill_climbing") and the entry's starting value: {"card", "start"}, or
|
||||
## {} when no Ledger card lists it.
|
||||
static func find(board: TowerBoard, name: String) -> Dictionary:
|
||||
if board == null:
|
||||
return {}
|
||||
var bare := name.strip_edges().trim_prefix("@")
|
||||
for card in board.tables:
|
||||
if not card.is_collection() or card.var_name == "":
|
||||
continue
|
||||
for member: Dictionary in card.members:
|
||||
if value_name(card, str(member["name"])) == bare:
|
||||
return {"card": card, "start": start_value(str(member["start"]))}
|
||||
return {}
|
||||
|
||||
|
||||
## Older spreads kept a Ledger's entries only as saved values. A Ledger card
|
||||
## with no members takes in the saved values that were made on it (source =
|
||||
## the card), with their current value as the start. Values that rolls added
|
||||
## (another source) are left as they are. Returns true when a card changed.
|
||||
static func adopt(board: TowerBoard, persistent: Dictionary) -> bool:
|
||||
if board == null:
|
||||
return false
|
||||
var changed := false
|
||||
for card in board.tables:
|
||||
if not card.is_collection() or card.var_name == "" or not card.members.is_empty():
|
||||
continue
|
||||
var prefix := card.var_name + "_"
|
||||
var names: Array = persistent.keys()
|
||||
names.sort_custom(func(left: String, right: String) -> bool: return left.naturalnocasecmp_to(right) < 0)
|
||||
for saved_name: String in names:
|
||||
var saved: Variant = persistent[saved_name]
|
||||
if not saved_name.begins_with(prefix) or saved_name.length() <= prefix.length():
|
||||
continue
|
||||
if not (saved is Dictionary) or str(saved.get("source", "")) != card.id:
|
||||
continue
|
||||
card.members.append({"name": saved_name.substr(prefix.length()), "start": Expr.format_value(saved.get("value"))})
|
||||
changed = true
|
||||
return changed
|
||||
|
||||
|
||||
## Brings the saved values in line with the Ledger cards: a member with no
|
||||
## saved value gets its start, and a value made on the card (source = the
|
||||
## card) whose member is gone is removed. Returns true when anything changed.
|
||||
static func sync(board: TowerBoard, persistent: Dictionary) -> bool:
|
||||
if board == null:
|
||||
return false
|
||||
var changed := false
|
||||
for card in board.tables:
|
||||
if not card.is_collection() or card.var_name == "":
|
||||
continue
|
||||
var listed := {}
|
||||
for member: Dictionary in card.members:
|
||||
var saved_name := value_name(card, str(member["name"]))
|
||||
listed[saved_name] = true
|
||||
if not persistent.has(saved_name):
|
||||
persistent[saved_name] = {"value": start_value(str(member["start"])), "source": card.id}
|
||||
changed = true
|
||||
if card.members.is_empty():
|
||||
continue
|
||||
for saved_name: String in persistent.keys():
|
||||
var saved: Variant = persistent[saved_name]
|
||||
if saved_name.begins_with(card.var_name + "_") and not listed.has(saved_name) and saved is Dictionary and str(saved.get("source", "")) == card.id:
|
||||
persistent.erase(saved_name)
|
||||
changed = true
|
||||
return changed
|
||||
1
core/ledger_members.gd.uid
Normal file
1
core/ledger_members.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://beeuxo7krcjom
|
||||
|
|
@ -66,7 +66,7 @@ func list() -> Array[Dictionary]:
|
|||
continue
|
||||
var b := load_collection(id)
|
||||
if b:
|
||||
out.append({"id": id, "name": b.name})
|
||||
out.append({"id": id, "name": b.name, "folder": b.folder})
|
||||
out.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
|
||||
return str(a["name"]).naturalnocasecmp_to(str(b["name"])) < 0)
|
||||
return out
|
||||
|
|
|
|||
|
|
@ -8,15 +8,22 @@ extends RefCounted
|
|||
## Most times a thread rolls again on the results it skips before giving up.
|
||||
const MAX_REROLLS := 100
|
||||
const ALL_REROLLED := "This thread rolls again on every result"
|
||||
const NONE_ALLOWED := "Nothing on this card can come up right now: every result's Only if is false"
|
||||
|
||||
|
||||
## pick_node() for the frame `f` that reached the card: its thread may roll
|
||||
## with other dice (f.dice) and roll again on some results (f.reroll, result
|
||||
## ids). Skipped rolls go in a {"type": "reroll", "skipped": [{value, text}]}
|
||||
## why fact on the kept node.
|
||||
## ids). A result whose "Only if" (show_if) is false right now is rolled
|
||||
## again too. Skipped rolls go in a {"type": "reroll", "skipped": [{value,
|
||||
## text}]} why fact on the kept node.
|
||||
static func pick_for(t: RollTable, ctx: RollContext, f: Dictionary) -> Dictionary:
|
||||
var dice := str(f.get("dice", ""))
|
||||
var skip: Array = f.get("reroll", [])
|
||||
var thread_skip: Array = f.get("reroll", [])
|
||||
var skip: Array = thread_skip.duplicate()
|
||||
if t.kind == RollTable.KIND_ROLL:
|
||||
for e in t.entries:
|
||||
if e.show_if.strip_edges() != "" and not skip.has(e.id) and not RollChoice.option_shown(e, ctx):
|
||||
skip.append(e.id)
|
||||
if skip.is_empty():
|
||||
return pick_node(t, ctx, dice)
|
||||
var left := false
|
||||
|
|
@ -24,7 +31,7 @@ static func pick_for(t: RollTable, ctx: RollContext, f: Dictionary) -> Dictionar
|
|||
if not skip.has(e.id) and t.can_come_up(e):
|
||||
left = true
|
||||
if not left:
|
||||
return Roller._stop(t, ALL_REROLLED)
|
||||
return Roller._stop(t, ALL_REROLLED if skip.size() == thread_skip.size() else NONE_ALLOWED)
|
||||
var skipped: Array = []
|
||||
for n in MAX_REROLLS:
|
||||
var node := pick_node(t, ctx, dice)
|
||||
|
|
@ -32,7 +39,8 @@ static func pick_for(t: RollTable, ctx: RollContext, f: Dictionary) -> Dictionar
|
|||
if not skipped.is_empty():
|
||||
Roller._why(node, [{"type": "reroll", "skipped": skipped}])
|
||||
return node
|
||||
skipped.append({"value": node["value"], "text": Formatter.strip_tags((node["entry"] as TableEntry).text).strip_edges()})
|
||||
skipped.append({"value": node["value"], "text": Formatter.strip_tags((node["entry"] as TableEntry).text).strip_edges(),
|
||||
"entry_id": (node["entry"] as TableEntry).id})
|
||||
return Roller._stop(t, ALL_REROLLED)
|
||||
|
||||
|
||||
|
|
@ -101,6 +109,19 @@ static func pick_node(t: RollTable, ctx: RollContext, dice: String = "") -> Dict
|
|||
return Roller._stop(t, "No result can come up")
|
||||
value = index + 1
|
||||
fact = {"type": "roll", "pick": "weighted", "dice": t.dice_label(), "total": value}
|
||||
# A plain table's modifier moves the pick down (+) or up (−) the list by
|
||||
# that many rows; the first and last rows catch anything past them.
|
||||
if t.has_mod():
|
||||
var shift := RollRange.modifier(t.dice_mod, ctx)
|
||||
if shift["error"] != "":
|
||||
return Roller._stop(t, "Can't work out the modifier %s: %s" % [t.dice_mod.strip_edges(), shift["error"]])
|
||||
var moved := clampi(index + int(shift["value"]), 0, t.entries.size() - 1)
|
||||
fact["mod"] = int(shift["value"])
|
||||
fact["mod_expr"] = t.dice_mod.strip_edges()
|
||||
fact["from"] = value
|
||||
index = moved
|
||||
value = index + 1
|
||||
fact["total"] = value
|
||||
var node := {"table": t, "index": index, "value": value, "entry": t.entries[index], "children": [],
|
||||
"summary": "", "why": [fact]}
|
||||
if reshuffled:
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -11,7 +11,8 @@ extends RefCounted
|
|||
## happen as usual.
|
||||
##
|
||||
## A "roll twice and combine" row (TableEntry.repeat) that comes up in a
|
||||
## column rolls that column again `count` times and combines the texts with
|
||||
## column it applies to (repeat "columns": indices; none listed = every
|
||||
## column) rolls that column again `count` times and combines the texts with
|
||||
## REPEAT_JOIN ("Ash & Black"); a repeat row that comes up on those rolls adds
|
||||
## its own count (so "roll twice" again means one more), up to MAX_REPEATS.
|
||||
##
|
||||
|
|
@ -59,7 +60,7 @@ static func fill(node: Dictionary, f: Dictionary, ctx: RollContext, depth: int)
|
|||
row["index"] = int(pick["index"])
|
||||
row["value"] = pick.get("value")
|
||||
var e: TableEntry = pick["entry"]
|
||||
if not e.repeat.is_empty():
|
||||
if repeats_in(e, k):
|
||||
text = await _repeat(node, t, k, e, f, ctx, depth, why)
|
||||
elif k == 0:
|
||||
text = str(node["summary"])
|
||||
|
|
@ -110,7 +111,7 @@ static func _repeat(node: Dictionary, t: RollTable, k: int, e: TableEntry, f: Di
|
|||
got.append(str(p["summary"]))
|
||||
continue
|
||||
var pe: TableEntry = p["entry"]
|
||||
if not pe.repeat.is_empty():
|
||||
if repeats_in(pe, k):
|
||||
for _n in int(pe.repeat.get("count", 2)):
|
||||
queue.append(pe.repeat.get("reroll", []))
|
||||
continue
|
||||
|
|
@ -121,6 +122,14 @@ static func _repeat(node: Dictionary, t: RollTable, k: int, e: TableEntry, f: Di
|
|||
return REPEAT_JOIN.join(got)
|
||||
|
||||
|
||||
## True when entry `e`'s "roll again and combine" applies in column `k`.
|
||||
static func repeats_in(e: TableEntry, k: int) -> bool:
|
||||
if e.repeat.is_empty():
|
||||
return false
|
||||
var only: Variant = e.repeat.get("columns")
|
||||
return not (only is Array) or (only as Array).is_empty() or (only as Array).has(k)
|
||||
|
||||
|
||||
static func _add_why(why: Array, pick: Dictionary, column: String) -> void:
|
||||
if pick.has("why"):
|
||||
for fact: Dictionary in pick["why"]:
|
||||
|
|
|
|||
|
|
@ -128,7 +128,7 @@ func save_result(name: String, value: Variant, source_id: String = "") -> void:
|
|||
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)
|
||||
list = Effects.list_with(list, item, false, card.list_repeats)
|
||||
save(n, list if list != null else "", source_id)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,30 +1,31 @@
|
|||
class_name RollCosts
|
||||
extends RefCounted
|
||||
## Costs on choice options: an option can cost an amount of a value
|
||||
## (TableEntry.cost_value, cost_amount). It's offered greyed out, with the
|
||||
## reason, when the value is too low; picking it takes the amount away.
|
||||
## A "Reroll?" option that pipes back to a card and costs a point makes a
|
||||
## spend-a-point-to-reroll table.
|
||||
## Costs: a choice option (TableEntry) or a whole card (RollTable) can cost an
|
||||
## amount of a value (cost_value, cost_amount). An option is offered greyed
|
||||
## out, with the reason, when the value is too low; picking it takes the
|
||||
## amount away. A "Reroll?" option that pipes back to a card and costs a point
|
||||
## makes a spend-a-point-to-reroll table. A card with a cost can't be rolled
|
||||
## without it; a thread that reaches it asks first (card_gate).
|
||||
|
||||
|
||||
## "" when the option can be afforded now, else why not (shown to the player).
|
||||
static func blocked(e: TableEntry, ctx: RollContext, board: TowerBoard = null) -> String:
|
||||
static func blocked(e: Object, ctx: RollContext, board: TowerBoard = null) -> String:
|
||||
if not has_cost(e):
|
||||
return ""
|
||||
var have := _number(Expr.evaluate(var_ref(e), ctx))
|
||||
var need := _number(Expr.evaluate(e.cost_amount, ctx))
|
||||
var need := _number(Expr.evaluate(str(e.get("cost_amount")), ctx))
|
||||
if have >= need:
|
||||
return ""
|
||||
return "Needs %s %s (you have %s)" % [Expr.format_value(need), label(e, board), Expr.format_value(have)]
|
||||
|
||||
|
||||
static func has_cost(e: TableEntry) -> bool:
|
||||
return e.cost_value.strip_edges() != "" and e.cost_amount.strip_edges() != ""
|
||||
static func has_cost(e: Object) -> bool:
|
||||
return str(e.get("cost_value")).strip_edges() != "" and str(e.get("cost_amount")).strip_edges() != ""
|
||||
|
||||
|
||||
## "Costs 1 Luck".
|
||||
static func describe(e: TableEntry, board: TowerBoard = null) -> String:
|
||||
return "Costs %s %s" % [e.cost_amount.strip_edges(), label(e, board)] if has_cost(e) else ""
|
||||
static func describe(e: Object, board: TowerBoard = null) -> String:
|
||||
return "Costs %s %s" % [str(e.get("cost_amount")).strip_edges(), label(e, board)] if has_cost(e) else ""
|
||||
|
||||
|
||||
## Takes the cost away (an ordinary change, so it shows in the result's
|
||||
|
|
@ -37,12 +38,47 @@ static func pay(e: TableEntry, ctx: RollContext, t: RollTable, node: Dictionary)
|
|||
Roller._why(node, facts)
|
||||
|
||||
|
||||
static func var_ref(e: TableEntry) -> String:
|
||||
var v := e.cost_value.strip_edges()
|
||||
return v if v.begins_with("@") else "@" + v
|
||||
## A card's cost before it rolls. A roll that starts on the card (its
|
||||
## button) pays when it can, else stops with the reason. A thread that reaches
|
||||
## it asks the player first (a "pause" question: Continue pays). Returns false
|
||||
## when the card doesn't roll; then a stop node says why. Payment shows as a
|
||||
## change on the card's result (frame "pre_why").
|
||||
static func card_gate(board: TowerBoard, t: RollTable, f: Dictionary, ctx: RollContext) -> bool:
|
||||
if not has_cost(t):
|
||||
return true
|
||||
var reason := blocked(t, ctx, board)
|
||||
var cost := describe(t, board).to_lower()
|
||||
if not f.get("top", false):
|
||||
if reason != "":
|
||||
Roller._attach(f, Roller._stop(t, "Not rolled: %s" % reason.to_lower()), ctx)
|
||||
return false
|
||||
var request := {"kind": "pause", "table_id": t.id, "title": t.name, "cost": cost,
|
||||
"prompt": "Pay %s to roll %s?" % [cost.trim_prefix("costs "), Formatter.strip_tags(t.name)],
|
||||
"from": Formatter.strip_tags(t.name)}
|
||||
var reply: Variant = await RollChoice.ask(ctx, request)
|
||||
if reply != true:
|
||||
Roller._attach(f, Roller._stop(t, "Not rolled: you didn't pay"), ctx)
|
||||
return false
|
||||
elif reason != "":
|
||||
Roller._attach(f, Roller._stop(t, "Can't roll: %s" % reason.to_lower()), ctx)
|
||||
return false
|
||||
var facts: Array = []
|
||||
var lines := Effects.run("%s -= %s" % [var_ref(t), t.cost_amount.strip_edges()], ctx, t.id, facts)
|
||||
var pre_why: Array = f.get("pre_why", [])
|
||||
pre_why.append_array(facts)
|
||||
f["pre_why"] = pre_why
|
||||
var pre_log: Array = f.get("pre_log", [])
|
||||
pre_log.append_array(lines)
|
||||
f["pre_log"] = pre_log
|
||||
return true
|
||||
|
||||
|
||||
static func label(e: TableEntry, board: TowerBoard) -> String:
|
||||
static func var_ref(e: Object) -> String:
|
||||
var value_name := str(e.get("cost_value")).strip_edges()
|
||||
return value_name if value_name.begins_with("@") else "@" + value_name
|
||||
|
||||
|
||||
static func label(e: Object, board: TowerBoard) -> String:
|
||||
return Describe.label(var_ref(e).trim_prefix("@"), board) if board else var_ref(e).trim_prefix("@")
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -147,8 +147,8 @@ static func lint_options(t: RollTable) -> Array[Dictionary]:
|
|||
var w := e.show_if.strip_edges()
|
||||
if w == "":
|
||||
continue
|
||||
if not pick:
|
||||
out.append({"table_id": t.id, "entry_id": e.id, "message": "Show only if %s does nothing: only Which option cards hide options" % w})
|
||||
if not pick and t.kind != RollTable.KIND_ROLL:
|
||||
out.append({"table_id": t.id, "entry_id": e.id, "message": "Only if %s does nothing here: only results and Which options can be held back" % w})
|
||||
elif Expr.check(w) != "":
|
||||
out.append({"table_id": t.id, "entry_id": e.id, "message": "Show only if %s: %s" % [w, Expr.check(w)]})
|
||||
return out
|
||||
|
|
|
|||
84
core/roll_live.gd
Normal file
84
core/roll_live.gd
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
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.
|
||||
## Ledger entries that aren't set get their starting value the same way.
|
||||
static func apply_starting_values(board: TowerBoard, ctx: RollContext) -> void:
|
||||
if board == null:
|
||||
return
|
||||
for table in board.tables:
|
||||
if table.is_collection() and table.var_name != "":
|
||||
for member: Dictionary in table.members:
|
||||
var member_value := "@" + LedgerMembers.value_name(table, str(member["name"]))
|
||||
if ctx.get_value(member_value) == null:
|
||||
ctx.save(member_value, LedgerMembers.start_value(str(member["start"])), table.id)
|
||||
continue
|
||||
if table.kind != RollTable.KIND_VARIABLE 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
1
core/roll_live.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bud06wjypp8dn
|
||||
63
core/roll_nodes.gd
Normal file
63
core/roll_nodes.gd
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
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"]
|
||||
# Facts from before the pick (inputs, a paid cost) come first.
|
||||
if frame.has("pre_why"):
|
||||
var facts: Array = (frame["pre_why"] as Array).duplicate()
|
||||
if node.has("why"):
|
||||
facts.append_array(node["why"])
|
||||
node["why"] = facts
|
||||
add_log(node, frame.get("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
1
core/roll_nodes.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://c4ew0gu64j7vn
|
||||
|
|
@ -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,86 @@ 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)
|
||||
if entry.pipe_distinct.has(target) and int(item["count"]) > 1:
|
||||
frame["distinct_from"] = (node["children"] as Array).size()
|
||||
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.has("distinct_from"):
|
||||
# No repeats: this roll also skips every result this thread already gave.
|
||||
var skip: Array = (frame.get("reroll", []) as Array).duplicate()
|
||||
var children: Array = (frame["node"] as Dictionary)["children"]
|
||||
for i in range(int(frame["distinct_from"]), children.size()):
|
||||
var child: Dictionary = children[i]
|
||||
if child.get("entry") is TableEntry and (child["table"] as RollTable).id == str(frame["to"]) and not skip.has((child["entry"] as TableEntry).id):
|
||||
skip.append((child["entry"] as TableEntry).id)
|
||||
roll_frame["reroll"] = skip
|
||||
if frame.get("no_follow", false):
|
||||
roll_frame["no_follow"] = true
|
||||
stack.append(roll_frame)
|
||||
|
|
|
|||
|
|
@ -120,6 +120,15 @@ var var_type: String = "number"
|
|||
var initial: String = ""
|
||||
## Scale variables: the ordered steps, lowest first.
|
||||
var steps: Array[String] = []
|
||||
## A cost to roll this card (RollCosts): the value ("@luck") and the amount
|
||||
## taken away each time. Empty = free.
|
||||
var cost_value: String = ""
|
||||
var cost_amount: String = ""
|
||||
## List cards: true when the list keeps repeats (an item added every time, in
|
||||
## order); false adds an item only if it isn't there yet.
|
||||
var list_repeats := false
|
||||
## Ledger cards: the entries, [{name, start}] (LedgerMembers).
|
||||
var members: Array = []
|
||||
## Check cards: the dice, the modifier and the target (expressions) and the
|
||||
## comparison ("ge" or "le"). entries[0] is Success, entries[1] Failure.
|
||||
var check_dice: String = CHECK_DEFAULT_DICE
|
||||
|
|
@ -142,58 +151,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 +201,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 +216,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 +265,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 +287,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 +301,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 +313,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 +331,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 +341,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)
|
||||
|
|
|
|||
72
core/roll_table_factory.gd
Normal file
72
core/roll_table_factory.gd
Normal 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"
|
||||
1
core/roll_table_factory.gd.uid
Normal file
1
core/roll_table_factory.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://beg2f63ux4nmx
|
||||
|
|
@ -19,6 +19,8 @@ static func to_dict(t: RollTable) -> Dictionary:
|
|||
d["tags"] = t.tags.duplicate()
|
||||
if t.color != "":
|
||||
d["color"] = t.color
|
||||
if t.cost_value.strip_edges() != "" and t.cost_amount.strip_edges() != "":
|
||||
d["cost"] = {"value": t.cost_value.strip_edges(), "amount": t.cost_amount.strip_edges()}
|
||||
if t.roll_floor.strip_edges() != "":
|
||||
d["roll_floor"] = t.roll_floor.strip_edges()
|
||||
if t.roll_ceiling.strip_edges() != "":
|
||||
|
|
@ -29,8 +31,8 @@ static func to_dict(t: RollTable) -> Dictionary:
|
|||
d["list_h"] = roundi(t.list_height)
|
||||
if t.is_ranged():
|
||||
d["dice"] = t.dice
|
||||
if t.has_mod():
|
||||
d["dice_mod"] = t.dice_mod.strip_edges()
|
||||
if t.has_mod():
|
||||
d["dice_mod"] = t.dice_mod.strip_edges()
|
||||
if t.card_mode:
|
||||
d["card_mode"] = true
|
||||
if t.deck_empty != "reshuffle":
|
||||
|
|
@ -72,6 +74,10 @@ static func to_dict(t: RollTable) -> Dictionary:
|
|||
d["initial"] = t.initial
|
||||
if t.var_type == RollTable.VAR_SCALE and not t.steps.is_empty():
|
||||
d["steps"] = t.steps.duplicate()
|
||||
if t.var_type == "list" and t.list_repeats:
|
||||
d["repeats"] = true
|
||||
if t.is_collection() and not t.members.is_empty():
|
||||
d["members"] = t.members.duplicate(true)
|
||||
elif t.kind == RollTable.KIND_CHECK:
|
||||
if t.check_dice != RollTable.CHECK_DEFAULT_DICE:
|
||||
d["check_dice"] = t.check_dice
|
||||
|
|
@ -135,6 +141,12 @@ static func from_dict(d: Dictionary) -> RollTable:
|
|||
t.var_type = vt if RollTable.VAR_TYPES.has(vt) else "number"
|
||||
t.initial = RollTable.expr_text(d.get("initial", ""), "")
|
||||
t.steps = Scales.clean(d.get("steps", []))
|
||||
t.members = LedgerMembers.clean(d.get("members", []))
|
||||
t.list_repeats = bool(d.get("repeats", false))
|
||||
var cost: Variant = d.get("cost")
|
||||
if cost is Dictionary:
|
||||
t.cost_value = str(cost.get("value", ""))
|
||||
t.cost_amount = str(cost.get("amount", ""))
|
||||
t.check_dice = RollTable.expr_text(d.get("check_dice", RollTable.CHECK_DEFAULT_DICE), RollTable.CHECK_DEFAULT_DICE).strip_edges()
|
||||
if t.check_dice == "":
|
||||
t.check_dice = RollTable.CHECK_DEFAULT_DICE
|
||||
|
|
@ -177,3 +189,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)
|
||||
|
|
|
|||
|
|
@ -34,6 +34,8 @@ static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
|
|||
step["save_as"] = n["save_as"]
|
||||
if n.has("kind"):
|
||||
step["kind"] = n["kind"]
|
||||
if n.has("spread"):
|
||||
step["spread"] = n["spread"]
|
||||
if n.has("effects"):
|
||||
step["effects"] = (n["effects"] as Array).duplicate(true)
|
||||
for k in ["answer", "passes", "pass", "after", "picked", "only_option", "random", "limit", "cancelled", "deck_empty", "dropped", "kept", "combined", "stopped_before", "case", "option", "check", "inputs", "columns"]:
|
||||
|
|
@ -138,7 +140,7 @@ static func link_key(table_id: String, entry_id: String, c: Dictionary) -> Strin
|
|||
|
||||
|
||||
## Ids of the tables an entry's text references, resolved against the board,
|
||||
## without duplicates or missing tables.
|
||||
## without duplicates, missing tables or cards from other spreads.
|
||||
static func ref_targets(board: TowerBoard, text: String) -> Array[String]:
|
||||
var out: Array[String] = []
|
||||
if not text.contains("[[") and not text.contains("|"):
|
||||
|
|
@ -146,6 +148,6 @@ static func ref_targets(board: TowerBoard, text: String) -> Array[String]:
|
|||
var res := func(name: String) -> String: return Roller.resolve(board, name)
|
||||
for name in TextExpander.references(text, res):
|
||||
var id := Roller.resolve(board, name)
|
||||
if id != "" and not out.has(id):
|
||||
if id != "" and not SpreadLinks.is_link(id) and not out.has(id):
|
||||
out.append(id)
|
||||
return out
|
||||
|
|
|
|||
214
core/roller.gd
214
core/roller.gd
|
|
@ -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
|
||||
|
|
@ -67,16 +69,25 @@ static func new_context(board: TowerBoard, rng: RandomNumberGenerator, persisten
|
|||
ctx.set_meta("decks", decks)
|
||||
# A weak reference, so the context doesn't keep itself alive through its hooks.
|
||||
var wr: WeakRef = weakref(ctx)
|
||||
# The hooks use the context's spread, which is another spread's while a
|
||||
# [[Spread::Card]] link rolls (SpreadLinks).
|
||||
ctx.resolve_table = func(name_or_id: String) -> String:
|
||||
return resolve(board, name_or_id)
|
||||
var c: RollContext = wr.get_ref()
|
||||
return resolve(c.board if c and c.board else board, name_or_id)
|
||||
ctx.roll_table = func(id: String, depth: int) -> Dictionary:
|
||||
var c: RollContext = wr.get_ref()
|
||||
return {} if c == null else _chain_sync(board, id, depth, c)
|
||||
if c == null:
|
||||
return {}
|
||||
if SpreadLinks.is_link(id):
|
||||
return SpreadLinks.roll_sync(id, depth, c)
|
||||
return _chain_sync(c.board if c.board else board, id, depth, c)
|
||||
ctx.roll_table_async = func(id: String, depth: int) -> Dictionary:
|
||||
var c: RollContext = wr.get_ref()
|
||||
if c == null:
|
||||
return {}
|
||||
return await _chain(board, id, depth, c)
|
||||
if SpreadLinks.is_link(id):
|
||||
return await SpreadLinks.roll_async(id, depth, c)
|
||||
return await _chain(c.board if c.board else board, id, depth, c)
|
||||
return ctx
|
||||
|
||||
|
||||
|
|
@ -84,6 +95,8 @@ static func new_context(board: TowerBoard, rng: RandomNumberGenerator, persisten
|
|||
## case-insensitively without BBCode. "" if there's no such table.
|
||||
static func resolve(board: TowerBoard, name_or_id: String) -> String:
|
||||
var key := name_or_id.strip_edges()
|
||||
if SpreadLinks.is_link(key):
|
||||
return SpreadLinks.resolve(key)
|
||||
if board.get_table(key) != null:
|
||||
return key
|
||||
var want := RollContext.normalize_name(key)
|
||||
|
|
@ -136,22 +149,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 +190,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 +198,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 +211,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:
|
||||
|
|
@ -252,6 +227,8 @@ static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack:
|
|||
if not _take_action(f, t, ctx):
|
||||
return
|
||||
RollPipes.bind_inputs(t, f, ctx, stack)
|
||||
if not await RollCosts.card_gate(board, t, f, ctx):
|
||||
return
|
||||
if t.entries.is_empty():
|
||||
_attach(f, _stop(t, "This table has no results"), ctx)
|
||||
return
|
||||
|
|
@ -331,127 +308,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
|
||||
|
|
|
|||
153
core/rule_tokens.gd
Normal file
153
core/rule_tokens.gd
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
class_name RuleTokens
|
||||
extends RefCounted
|
||||
## Splits rule text into small pieces ("tokens") such as @luck, >=, 8 or
|
||||
## "Aslan", so the Builder can read conditions and effects as rows. Also
|
||||
## holds the small text helpers that go with it: is a character part of a
|
||||
## word, dice words like 2d6, and quoting text. Builder delegates here.
|
||||
|
||||
static var _dice_re: RegEx = null
|
||||
static var _num_re: RegEx = null
|
||||
|
||||
|
||||
## Splits a rule into tokens: Array of {"t": type, "s": text}, or [] when it
|
||||
## can't (an unclosed quote or bracket, a stray character, "2x"). Types:
|
||||
## "var" (@name, lowercased, or @[expr] as written), "prefix" (@name_*),
|
||||
## "name" (a chain name or function), "num", "dice" (2d6, D3, 2D), "str" (a
|
||||
## quoted text, quotes included), "op" (+ - * / % ( ) , = == != < <= > >=),
|
||||
## "kw" (and, or, not; && || ! are read as these).
|
||||
static func tokenize(src: String) -> Array:
|
||||
var out: Array = []
|
||||
var i := 0
|
||||
var src_len := src.length()
|
||||
while i < src_len:
|
||||
var ch := src[i]
|
||||
if ch == " " or ch == "\t" or ch == "\n":
|
||||
i += 1
|
||||
continue
|
||||
if ch == "\"" or ch == "'":
|
||||
var j := i + 1
|
||||
while j < src_len and src[j] != ch:
|
||||
if src[j] == "\\":
|
||||
j += 1
|
||||
j += 1
|
||||
if j >= src_len:
|
||||
return []
|
||||
out.append({"t": "str", "s": src.substr(i, j - i + 1)})
|
||||
i = j + 1
|
||||
continue
|
||||
if ch == "@":
|
||||
if i + 1 < src_len and src[i + 1] == "[":
|
||||
var close := Expr.bracket_end(src, i + 1)
|
||||
if close < 0:
|
||||
return []
|
||||
out.append({"t": "var", "s": "@[%s]" % src.substr(i + 2, close - i - 2).strip_edges()})
|
||||
i = close + 1
|
||||
continue
|
||||
var name_end := i + 1
|
||||
while name_end < src_len and is_word(src[name_end]):
|
||||
name_end += 1
|
||||
var name := src.substr(i + 1, name_end - i - 1).to_lower()
|
||||
if name == "" or name[0].is_valid_int():
|
||||
return []
|
||||
if name_end < src_len and src[name_end] == "*":
|
||||
out.append({"t": "prefix", "s": "@%s*" % name})
|
||||
i = name_end + 1
|
||||
else:
|
||||
out.append({"t": "var", "s": "@" + name})
|
||||
i = name_end
|
||||
continue
|
||||
if is_word(ch):
|
||||
var word_end := i
|
||||
while word_end < src_len and (is_word(src[word_end]) or (src[word_end] == "." and word_end + 1 < src_len and src[word_end + 1].is_valid_int())):
|
||||
word_end += 1
|
||||
var word := src.substr(i, word_end - i)
|
||||
i = word_end
|
||||
if _num().search(word) != null:
|
||||
out.append({"t": "num", "s": word})
|
||||
elif dice_regex().search(word) != null and word.length() > 1:
|
||||
out.append({"t": "dice", "s": word})
|
||||
elif word[0].is_valid_int():
|
||||
return []
|
||||
elif ["and", "or", "not"].has(word.to_lower()) and word == word.to_lower():
|
||||
out.append({"t": "kw", "s": word})
|
||||
else:
|
||||
out.append({"t": "name", "s": word})
|
||||
continue
|
||||
var two := src.substr(i, 2)
|
||||
if two in [">=", "<=", "!=", "=="]:
|
||||
out.append({"t": "op", "s": two})
|
||||
i += 2
|
||||
continue
|
||||
if two == "&&" or two == "||":
|
||||
out.append({"t": "kw", "s": "and" if two == "&&" else "or"})
|
||||
i += 2
|
||||
continue
|
||||
if ch == "!":
|
||||
out.append({"t": "kw", "s": "not"})
|
||||
i += 1
|
||||
continue
|
||||
if ch in ["+", "-", "*", "/", "%", "(", ")", ",", "=", "<", ">"]:
|
||||
out.append({"t": "op", "s": ch})
|
||||
i += 1
|
||||
continue
|
||||
return []
|
||||
return out
|
||||
|
||||
|
||||
## True when `ch` can be part of a name or number: a letter, a digit or "_".
|
||||
static func is_word(ch: String) -> bool:
|
||||
return ch == "_" or ch.is_valid_int() or (ch.to_lower() != ch.to_upper())
|
||||
|
||||
|
||||
## The pattern for a dice word: an optional count, d or D, optional sides.
|
||||
static func dice_regex() -> RegEx:
|
||||
if _dice_re == null:
|
||||
_dice_re = RegEx.create_from_string("^(\\d*)[dD](\\d*)$")
|
||||
return _dice_re
|
||||
|
||||
|
||||
static func _num() -> RegEx:
|
||||
if _num_re == null:
|
||||
_num_re = RegEx.create_from_string("^\\d+(\\.\\d+)?$")
|
||||
return _num_re
|
||||
|
||||
|
||||
## [count, sides] of a dice token ("2d6" -> [2, 6], "D3" -> [1, 3], "2D" ->
|
||||
## [2, 6]), or [].
|
||||
static func dice_parts(word: String) -> Array:
|
||||
var found := dice_regex().search(word)
|
||||
if found == null or word.length() < 2:
|
||||
return []
|
||||
var count_text := found.get_string(1)
|
||||
var sides_text := found.get_string(2)
|
||||
return [int(count_text) if count_text != "" else 1, int(sides_text) if sides_text != "" else 6]
|
||||
|
||||
|
||||
## True when `text` is one quoted text literal ("Aslan" or 'Aslan').
|
||||
static func is_text_literal(text: String) -> bool:
|
||||
var toks := tokenize(text.strip_edges())
|
||||
return toks.size() == 1 and toks[0]["t"] == "str"
|
||||
|
||||
|
||||
## A quoted literal's text: "\"Aslan\"" -> "Aslan" (\" and \\ unescaped).
|
||||
## Anything else comes back as it is.
|
||||
static func unquote(text: String) -> String:
|
||||
text = text.strip_edges()
|
||||
if text.length() < 2 or not ((text.begins_with("\"") and text.ends_with("\"")) or (text.begins_with("'") and text.ends_with("'"))):
|
||||
return text
|
||||
var inner := text.substr(1, text.length() - 2)
|
||||
var out := ""
|
||||
var pos := 0
|
||||
while pos < inner.length():
|
||||
var ch := inner[pos]
|
||||
if ch == "\\" and pos + 1 < inner.length():
|
||||
pos += 1
|
||||
ch = inner[pos]
|
||||
out += ch
|
||||
pos += 1
|
||||
return out
|
||||
|
||||
|
||||
## Text as a double-quoted literal, escaping \ and ".
|
||||
static func quote(text: String) -> String:
|
||||
return "\"%s\"" % text.replace("\\", "\\\\").replace("\"", "\\\"")
|
||||
1
core/rule_tokens.gd.uid
Normal file
1
core/rule_tokens.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://0hqt0mqmpit4
|
||||
91
core/spread_links.gd
Normal file
91
core/spread_links.gd
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
class_name SpreadLinks
|
||||
extends RefCounted
|
||||
## Rolling a card from another spread: [[Treasure::Loot]] in result text rolls
|
||||
## the Loot card of the spread called Treasure and puts its result in the text
|
||||
## (with its own threads and references, which resolve inside Treasure). The
|
||||
## roll uses this spread's values, so the other spread's changes (@gold += 10)
|
||||
## land here; its decks are not kept between rolls.
|
||||
##
|
||||
## A linked card's id is "<spread id>::<card id>". The app sets `loader` (a
|
||||
## spread's id or name -> TowerBoard or null); without it, links are missing.
|
||||
|
||||
const SEP := "::"
|
||||
|
||||
## func(spread_id_or_name: String) -> TowerBoard (or null). Set by Main.
|
||||
static var loader: Callable = Callable()
|
||||
|
||||
|
||||
static func is_link(name_or_id: String) -> bool:
|
||||
return name_or_id.contains(SEP)
|
||||
|
||||
|
||||
## "Treasure::Loot" -> the linked id "treasure::t12", or "" when the spread or
|
||||
## the card can't be found.
|
||||
static func resolve(name_or_id: String) -> String:
|
||||
var parts := name_or_id.split(SEP, true, 1)
|
||||
if parts.size() != 2:
|
||||
return ""
|
||||
var other := load_board(parts[0])
|
||||
if other == null:
|
||||
return ""
|
||||
var card_id := Roller.resolve(other, parts[1])
|
||||
return "" if card_id == "" else "%s%s%s" % [other.id, SEP, card_id]
|
||||
|
||||
|
||||
static func load_board(spread: String) -> TowerBoard:
|
||||
if not loader.is_valid() or spread.strip_edges() == "":
|
||||
return null
|
||||
var found: Variant = loader.call(spread.strip_edges())
|
||||
return found if found is TowerBoard else null
|
||||
|
||||
|
||||
## The card a linked id names, or null.
|
||||
static func card(linked_id: String) -> RollTable:
|
||||
var parts := linked_id.split(SEP, true, 1)
|
||||
var other := load_board(parts[0]) if parts.size() == 2 else null
|
||||
return other.get_table(parts[1]) if other else null
|
||||
|
||||
|
||||
## Rolls a linked card inside its own spread: while it runs, the context's
|
||||
## spread (and its decks) are the other spread's; then they're put back.
|
||||
static func roll_async(linked_id: String, depth: int, ctx: RollContext) -> Dictionary:
|
||||
var visit := _enter(linked_id, ctx)
|
||||
if visit.is_empty():
|
||||
return {}
|
||||
var node: Dictionary = await Roller._chain(visit["board"], visit["card"], depth, ctx)
|
||||
return _leave(visit, node, ctx)
|
||||
|
||||
|
||||
## The same without waiting (headless rolls: tests, Test spread).
|
||||
static func roll_sync(linked_id: String, depth: int, ctx: RollContext) -> Dictionary:
|
||||
var visit := _enter(linked_id, ctx)
|
||||
if visit.is_empty():
|
||||
return {}
|
||||
var node: Dictionary = Roller._chain_sync(visit["board"], visit["card"], depth, ctx)
|
||||
return _leave(visit, node, ctx)
|
||||
|
||||
|
||||
static func _enter(linked_id: String, ctx: RollContext) -> Dictionary:
|
||||
var parts := linked_id.split(SEP, true, 1)
|
||||
var other := load_board(parts[0]) if parts.size() == 2 else null
|
||||
if other == null or other.get_table(parts[1]) == null:
|
||||
return {}
|
||||
var visit := {"board": other, "card": parts[1], "home": ctx.board, "decks": ctx.get_meta("decks", {})}
|
||||
ctx.board = other
|
||||
ctx.set_meta("decks", {})
|
||||
ctx.forget_declarations()
|
||||
return visit
|
||||
|
||||
|
||||
static func _leave(visit: Dictionary, node: Dictionary, ctx: RollContext) -> Dictionary:
|
||||
ctx.board = visit["home"]
|
||||
ctx.set_meta("decks", visit["decks"])
|
||||
ctx.forget_declarations()
|
||||
# Every node from the other spread is marked, so this spread's cards with
|
||||
# the same ids aren't lit or animated for them.
|
||||
var stack: Array = [] if node.is_empty() else [node]
|
||||
while not stack.is_empty():
|
||||
var each: Dictionary = stack.pop_back()
|
||||
each["spread"] = (visit["board"] as TowerBoard).name
|
||||
stack.append_array(each.get("children", []))
|
||||
return node
|
||||
1
core/spread_links.gd.uid
Normal file
1
core/spread_links.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bdj04p1iyb8vd
|
||||
|
|
@ -9,7 +9,7 @@ extends RefCounted
|
|||
## Decks are opaque Dictionaries (whatever DeckState.to_dict() produces).
|
||||
|
||||
const FORMAT_VERSION := 1
|
||||
const HISTORY_CAP := 50
|
||||
const HISTORY_CAP := 200
|
||||
|
||||
## Folder that contains state/. Default user://.
|
||||
var root: String
|
||||
|
|
|
|||
|
|
@ -45,6 +45,9 @@ var pipe_combine: Dictionary = {}
|
|||
## target table id -> true: the roll waits before following this thread until
|
||||
## the player continues (Roller.OP_PAUSE). Missing = no pause.
|
||||
var pipe_pause: Dictionary = {}
|
||||
## target table id -> true: when the thread rolls its card more than once,
|
||||
## each roll skips results already rolled (no repeats). Missing = repeats ok.
|
||||
var pipe_distinct: Dictionary = {}
|
||||
## target table id -> dice to roll the target with instead of its own
|
||||
## ("3d10+70"; a ranged target only). Missing = the card's own dice.
|
||||
var pipe_dice: Dictionary = {}
|
||||
|
|
@ -273,138 +276,20 @@ func remove_pipe(target: String) -> void:
|
|||
pipe_color.erase(target)
|
||||
pipe_combine.erase(target)
|
||||
pipe_pause.erase(target)
|
||||
pipe_distinct.erase(target)
|
||||
pipe_dice.erase(target)
|
||||
pipe_reroll.erase(target)
|
||||
|
||||
|
||||
## The entry as a Dictionary for the board file (TableEntryIO).
|
||||
func to_dict() -> Dictionary:
|
||||
var d := {"id": id, "text": text}
|
||||
if details != "":
|
||||
d["details"] = details
|
||||
if weight != 1:
|
||||
d["weight"] = weight
|
||||
if effects != "":
|
||||
d["effects"] = effects
|
||||
if when.strip_edges() != "":
|
||||
d["when"] = when.strip_edges()
|
||||
if show_if.strip_edges() != "":
|
||||
d["show_if"] = show_if.strip_edges()
|
||||
if not pipes.is_empty():
|
||||
var list: Array = []
|
||||
for p in pipes:
|
||||
var expr := count_expr(p)
|
||||
var n := count_for(p)
|
||||
var s := save_for(p)
|
||||
var w := when_for(p)
|
||||
var other := is_otherwise(p)
|
||||
var wv: Variant = pipe_with.get(p)
|
||||
var col := str(pipe_color.get(p, ""))
|
||||
var comb := combine_for(p)
|
||||
var paused := pipe_pause.has(p)
|
||||
var dice := dice_for(p)
|
||||
var again := reroll_for(p)
|
||||
if expr == "" and n == 1 and s == "" and w == "" and not other and wv == null and col == "" and comb == "all" and not paused and dice == "" and again.is_empty():
|
||||
list.append(p)
|
||||
else:
|
||||
var po := {"table": p}
|
||||
if expr != "":
|
||||
po["count"] = expr
|
||||
elif n != 1:
|
||||
po["count"] = n
|
||||
if s != "":
|
||||
po["save_as"] = s
|
||||
if w != "":
|
||||
po["when"] = w
|
||||
elif other:
|
||||
po["otherwise"] = true
|
||||
if wv is Dictionary and not (wv as Dictionary).is_empty():
|
||||
po["with"] = (wv as Dictionary).duplicate()
|
||||
if col != "":
|
||||
po["color"] = col
|
||||
if comb != "all":
|
||||
po["combine"] = comb
|
||||
if paused:
|
||||
po["pause"] = true
|
||||
if dice != "":
|
||||
po["dice"] = dice
|
||||
if not again.is_empty():
|
||||
po["reroll"] = again
|
||||
list.append(po)
|
||||
d["pipes"] = list
|
||||
if has_range:
|
||||
d["range"] = [range_lo, range_hi]
|
||||
if not cells.is_empty():
|
||||
d["cells"] = cells.duplicate()
|
||||
if not repeat.is_empty():
|
||||
d["repeat"] = repeat.duplicate(true)
|
||||
if page != "":
|
||||
d["page"] = page
|
||||
if image != "":
|
||||
d["image"] = image
|
||||
if cost_value.strip_edges() != "":
|
||||
d["cost"] = {"value": cost_value.strip_edges(), "amount": cost_amount.strip_edges()}
|
||||
return d
|
||||
return TableEntryIO.to_dict(self)
|
||||
|
||||
|
||||
## A "repeat" value from JSON or the UI: {count >= 1, reroll?: [ids]}, or {}.
|
||||
static func clean_repeat(v: Variant) -> Dictionary:
|
||||
if not (v is Dictionary):
|
||||
return {}
|
||||
var n := int(JsonIO._num((v as Dictionary).get("count", 2), 2))
|
||||
if n < 1:
|
||||
return {}
|
||||
var out := {"count": n}
|
||||
var ids: Array[String] = []
|
||||
if (v as Dictionary).get("reroll") is Array:
|
||||
for x: Variant in v["reroll"]:
|
||||
if str(x) != "" and not ids.has(str(x)):
|
||||
ids.append(str(x))
|
||||
if not ids.is_empty():
|
||||
out["reroll"] = ids
|
||||
return out
|
||||
static func clean_repeat(value: Variant) -> Dictionary:
|
||||
return TableEntryIO.clean_repeat(value)
|
||||
|
||||
|
||||
static func from_dict(d: Dictionary) -> TableEntry:
|
||||
var e := TableEntry.new(str(d.get("id", "")), str(d.get("text", "")))
|
||||
e.details = str(d.get("details", ""))
|
||||
e.weight = maxi(0, int(d.get("weight", 1)))
|
||||
e.effects = str(d.get("effects", ""))
|
||||
e.page = str(d.get("page", ""))
|
||||
e.image = str(d.get("image", ""))
|
||||
var cost: Variant = d.get("cost")
|
||||
if cost is Dictionary:
|
||||
e.cost_value = str(cost.get("value", ""))
|
||||
e.cost_amount = str(cost.get("amount", ""))
|
||||
e.when = str(d.get("when", "")).strip_edges() if d.get("when") != null else ""
|
||||
e.show_if = str(d.get("show_if", "")).strip_edges() if d.get("show_if") != null else ""
|
||||
for p: Variant in d.get("pipes", []):
|
||||
if p is Dictionary:
|
||||
var target := str(p.get("table", ""))
|
||||
if target != "":
|
||||
var c: Variant = p.get("count", 1)
|
||||
e.add_pipe(target, c if c is String else int(c), str(p.get("save_as", "")))
|
||||
e.set_pipe_when(target, str(p.get("when", "")) if p.get("when") != null else "")
|
||||
e.set_pipe_otherwise(target, bool(p.get("otherwise", false)))
|
||||
if p.get("with") is Dictionary:
|
||||
e.set_pipe_with(target, p["with"])
|
||||
if str(p.get("color", "")) != "":
|
||||
e.pipe_color[target] = str(p["color"])
|
||||
if RollCombine.MODES.has(str(p.get("combine", "all"))) and str(p.get("combine", "all")) != "all":
|
||||
e.pipe_combine[target] = str(p["combine"])
|
||||
if bool(p.get("pause", false)):
|
||||
e.pipe_pause[target] = true
|
||||
e.set_pipe_dice(target, str(p.get("dice", "")) if p.get("dice") != null else "")
|
||||
if p.get("reroll") is Array:
|
||||
e.set_pipe_reroll(target, p["reroll"])
|
||||
elif str(p) != "":
|
||||
e.add_pipe(str(p))
|
||||
if d.get("cells") is Array:
|
||||
for c: Variant in d["cells"]:
|
||||
e.cells.append(str(c) if c != null else "")
|
||||
e.repeat = clean_repeat(d.get("repeat"))
|
||||
var r: Variant = d.get("range")
|
||||
if r is Array and r.size() == 2:
|
||||
e.has_range = true
|
||||
e.range_lo = int(r[0])
|
||||
e.range_hi = int(r[1])
|
||||
return e
|
||||
static func from_dict(data: Dictionary) -> TableEntry:
|
||||
return TableEntryIO.from_dict(data)
|
||||
|
|
|
|||
168
core/table_entry_io.gd
Normal file
168
core/table_entry_io.gd
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
class_name TableEntryIO
|
||||
extends RefCounted
|
||||
## Saves a TableEntry (one result on a card) to a plain Dictionary for the
|
||||
## board file, and builds one back from such a Dictionary. Only values that
|
||||
## differ from the defaults are written, so files stay small. TableEntry keeps
|
||||
## to_dict(), from_dict() and clean_repeat() as one-line delegators.
|
||||
|
||||
|
||||
## The entry as a Dictionary (the board file's form).
|
||||
static func to_dict(entry: TableEntry) -> Dictionary:
|
||||
var data := {"id": entry.id, "text": entry.text}
|
||||
if entry.details != "":
|
||||
data["details"] = entry.details
|
||||
if entry.weight != 1:
|
||||
data["weight"] = entry.weight
|
||||
if entry.effects != "":
|
||||
data["effects"] = entry.effects
|
||||
if entry.when.strip_edges() != "":
|
||||
data["when"] = entry.when.strip_edges()
|
||||
if entry.show_if.strip_edges() != "":
|
||||
data["show_if"] = entry.show_if.strip_edges()
|
||||
if not entry.pipes.is_empty():
|
||||
var list: Array = []
|
||||
for target in entry.pipes:
|
||||
list.append(_pipe_to_value(entry, target))
|
||||
data["pipes"] = list
|
||||
if entry.has_range:
|
||||
data["range"] = [entry.range_lo, entry.range_hi]
|
||||
if not entry.cells.is_empty():
|
||||
data["cells"] = entry.cells.duplicate()
|
||||
if not entry.repeat.is_empty():
|
||||
data["repeat"] = entry.repeat.duplicate(true)
|
||||
if entry.page != "":
|
||||
data["page"] = entry.page
|
||||
if entry.image != "":
|
||||
data["image"] = entry.image
|
||||
if entry.cost_value.strip_edges() != "":
|
||||
data["cost"] = {"value": entry.cost_value.strip_edges(), "amount": entry.cost_amount.strip_edges()}
|
||||
return data
|
||||
|
||||
|
||||
## One pipe as saved: just the target id when every option is the default,
|
||||
## else a Dictionary with "table" and the options that are set.
|
||||
static func _pipe_to_value(entry: TableEntry, target: String) -> Variant:
|
||||
var expr := entry.count_expr(target)
|
||||
var count := entry.count_for(target)
|
||||
var save_as := entry.save_for(target)
|
||||
var condition := entry.when_for(target)
|
||||
var otherwise := entry.is_otherwise(target)
|
||||
var with_values: Variant = entry.pipe_with.get(target)
|
||||
var color := str(entry.pipe_color.get(target, ""))
|
||||
var combine := entry.combine_for(target)
|
||||
var paused := entry.pipe_pause.has(target)
|
||||
var distinct := entry.pipe_distinct.has(target)
|
||||
var dice := entry.dice_for(target)
|
||||
var reroll := entry.reroll_for(target)
|
||||
if expr == "" and count == 1 and save_as == "" and condition == "" and not otherwise \
|
||||
and with_values == null and color == "" and combine == "all" and not paused and not distinct \
|
||||
and dice == "" and reroll.is_empty():
|
||||
return target
|
||||
var options := {"table": target}
|
||||
if expr != "":
|
||||
options["count"] = expr
|
||||
elif count != 1:
|
||||
options["count"] = count
|
||||
if save_as != "":
|
||||
options["save_as"] = save_as
|
||||
if condition != "":
|
||||
options["when"] = condition
|
||||
elif otherwise:
|
||||
options["otherwise"] = true
|
||||
if with_values is Dictionary and not (with_values as Dictionary).is_empty():
|
||||
options["with"] = (with_values as Dictionary).duplicate()
|
||||
if color != "":
|
||||
options["color"] = color
|
||||
if combine != "all":
|
||||
options["combine"] = combine
|
||||
if paused:
|
||||
options["pause"] = true
|
||||
if distinct:
|
||||
options["distinct"] = true
|
||||
if dice != "":
|
||||
options["dice"] = dice
|
||||
if not reroll.is_empty():
|
||||
options["reroll"] = reroll
|
||||
return options
|
||||
|
||||
|
||||
## A "repeat" value from JSON or the UI: {count >= 1, reroll?: [ids]}, or {}.
|
||||
static func clean_repeat(value: Variant) -> Dictionary:
|
||||
if not (value is Dictionary):
|
||||
return {}
|
||||
var count := int(JsonIO._num((value as Dictionary).get("count", 2), 2))
|
||||
if count < 1:
|
||||
return {}
|
||||
var out := {"count": count}
|
||||
var ids: Array[String] = []
|
||||
if (value as Dictionary).get("reroll") is Array:
|
||||
for item: Variant in value["reroll"]:
|
||||
if str(item) != "" and not ids.has(str(item)):
|
||||
ids.append(str(item))
|
||||
if not ids.is_empty():
|
||||
out["reroll"] = ids
|
||||
var columns: Array[int] = []
|
||||
if (value as Dictionary).get("columns") is Array:
|
||||
for item: Variant in value["columns"]:
|
||||
var index := int(JsonIO._num(item, -1))
|
||||
if index >= 0 and not columns.has(index):
|
||||
columns.append(index)
|
||||
if not columns.is_empty():
|
||||
columns.sort()
|
||||
out["columns"] = columns
|
||||
return out
|
||||
|
||||
|
||||
## Builds an entry from its saved Dictionary.
|
||||
static func from_dict(data: Dictionary) -> TableEntry:
|
||||
var entry := TableEntry.new(str(data.get("id", "")), str(data.get("text", "")))
|
||||
entry.details = str(data.get("details", ""))
|
||||
entry.weight = maxi(0, int(data.get("weight", 1)))
|
||||
entry.effects = str(data.get("effects", ""))
|
||||
entry.page = str(data.get("page", ""))
|
||||
entry.image = str(data.get("image", ""))
|
||||
var cost: Variant = data.get("cost")
|
||||
if cost is Dictionary:
|
||||
entry.cost_value = str(cost.get("value", ""))
|
||||
entry.cost_amount = str(cost.get("amount", ""))
|
||||
entry.when = str(data.get("when", "")).strip_edges() if data.get("when") != null else ""
|
||||
entry.show_if = str(data.get("show_if", "")).strip_edges() if data.get("show_if") != null else ""
|
||||
for pipe: Variant in data.get("pipes", []):
|
||||
if pipe is Dictionary:
|
||||
_read_pipe(entry, pipe)
|
||||
elif str(pipe) != "":
|
||||
entry.add_pipe(str(pipe))
|
||||
if data.get("cells") is Array:
|
||||
for cell: Variant in data["cells"]:
|
||||
entry.cells.append(str(cell) if cell != null else "")
|
||||
entry.repeat = clean_repeat(data.get("repeat"))
|
||||
var range_value: Variant = data.get("range")
|
||||
if range_value is Array and range_value.size() == 2:
|
||||
entry.has_range = true
|
||||
entry.range_lo = int(range_value[0])
|
||||
entry.range_hi = int(range_value[1])
|
||||
return entry
|
||||
|
||||
|
||||
## Adds one saved pipe Dictionary ({"table": id, options...}) to `entry`.
|
||||
static func _read_pipe(entry: TableEntry, pipe: Dictionary) -> void:
|
||||
var target := str(pipe.get("table", ""))
|
||||
if target == "":
|
||||
return
|
||||
var count: Variant = pipe.get("count", 1)
|
||||
entry.add_pipe(target, count if count is String else int(count), str(pipe.get("save_as", "")))
|
||||
entry.set_pipe_when(target, str(pipe.get("when", "")) if pipe.get("when") != null else "")
|
||||
entry.set_pipe_otherwise(target, bool(pipe.get("otherwise", false)))
|
||||
if pipe.get("with") is Dictionary:
|
||||
entry.set_pipe_with(target, pipe["with"])
|
||||
if str(pipe.get("color", "")) != "":
|
||||
entry.pipe_color[target] = str(pipe["color"])
|
||||
if RollCombine.MODES.has(str(pipe.get("combine", "all"))) and str(pipe.get("combine", "all")) != "all":
|
||||
entry.pipe_combine[target] = str(pipe["combine"])
|
||||
if bool(pipe.get("pause", false)):
|
||||
entry.pipe_pause[target] = true
|
||||
if bool(pipe.get("distinct", false)):
|
||||
entry.pipe_distinct[target] = true
|
||||
entry.set_pipe_dice(target, str(pipe.get("dice", "")) if pipe.get("dice") != null else "")
|
||||
if pipe.get("reroll") is Array:
|
||||
entry.set_pipe_reroll(target, pipe["reroll"])
|
||||
1
core/table_entry_io.gd.uid
Normal file
1
core/table_entry_io.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://xmi7f46bxkv1
|
||||
|
|
@ -25,8 +25,9 @@ var details: String = ""
|
|||
var members: Array[String] = []
|
||||
## The group this one sits inside ("" = on the spread itself).
|
||||
var parent: String = ""
|
||||
## "#rrggbb", or "" for the theme's group colour (Style.GROUP). Marks the
|
||||
## frame's border and each member card's top-right corner.
|
||||
## "#rrggbb", or "" for the default (GroupMark.DEFAULT_COLOR, the same in
|
||||
## every theme). Marks the frame's border and each member card's top-right
|
||||
## corner, and a collapsed group's own corner.
|
||||
var color: String = ""
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -13,6 +13,8 @@ static var _salt: String = ""
|
|||
var id: String = ""
|
||||
## Display name; free to change.
|
||||
var name: String = ""
|
||||
## The folder it's listed under in the spread switcher ("" = none).
|
||||
var folder: String = ""
|
||||
var tables: Array[RollTable] = []
|
||||
## Group cards (frames around blocks of tables). Optional; a table is in at
|
||||
## most one group. See TableGroup.
|
||||
|
|
@ -164,204 +166,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:
|
||||
|
|
@ -369,6 +203,8 @@ func to_dict() -> Dictionary:
|
|||
for t in tables:
|
||||
list.append(t.to_dict())
|
||||
var d := {"format_version": FORMAT_VERSION, "id": id, "name": name, "tables": list}
|
||||
if folder != "":
|
||||
d["folder"] = folder
|
||||
if not groups.is_empty():
|
||||
var gl: Array = []
|
||||
for g in groups:
|
||||
|
|
@ -421,35 +257,13 @@ func load_dict(src: Dictionary) -> bool:
|
|||
id = str(d["id"])
|
||||
if str(d.get("name", "")) != "":
|
||||
name = str(d["name"])
|
||||
if d.has("folder"):
|
||||
folder = str(d["folder"]).strip_edges()
|
||||
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:
|
||||
|
|
|
|||
|
|
@ -195,9 +195,41 @@ Format spec: `docs/THEMES.md`. Built-in themes: `themes/<id>/theme.gd` (`const D
|
|||
Keep File importer so its text is exported).
|
||||
- **Background:** `ui/board_backdrop.gd` (gradient, scene, tile; old dots/stars).
|
||||
- **Sound:** `ui/sound_board.gd` (`Main.sound`; roll / card_turn / thread / click / ambient;
|
||||
View ▾ → Sound levels; setting `sound_volume`).
|
||||
☰ / right-click menu → Sound levels, not in the top bar's View ▾; setting `sound_volume`).
|
||||
- **Generators:** `tools/theme_art/` (SVG art), `tools/theme_sounds/` (OGG), `tools/theme_defs/`.
|
||||
|
||||
## 3e. Size audit batch 1 (2026-11-14): helpers split out
|
||||
Each original file keeps one-line delegators, so callers are unchanged.
|
||||
- `inspector_card` → `inspector_choice`, `inspector_router`, `inspector_collection` (Ledger section);
|
||||
`group_card` → `group_card_compact` (the collapsed group card).
|
||||
- `main_cli` → `main_cli_build` (group/template/inspector flags), `main_cli_perf` (`--perf`);
|
||||
`pipe_layer` → `pipe_batch` (unlit thread canvas items), `pipe_geometry` (curve maths);
|
||||
`main_rolling` → `main_rolling_seed` (session start), `main_rolling_copy` (copy as text).
|
||||
- `expr` → `expr_rewriter` (user syntax → Godot Expression); `builder` → `rule_tokens` (tokenizer,
|
||||
shared with Expr), `builder_values` (`known_values`); `board_tester` → `board_checks`
|
||||
(static checks), `board_report_text`.
|
||||
- `roll_table` → `roll_table_factory` (`create`), more in `roll_table_io`; `roller` → `roll_nodes`
|
||||
(stop/attach/why/log), `roll_live` (starting values, live displays), more in `roll_pipes` and
|
||||
`roll_choice`; `tower_board` → `board_groups` (nesting, membership), `board_file_io` (migrate,
|
||||
atomic write).
|
||||
- Batch 2: `main` (tightened) and `main_groups` → `main_card_drag`; `result_tray` → `tray_controls`,
|
||||
`tray_why`; `inspector` → `inspector_frame`; `table_entry` → `table_entry_io` (to/from dict);
|
||||
`describe` → `describe_labels`, `describe_dice`; `table_card` → `table_card_rebuild`;
|
||||
`table_card_header` → `table_card_go_button`; `table_card_rows` → `table_card_row_text`,
|
||||
`table_card_odds`. No script is over 400 lines now (largest: test_board_dialog, board_view, 398).
|
||||
|
||||
## 3f. Modules added 2026-11-14 (playtest fixes)
|
||||
- **Ledger:** `core/ledger_members.gd` (entries on the card: clean, adopt older spreads, sync with
|
||||
saved values), `ui/ledger_edits.gd` (add/rename/start/remove with undo), `ui/ledger_card_rows.gd`
|
||||
(Build-mode fields on the card).
|
||||
- **Rolling:** `ui/main_rolling_show.gd` (show a roll at once), `RollCosts.card_gate` (card costs),
|
||||
`RollPauses` pop-up, `SpreadLinks` (`core/spread_links.gd`, [[Spread::Card]]) with
|
||||
`ui/spread_loader.gd` and `ui/spread_link_dialog.gd`.
|
||||
- **Interface:** `ui/delete_key.gd`, `ui/sound_panel.gd`, `ui/format_menu.gd` (right-click Format),
|
||||
`ui/text_effects/` (sparkle, shimmer, flash RichTextEffects; `RichText.install_effects`),
|
||||
`ui/colour_dialog.gd` ("Any colour…").
|
||||
- **Timing:** `tests/perf_roll.gd` (not in the suite).
|
||||
|
||||
## 4. Data and storage
|
||||
- **Collections:** `user://collections/<id>.json`, format_version 2 (`{format_version, id,
|
||||
name, tables, groups?}`). On Linux that's `~/.local/share/godot/app_userdata/TableTower/`.
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
# Table Tarot (repo: TableTower) — Status and Plan
|
||||
|
||||
**Engine:** Godot 4.7.2 (GDScript) · **Started:** 2026-11-08 · **Last updated:** 2026-11-11 (theme files, 18 new
|
||||
built-in themes, Morgan Fortuna; merged to `main` and pushed)
|
||||
**Engine:** Godot 4.7.2 (GDScript) · **Started:** 2026-11-08 · **Last updated:** 2026-11-14 (playtest fixes merged to
|
||||
`main` and pushed)
|
||||
|
||||
The short page to read at the start of every session. Everything else is read only when needed:
|
||||
- `docs/ARCHITECTURE.md`: feature summary, file map (§3b lists the 2026-11-10 modules), storage, known gaps.
|
||||
|
|
@ -74,8 +74,7 @@ Card, Result, Change, Reset, Dice wording rules: `docs/HISTORY.md` §6 "Terminol
|
|||
- The Collection card kind is called **Ledger** in the UI "for the time being". The spread
|
||||
switcher's tooltip says "Spreads".
|
||||
- Reroll rule settled by the thread option "Roll again if it comes up".
|
||||
- **Hand testing:** the user tests by hand as they go but hasn't done a full pass; a comprehensive
|
||||
playtest with a checklist is planned (they'll do it later; offer a checklist when asked).
|
||||
- **Hand testing:** full pass done 2026-11-14 (see §4 "Playtest findings").
|
||||
|
||||
- **Theme tiers 1–2 built and merged to `main` (2026-11-11):** theme folders,
|
||||
Morgan recolouring by role, background scene + tile, frame sets (3-stop gradient map), picture
|
||||
|
|
@ -83,14 +82,18 @@ Card, Result, Change, Reset, Dice wording rules: `docs/HISTORY.md` §6 "Terminol
|
|||
themes from the mockup (Vaporwave … Terminal) with stand-in art and synthesised sounds; 10 new OFL
|
||||
fonts. `--theme=<id>` CLI flag. Then (same day) Web 1.0 + the 8 suggested themes (Case File, Eldritch
|
||||
Archive, Comic Panel, Brass & Gears, Chrome Street, Star Chart, Cartographer, Storybook): 18 new
|
||||
built-ins in all, 20 bundled-font additions. Placeholder list: Theme Art Guide, "Placeholder art". Not hand-tested yet. Map: ARCHITECTURE §3d; format: THEMES.md.
|
||||
built-ins in all, 20 bundled-font additions. Placeholder list: Theme Art Guide, "Placeholder art". Hand-tested 2026-11-14. Map: ARCHITECTURE §3d; format: THEMES.md.
|
||||
Known gaps vs mockup: corner ornaments show on all four corners; no card drop shadows; Terminal
|
||||
has no scanlines. `pipe_layer.gd` is now 456 lines (size audit).
|
||||
|
||||
**Next, likely:** fix the Morgan colour bug (§4 "Theme editor"); then the user may ask for the
|
||||
theme editor's live preview and file pickers, or the Web 1.0 slots (panel picture, button style).
|
||||
Older items: the user's hand test of Stage II and the new column options; the roll hitch (§4); a
|
||||
size audit (§4: `pipe_layer.gd` is now 456 lines); a hand-testing checklist.
|
||||
**2026-11-14: the user did the full hand playtest** (all 20 themes, every feature); all 7 steps
|
||||
of §4 "Playtest findings" are built, **merged to `main` and pushed** (46 suites pass). The user
|
||||
hand-tested almost all of it: works. **Not hand-tested yet: `[[Spread::Card]]` links** (they were
|
||||
unsure where to type one: in a result's text, or with "+ Roll a card from another spread…" under
|
||||
the Text field when a result is selected in Build). Placeholder *writing* (help, demos, sample,
|
||||
templates) is on the Theme Art Guide checklist.
|
||||
|
||||
**Next, likely:** the user tries spread links; new playtest reports. Older open items in §4.
|
||||
|
||||
## 3b. Theme slots plan (2026-11-11, user-approved order)
|
||||
Mockups: "Morgan's Wardrobe" artifact (https://claude.ai/code/artifact/136b4ce8-1ef7-47ca-a39a-a75eb34d64b7):
|
||||
|
|
@ -116,37 +119,67 @@ that works on any theme (solid background, stronger text, thicker borders, no ef
|
|||
- Repo privacy on Forgejo: needs Niles/sock's username and a token from the user.
|
||||
|
||||
**Theme editor (user, 2026-11-11)**
|
||||
- **Bug, open (next to fix):** in the user's real app, changing Morgan's colours in View ▾ → Theme…,
|
||||
pressing "Use theme" and saving the copy (the "Save theme" box did appear) left the top-left
|
||||
Morgan unchanged. The copy WAS saved (user://themes/ written 15:10:09; the user deleted it
|
||||
after). Automated runs of the same path (tests/scratch harness: dialog swatch → _use → Save
|
||||
button) recolour fine, so suspect something only the real reload hits: e.g. `Main._ready`/top bar
|
||||
reading a different theme dict than `ThemeStore.current`, the MascotArt cache, or the editor
|
||||
(Godot editor run vs. Keep File import of `fortune_teller_logo.svg`). Next step: a real windowed
|
||||
run that saves (no --sample, so ask the user first; it writes to their user://), with a print of
|
||||
`ThemeStore.current.mascot_colors` in `MainTopBar._logo`. Morgan only shows in the top bar.
|
||||
- **Morgan colour bug: fixed** (user confirmed 2026-11-14 with a fully custom theme).
|
||||
- **Later:** a live preview of Morgan (and the theme) in the editor.
|
||||
- **Later:** file pickers in the editor for a theme's pictures (tile, scene, frame, thread,
|
||||
mascot) and sounds; today a user theme can only name files by editing its JSON.
|
||||
- **Mockup only:** Web 1.0 theme (marble tile, wood panels, bevelled window cards) in the
|
||||
Wardrobe; it needs two new slots, a panel tile and a button style (nine-patch). Not started.
|
||||
|
||||
**Playtest findings (2026-11-14), proposed order; the user may reorder**
|
||||
1. ~~Size audit batch 2~~ done.
|
||||
2. ~~Data bugs~~ done 2026-11-14 (Ledger `members` on the card, group colour on import,
|
||||
grouping over open groups nests them, Add to list fixes + Allow repeats, combine rows per
|
||||
column). Original notes: Ledger entries live only in local state (`state.json` variables), so copies,
|
||||
exports and imports lose them, and the spread can't add entries: store them on the card.
|
||||
JSON import drops group `color`. Making a group over open groups steals their cards (leaves
|
||||
empty groups); nesting works only with collapsed groups. "Add to list": can't pick an
|
||||
existing value, only numbers, needs "unless already there" vs "every time, in order".
|
||||
Rerolls apply to all columns (make per-column, all-columns optional).
|
||||
3. ~~Roll hitch~~ fixed (see "Known, not urgent").
|
||||
4. ~~Themes~~ done 2026-11-14 (fixed-corner layer redraws on resize; built-in pictures get
|
||||
mipmaps; group mark = filled corner tab, default blue #3a7bd5 in every theme, on collapsed groups
|
||||
too, "Any colour…" picker; IM Fell never fake-bold; Gothic/Cartographer titles IM Fell SC /
|
||||
Alegreya; List view hover; Gothic scene arch removed). Original notes: frame corners jump on resize and float off the bottom (10 themes; one shared bug);
|
||||
Terminal edges and group corners flicker when zoomed out; group corners too hard to see in
|
||||
most themes (make bigger, outlined; one fixed default colour across themes; full colour
|
||||
picker; mark collapsed groups); Cartographer chosen-result text glitchy; Tarot List view hover
|
||||
unreadable; Gothic/Cartographer title fonts; red patch in Gothic's background.
|
||||
5. ~~Roll features~~ done 2026-11-14 (card costs + Pay/Don't pay; pause pop-up and animation
|
||||
up to and after it; batches in Earlier, one sound, Earlier 30 / saved 200; rerolls flicker
|
||||
"rolled again"; No repeats on threads; plain-table modifier moves rows; Only if on results;
|
||||
List view rolls fast). Original notes: "costs to roll" on any rolling card (threads pause to ask); pause as a pop-up
|
||||
that waits between card animations; batch rolls into history with one sound; a result
|
||||
history; visible in-between rolls for roll again/rerolls; "roll N different results, then
|
||||
pick"; "move the result up/down N rows" on standard tables (pick by weight, then shift,
|
||||
clamp); "only if" on roll results (reuse `show_if`); no animation when rolling from List view.
|
||||
6. ~~UI~~ done 2026-11-14 (SoundPanel slider; Delete hidden on built-ins; Delete key = DeleteKey,
|
||||
View ▾ Ask before deleting; FormatMenu right-click + ui/text_effects sparkle/shimmer/flash;
|
||||
spread folders + tooltip; Show less; Book reload after undo; dice hint; export names).
|
||||
Original notes: sound slider (default = Quiet) also in View ▾; hide Delete for built-in themes; Delete
|
||||
key + "Are you sure?" + a "Confirm delete" setting; BBCode buttons and right-click formatting
|
||||
(wave, tornado, shake, rainbow, pulse, fade + custom RichTextEffects such as glow, sparkle);
|
||||
folders in the spread switcher and a useful tooltip; collapse button on expanded large cards;
|
||||
Book editor refresh after undo; hint where "Roll it with … instead" is hidden (ranged targets
|
||||
only); call diagram exports "Export as diagram" (only JSON is a full save).
|
||||
7. ~~Spreads calling other spreads~~ done 2026-11-14: `[[Spread::Card]]` (LOGIC.md §5.3).
|
||||
|
||||
**Known, not urgent**
|
||||
- `export_presets.cfg` (and `project.godot`) hold the user's uncommitted edits. The Windows preset's
|
||||
`include_filter` now matches Linux (help + templates; verified by a real Windows export
|
||||
2026-11-11) but is still uncommitted with their edits; ask before committing. Both presets also
|
||||
pack `tests/` (could add `tests/*` to the exclude filter).
|
||||
- Over ~400 lines: inspector_card (593), board_tester (505), main_cli, builder (499), expr (520),
|
||||
roller, tower_board, group_card, main_rolling (426), describe (408), inspector (407). A size
|
||||
audit is due. (roll_table was split: RollTableIO.)
|
||||
- Size audit batches 1–2 done (2026-11-14): no script over 400 lines (ARCHITECTURE §3e).
|
||||
- Small ideas from the Perilous Void spread: an empty list shows blank in a sheet (no "none"
|
||||
default); a value change that should apply when a later value is rolled (Shattered lowers
|
||||
atmosphere after Gas/Life were already decided) has no clean form.
|
||||
- **Roll hitch (user report, 2026-11-11):** before certain groups show their results, the whole
|
||||
app freezes for several frames. Not investigated yet; which groups is not pinned down. Likely
|
||||
suspects: a long pipe chain rolled in one frame (Stage II's lifeform loop with nested
|
||||
pipes), the rebuild of the result tree/thread nodes, or the why/describe text. Profile first
|
||||
(Godot profiler, or time `Roller` vs. the board redraw) before changing anything.
|
||||
- **Roll hitch: fixed 2026-11-14.** Measured on Perilous Void (headless, fast roll of "New
|
||||
World"): roll logic ~3 ms, but the app took 3.4 s after it. Causes: every relight restyled every
|
||||
row and column cell (font overrides make RichTextLabels re-measure; ~11 ms per row), and the
|
||||
Earlier tab rebuilt every history row each render (long texts, ~25 ms each, growing per roll).
|
||||
Now rows/cells skip restyling when their look is unchanged, and Earlier reuses its rows: ~240 ms
|
||||
per roll, flat (most of it is the 2–3 questions, each relighting ~70 ms first). Timing tool:
|
||||
`tests/perf_roll.gd` (SPREAD=… CARD=…; not in the suite).
|
||||
- Known gaps: ARCHITECTURE.md §7.
|
||||
|
||||
## 5. Working on it
|
||||
|
|
|
|||
|
|
@ -378,6 +378,11 @@ when the expression has modifiers.
|
|||
label members by the rest of their name ("Gun Combat") and the group by the card's name.
|
||||
`RollTable.create("variable", id, "Skills", "collection")` gives the stem `skill` (the name's
|
||||
slug without a final "s"). Its live display lists the set members.
|
||||
The card's `members` ([{name, start}], `LedgerMembers`, since 2026-11-14) are its entries, saved
|
||||
in the spread file: each gets its start the first time it's needed (like a variable's
|
||||
`initial`), and `reset` puts it back to the start. Members added by rules (another source)
|
||||
stay saved values only. Older spreads: a Ledger card with no `members` takes in the saved
|
||||
values whose source is the card when the spread opens.
|
||||
- **Results saved into a list.** A thread's or column's "save as", a choice's `save_as` and
|
||||
an inline `[[Table -> @x]]` normally replace the value. When a list card (`var_type:
|
||||
"list"`) declares it, the saved text is **added** as an item instead (each item once,
|
||||
|
|
@ -396,7 +401,7 @@ follow.
|
|||
|
||||
```
|
||||
@str = 2d6 set
|
||||
@terms += 1 add (number) · append ", item" if not present (text/list)
|
||||
@terms += 1 add (number) · append ", item" if not present (text/list; a list card with `"repeats": true` appends every time)
|
||||
@credits -= 1000 subtract (number) · remove the item (text/list)
|
||||
@age *= 2 multiply (/= divides, rounding down)
|
||||
@skill_pilot += 1 unset counts as 0, so this gives Pilot 1 or raises it
|
||||
|
|
@ -422,6 +427,12 @@ statement shows a red marker in the tray and in Build mode rather than stopping
|
|||
- `{@[expr]}` shows the variable named by `expr`, e.g. `{@[option]}`; unset shows its
|
||||
`{@name?}` marker, a bad name an error marker.
|
||||
- The existing `{@var|Table}`, `{hero}` and `[[refs]]` work as before.
|
||||
- `[[Spread::Card]]` (2026-11-14, `SpreadLinks`) rolls a card of another spread (by name or
|
||||
id, any capitals): its id is `<spread id>::<card id>`; while it rolls, `ctx.board` is that
|
||||
spread (its references resolve there; its decks aren't kept) and it reads and changes this
|
||||
spread's values. Its nodes carry `spread` (the spread's name), so the board doesn't light or
|
||||
animate same-id cards here. The app's `SpreadLoader` finds spreads (cached until the file
|
||||
changes); without a loader (`--sample`, tests) links show the missing marker.
|
||||
|
||||
### 5.4 Scales (ordered steps)
|
||||
A variable card with `var_type: "scale"` lists `steps`, lowest first (Supercold, Cold,
|
||||
|
|
|
|||
|
|
@ -52,7 +52,8 @@ than". `>= N` reads "is N or more" when it sits after a value name.
|
|||
- **Collection** is a variable card with `var_type: "collection"`. Its `var_name` is the stem
|
||||
(e.g. `skill`), its name is the label ("Skills"), and its members are the board values
|
||||
`@<stem>_<item>`.
|
||||
- On the board it shows a list editor: members with their values, plus "+ Add".
|
||||
- In Build the card shows its entries as fields (name, starting value, ×) plus "+ Add";
|
||||
Play shows the live values. Entries are saved on the card (`members`, LOGIC.md).
|
||||
- `options_from: "@skill_*"` reads "your Skills".
|
||||
- `count("skill_")` and `{@skill_*}` work as before.
|
||||
- `Describe` uses the collection to label its members.
|
||||
|
|
|
|||
|
|
@ -61,6 +61,7 @@ A card can give each result more than one part, like a row of a printed table wi
|
|||
- [b]Roll each column separately[/b] rolls again for every column, for rules like "roll 1d10 for each of Resources, Water, Atmosphere and Life". After the roll, the part each column landed on is lit.
|
||||
- [b]Save as[/b] keeps a column's text as a value, so later text and rules can use it.
|
||||
- [b]Only roll this column if[/b] skips a column unless a condition is true, such as "only roll Life if the Atmosphere is at least Thin". Columns are rolled left to right, so a condition can use what an earlier column saved.
|
||||
- A result can [b]roll that column again and combine[/b] ("roll twice and combine"). With columns rolled separately, tick [b]Only in[/b] to choose which columns it applies to; by default it applies to every column.
|
||||
- Remove a column with its ×: its text goes from every result.
|
||||
|
||||
# Threads
|
||||
|
|
@ -79,6 +80,7 @@ A thread carries the roll from a result to another card.
|
|||
## Rolling with other dice
|
||||
A thread can roll a card with numbered ranges using different dice, just this once.
|
||||
- Type the dice in [b]Roll it with … instead[/b], such as `3d10+70`. Leave it empty to use the card's own dice.
|
||||
- The field is in the thread's inspector, and only shows when the card it leads to has numbered ranges (Ranged in that card's settings). Otherwise the inspector says so.
|
||||
- Example: a World Feature card is rolled with 1d100, but "Multiple features" rolls it twice with 3d10+70, so only the higher results come up.
|
||||
|
||||
## Rolling again on some results
|
||||
|
|
@ -94,6 +96,7 @@ A ranged table can add a [b]modifier[/b] to its dice, for rules like "roll 1d20
|
|||
- [b]Ranges can go past the dice.[/b] A 1d6 table can have results for 0 or less and for 7 and up. Only a modifier reaches them, and their number's tooltip says so.
|
||||
- Totals past either end count as the end result, so the top result also catches every higher total.
|
||||
- The chances on the card follow the modifier's value as it is now.
|
||||
- A [b]plain[/b] table (no ranges) can have a modifier too. It moves the result down the list (+) or up (−) by that many rows, and the first and last results catch anything past them. Why this? says how far it moved.
|
||||
|
||||
## In the sample
|
||||
[b]Search the Ruins[/b] rolls 1d6 + Luck. With no Luck you can't reach "A tunnel caves in" or "A hidden vault". Pray at the shrine in [b]Make Camp[/b] to raise your Luck, gamble with the guards to lower it, then search again and watch the chances move. Why this? on the step names the modifier: "+1 for Luck".
|
||||
|
|
@ -126,18 +129,18 @@ An option can have [b]Show only if[/b], so it's offered only when a condition is
|
|||
|
||||
# Values and changes
|
||||
A spread can remember [b]values[/b] between rolls, such as Luck, Gold or the current town. In rules a value is written with @: `@luck`.
|
||||
- Any result can have [b]changes[/b] that happen when it comes up: [b]Add 1 to Luck[/b], [b]Subtract 3 from Gold[/b], [b]Set Town to …[/b]. Edit them in the inspector as rows, or with Edit as text.
|
||||
- Any result can have [b]changes[/b] that happen when it comes up: [b]Add 1 to Luck[/b], [b]Subtract 3 from Gold[/b], [b]Set Town to …[/b], [b]Add to list[/b] (the result's own text, unless you type another item). Edit them in the inspector as rows, or with Edit as text.
|
||||
- A [b]Variable[/b] card gives a value a name, a type and a starting value, and shows what it is now. The sample's [b]Luck[/b] card starts at 0.
|
||||
- A [b]Ledger[/b] card groups related values, such as Skills, so they can be listed and picked from together.
|
||||
- A [b]Ledger[/b] card groups related values, such as Skills, so they can be listed and picked from together. In Build mode, add and rename its entries right on the card; each entry's number is where it starts.
|
||||
- The tray's [b]Variables[/b] tab shows every value, and lets you clear or reset them. [b]Reset all…[/b] puts every value back to its start.
|
||||
|
||||
## Writing changes as text
|
||||
- `@luck += 1` adds, `@luck -= 1` subtracts and `@gold = 2d6` sets.
|
||||
- `reset @luck` goes back to the starting value. `reset @skill_*` resets every value starting with skill_.
|
||||
- Text values work as lists: `@traits += "Brave"` adds an item.
|
||||
- Text values work as lists: `@traits += "Brave"` adds an item, and `-=` takes one out. A [b]List[/b] variable adds an item only if it isn't there yet, unless you tick [b]Allow repeats[/b]; then it adds it every time, in order.
|
||||
|
||||
## Conditions
|
||||
Conditions are used by Only if threads, branches, repeats and Show only if. In plain words they read "Luck is at least 2". As text: `@luck >= 2`, `@town = "Saltmere"`, `@gold > 0 and @luck < 3`.
|
||||
Conditions are used by Only if threads, branches, repeats, Show only if on options, and [b]Can come up only if[/b] on results (a result whose condition is false is rolled again). In plain words they read "Luck is at least 2". As text: `@luck >= 2`, `@town = "Saltmere"`, `@gold > 0 and @luck < 3`.
|
||||
|
||||
# Scales
|
||||
A [b]Scale[/b] is a value that moves along steps in order, lowest first, such as a Climate that runs [b]Supercold, Cold, Temperate, Hot, Superhot[/b]. Add one with [b]+ Card ▾ → Scale (ordered steps)[/b], then list its steps, one per line, and pick the step it starts at. The card shows the current step, and the row of steps under it shows where that sits.
|
||||
|
|
@ -165,9 +168,11 @@ Use [b]Test spread[/b] to check that a spread of logic cards works. See [topic]T
|
|||
Result text can do more than plain words:
|
||||
- `[[Traveler Names]]` rolls that table and puts its result in the text.
|
||||
- `[[Traveler Names -> patron]]` also saves it as patron, so later text can say `{patron}`.
|
||||
- `[[Treasure::Loot]]` rolls the Loot card from another spread, called Treasure, so one spread can use another's tables (a dungeon calling a loot spread). Its own threads and references work there, and its changes apply to this spread's values. In the result's inspector, [b]+ Roll a card from another spread…[/b] picks the spread and card for you.
|
||||
- `{@town}` shows a value. `{@town|Towns}` shows it, or rolls Towns once and remembers the answer if it isn't set yet.
|
||||
- `{= @gold * 2}` shows a worked-out number.
|
||||
- Formatting: `[b]bold[/b]` and `[i]italic[/i]`.
|
||||
- Formatting: `[b]bold[/b]` and `[i]italic[/i]`. [b]Right-click[/b] any text field and use [b]Format[/b] to wrap the selected words: Bold, Italic, Underline, Strike-through, Colour, Size and Effect.
|
||||
- Moving text, for things such as loot rarity: [wave]Wave[/wave], [tornado]Tornado[/tornado], [shake]Shake[/shake], [rainbow]Rainbow[/rainbow], [pulse]Pulse[/pulse], Fade, [sparkle]Sparkle[/sparkle], [shimmer]Shimmer[/shimmer] and [flash]Flash[/flash]. As text: `[sparkle]Starlit ring[/sparkle]`.
|
||||
|
||||
[b]Quest Hooks[/b] in the sample uses all of these.
|
||||
|
||||
|
|
@ -175,7 +180,9 @@ Result text can do more than plain words:
|
|||
## Groups
|
||||
- Drag a box on empty space to select several cards and groups (hold Ctrl or Shift to add to the selection), or Ctrl-click or Shift-click cards. Dragging any selected card or group moves them all.
|
||||
- Press [b]Ctrl+G[/b] to put them in a group: a frame that moves and collapses as one.
|
||||
- Drag cards into or out of a group. The group's ⋯ menu renames, saves as a template, ungroups or deletes it.
|
||||
- Drag cards into or out of a group. The group's ⋯ menu renames, colours, saves as a template, ungroups or deletes it.
|
||||
- Each card in a group has a small tab in its top-right corner in the group's colour, and a collapsed group shows the same tab. Groups without a colour are blue in every theme.
|
||||
- To put whole groups inside a new group, select every card in them (or the collapsed group) along with the rest, then press Ctrl+G.
|
||||
- [b]Spread ▾ → Pack collapsed groups[/b] moves collapsed groups together to close the gaps.
|
||||
|
||||
## Templates
|
||||
|
|
@ -204,8 +211,9 @@ Groups can hold other groups. Select a group (drag a box around it) along with a
|
|||
[demo]groups[/demo]
|
||||
|
||||
# Colours and themes
|
||||
- [b]View ▾ → Sound…[/b] (or the ☰ menu) sets how loud the theme's sounds are, with a slider from Off to Loud.
|
||||
- [b]View ▾ → Theme…[/b] picks a theme and lets you change its colours, the background and panel gradients, the background pattern, the card border and the logo. Changes to a built-in theme are saved as a theme of your own.
|
||||
- Give a card or a thread its own colour from its right-click menu ([b]Colour[/b]) or in the inspector, to sort things at a glance.
|
||||
- Give a card, a thread or a group its own colour from its right-click menu ([b]Colour[/b]) or in the inspector, to sort things at a glance. [b]Any colour…[/b] at the end of the menu opens a full colour picker.
|
||||
|
||||
# List view
|
||||
[b]List view[/b] (View ▾, ☰ or right-click the spread) shows every card as a plain list, for when you'd rather not use the spread.
|
||||
|
|
@ -224,15 +232,17 @@ The [b]Book[/b] holds [b]Pages[/b]: results you want to use on more than one tab
|
|||
|
||||
# Rolling more than once
|
||||
- A thread can roll its card several times ([b]Rolls 3 times[/b] in the thread's inspector). Then choose what happens: [b]Keep every roll[/b], [b]Add them together[/b], [b]Keep the highest[/b], [b]Keep the lowest[/b] or [b]Let me choose[/b]. Rolls that aren't kept are faded in the tray, and don't follow their own threads.
|
||||
- [b]Roll several times…[/b] on a card's menu rolls its whole chain as many times as you like (five villagers, ten treasures) and shows every result together, ready to copy.
|
||||
- Tick [b]No repeats[/b] so every roll gives a different result (a result that already came up is rolled again). With [b]Let me choose[/b], that's "roll three different ones and pick one".
|
||||
- [b]Roll several times…[/b] on a card's menu rolls its whole chain as many times as you like (five villagers, ten treasures) and shows every result together, ready to copy. Each roll also appears in the tray's [b]Earlier[/b] list.
|
||||
[demo]repeats[/demo]
|
||||
|
||||
# Pausing a roll
|
||||
Tick [b]Wait for me first[/b] on a thread and the roll stops there, with [b]Continue ▸[/b] and [b]Stop here[/b] in the tray. Use it to reveal something a piece at a time. If you roll something else meanwhile, the paused roll waits in the tray until you continue it.
|
||||
Tick [b]Wait for me first[/b] on a thread and the roll stops there. The roll so far plays out first, then a pop-up asks [b]Continue ▸[/b], [b]Stop here[/b] or [b]Later[/b] (the same buttons wait in the tray). After Continue the rest of the roll plays out too. Use it to reveal something a piece at a time. If you roll something else meanwhile, the paused roll waits in the tray until you continue it.
|
||||
[demo]pause[/demo]
|
||||
|
||||
# Options that cost
|
||||
An option on a [b]Which option[/b] card can cost something: in its inspector, [b]Costs [1] of [Points][/b]. Picking it takes that away; when there isn't enough, the option is greyed out and says why. An option such as [b]Reroll[/b] that threads back to the loot card and costs a point gives players a spend-a-point reroll.
|
||||
- A whole card can cost something too: [b]Costs to roll[/b] in the card's inspector. Its roll button is greyed out when there isn't enough, and pressing it pays. When a thread reaches the card, the roll asks first: [b]Pay ▸[/b] rolls it, [b]Don't pay[/b] skips it.
|
||||
[demo]costs[/demo]
|
||||
|
||||
# One table adjusting another
|
||||
|
|
@ -253,11 +263,12 @@ A result or a Book page can have a picture: [b]Picture → Choose…[/b] in its
|
|||
- View, Help and Play/Build are in the [b]☰[/b] menu.
|
||||
|
||||
# Spreads, import and export
|
||||
A [b]spread[/b] is one layout of cards, saved under its own name. Use the switcher beside Play | Build (it shows the spread's name) to switch, or to make a new spread, rename, duplicate or delete one.
|
||||
A [b]spread[/b] is one layout of cards, saved under its own name. Use the switcher beside Play | Build (it shows the spread's name) to switch, or to make a new spread, rename, duplicate, delete one, or [b]Move to folder…[/b] to sort spreads into folders (the switcher lists each folder as a submenu).
|
||||
|
||||
In Build mode, [b]Spread ▾[/b] has:
|
||||
- [b]Import as new spread…[/b] for Table Tarot JSON, JSON Canvas and GraphML files.
|
||||
- [b]Export as…[/b] Table Tarot JSON, JSON Canvas, GraphML, a Mermaid diagram or Graphviz DOT.
|
||||
- [b]Export as Table Tarot JSON… (full copy)[/b]: everything on the spread, to import again or share.
|
||||
- [b]Export as a diagram[/b]: JSON Canvas, GraphML, a Mermaid diagram or Graphviz DOT, for diagram and mind-map tools. These hold cards and threads only; importing one back is not a full copy.
|
||||
|
||||
Exports hold the tables only. Your roll history, decks and remembered values stay on this computer.
|
||||
|
||||
|
|
@ -289,6 +300,7 @@ Click any item in the report to jump to that card. A spread that can loop foreve
|
|||
- [b]M[/b]: show or hide the minimap
|
||||
- [b]Ctrl+Z[/b]: undo. [b]Ctrl+Shift+Z[/b] or [b]Ctrl+Y[/b]: redo
|
||||
- [b]Ctrl+G[/b]: group the selected cards and groups
|
||||
- [b]Delete[/b] (Build): delete the selected cards and groups, or the thread, result or card in the inspector. It asks first; turn that off in [b]View ▾ → Ask before deleting[/b]. Ctrl+Z brings it back.
|
||||
- [b]Esc[/b]: clear the selection, or close a window
|
||||
- In a question pop-up: [b]1–9[/b] pick an option, [b]R[/b] Random, [b]M[/b] or [b]Tab[/b] look at the spread
|
||||
## Mouse
|
||||
|
|
|
|||
|
|
@ -15,6 +15,8 @@ static func canonical(src: Dictionary) -> Dictionary:
|
|||
tables.append(_canon_table(t))
|
||||
var cname := str(src.get("name", src.get("collection", "")))
|
||||
var out := {"format_version": JsonIO.FORMAT_VERSION, "id": str(src.get("id", "")), "name": cname, "tables": tables}
|
||||
if str(src.get("folder", "")).strip_edges() != "":
|
||||
out["folder"] = str(src["folder"]).strip_edges()
|
||||
var groups: Array = []
|
||||
var src_groups: Variant = src.get("groups", [])
|
||||
if src_groups is Array:
|
||||
|
|
@ -65,7 +67,7 @@ static func _canon_group(gd: Dictionary) -> Dictionary:
|
|||
if str(m) != "" and not members.has(str(m)):
|
||||
members.append(str(m))
|
||||
g["members"] = members
|
||||
_keep(gd, g, ["parent"])
|
||||
_keep(gd, g, ["parent", "color"])
|
||||
return g
|
||||
|
||||
|
||||
|
|
@ -129,7 +131,7 @@ static func _canon_table(td: Dictionary) -> Dictionary:
|
|||
for e in src_entries:
|
||||
entries.append(_canon_entry(e))
|
||||
t["entries"] = entries
|
||||
_keep(td, t, ["color", "w", "list_h", "roll_floor", "roll_ceiling", "deck_empty_text", "columns", "column_rolls", "steps"])
|
||||
_keep(td, t, ["color", "w", "list_h", "roll_floor", "roll_ceiling", "deck_empty_text", "columns", "column_rolls", "steps", "members", "repeats", "cost"])
|
||||
# A separator may be just a space, so it isn't trimmed.
|
||||
if td.get("column_join") is String and td["column_join"] != "":
|
||||
t["column_join"] = td["column_join"]
|
||||
|
|
@ -183,7 +185,7 @@ static func _canon_entry(ev: Variant) -> Dictionary:
|
|||
var wv := _canon_with(p.get("with"))
|
||||
if not wv.is_empty():
|
||||
np["with"] = wv
|
||||
_keep(p, np, ["color", "combine", "pause", "dice", "reroll"])
|
||||
_keep(p, np, ["color", "combine", "pause", "dice", "reroll", "distinct"])
|
||||
pipes.append(np)
|
||||
if not pipes.is_empty():
|
||||
e["pipes"] = pipes
|
||||
|
|
|
|||
47
tests/perf_roll.gd
Normal file
47
tests/perf_roll.gd
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
extends TestBase
|
||||
## Times rolling one card on a big spread: the roll logic alone, then the
|
||||
## whole app roll (fast), then the parts of the screen update after it.
|
||||
## Not part of the suite (the name doesn't start with test_). Run:
|
||||
## SPREAD=/path/to/spread.json CARD=start \
|
||||
## godot --headless --path . -s res://tests/perf_roll.gd -- --sample
|
||||
## (--sample keeps the app from reading or writing saved spreads.)
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
if not await start_main():
|
||||
return
|
||||
var card_id := OS.get_environment("CARD") if OS.get_environment("CARD") != "" else "start"
|
||||
main.prompt_hook = func(req: Dictionary) -> Variant:
|
||||
return 0 if not (req.get("options", []) as Array).is_empty() else req.get("default", 1)
|
||||
main.data.load_json(FileAccess.get_file_as_string(OS.get_environment("SPREAD")))
|
||||
main.persistent_vars.clear()
|
||||
main._rebuild_cards()
|
||||
await _frames(10)
|
||||
var logic_ms: Array[float] = []
|
||||
for seed_value in 10:
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = seed_value
|
||||
var ctx := Roller.new_context(main.data, rng, {}, {})
|
||||
ctx.prompt = main.prompt_hook
|
||||
var started := Time.get_ticks_usec()
|
||||
await Roller.roll_async(main.data, card_id, ctx)
|
||||
logic_ms.append((Time.get_ticks_usec() - started) / 1000.0)
|
||||
print("PERF logic ms: ", logic_ms)
|
||||
for seed_value in 6:
|
||||
main.rng.seed = 100 + seed_value
|
||||
var started := Time.get_ticks_usec()
|
||||
await main.rolling.start_roll(card_id, true)
|
||||
var rolled := Time.get_ticks_usec()
|
||||
await process_frame
|
||||
print("PERF app roll %.1f ms, next frame %.1f ms, steps %d" % [(rolled - started) / 1000.0,
|
||||
(Time.get_ticks_usec() - rolled) / 1000.0, (main.current["all"] as Array).size()])
|
||||
var marks: Array[int] = [Time.get_ticks_usec()]
|
||||
main._refresh_lit()
|
||||
marks.append(Time.get_ticks_usec())
|
||||
main.refresh_live()
|
||||
marks.append(Time.get_ticks_usec())
|
||||
main.tray.render()
|
||||
marks.append(Time.get_ticks_usec())
|
||||
print("PERF parts: relight %.1f ms, live cards %.1f ms, tray %.1f ms" % [(marks[1] - marks[0]) / 1000.0,
|
||||
(marks[2] - marks[1]) / 1000.0, (marks[3] - marks[2]) / 1000.0])
|
||||
finish()
|
||||
1
tests/perf_roll.gd.uid
Normal file
1
tests/perf_roll.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dh0lx2kdd1pje
|
||||
|
|
@ -10,6 +10,7 @@ func _init() -> void:
|
|||
return
|
||||
await _test_lists()
|
||||
await _test_popup_and_run()
|
||||
await _test_delete_key()
|
||||
finish()
|
||||
|
||||
|
||||
|
|
@ -68,3 +69,30 @@ func _test_popup_and_run() -> void:
|
|||
bar_pm.about_to_popup.emit()
|
||||
_check(bar_pm.item_count > 4, "the ☰ menu fills with the spread's actions")
|
||||
|
||||
|
||||
## The Delete key: asks first (by default), deletes the selection as one undo
|
||||
## step, and skips the question when "Ask before deleting" is off.
|
||||
func _test_delete_key() -> void:
|
||||
main.set_mode(Main.Mode.BUILD)
|
||||
await _frames()
|
||||
main.clear_selection()
|
||||
main.editing.toggle_selected("loot")
|
||||
main.editing.toggle_selected("names")
|
||||
var found := DeleteKey.target(main)
|
||||
_eq(str(found.get("what", "")), "2 cards", "Delete names what it would delete")
|
||||
DeleteKey.press(main)
|
||||
await _frames()
|
||||
var asked := main.get_children().filter(func(n: Node) -> bool: return n is ModalCard)
|
||||
_check(not asked.is_empty() and main.data.get_table("loot") != null, "by default it asks first and deletes nothing yet")
|
||||
for dialog: ModalCard in asked:
|
||||
dialog.close()
|
||||
DeleteKey.set_asks(main, false)
|
||||
DeleteKey.press(main)
|
||||
await _frames()
|
||||
_check(main.data.get_table("loot") == null and main.data.get_table("names") == null, "with asking off it deletes both cards")
|
||||
main.undo_redo.undo()
|
||||
await _frames()
|
||||
_check(main.data.get_table("loot") != null and main.data.get_table("names") != null, "one undo brings both back")
|
||||
DeleteKey.set_asks(main, true)
|
||||
main.clear_selection()
|
||||
main.set_mode(Main.Mode.PLAY)
|
||||
|
|
|
|||
|
|
@ -61,6 +61,17 @@ func _test_book() -> void:
|
|||
main.undo_redo.undo()
|
||||
await _frames()
|
||||
_check(main.data.book.size() == 1, "undo brings the page back")
|
||||
# Undo of a text edit shows in the open page editor at once.
|
||||
var page := main.data.book[0]
|
||||
main.book.editor.show_page(page)
|
||||
var typed: TextEdit = main.book.editor.find_children("*", "TextEdit", true, false)[0]
|
||||
typed.text = "Rusty Sword"
|
||||
typed.text_changed.emit()
|
||||
await _frames()
|
||||
main.undo_redo.undo()
|
||||
await _frames()
|
||||
var shown: Array = main.book.editor.find_children("*", "TextEdit", true, false).map(func(edit: TextEdit) -> String: return edit.text)
|
||||
_check(shown.has("Holy Sword"), "the page editor shows the undone text without reselecting: %s" % str(shown))
|
||||
|
||||
|
||||
func _test_pictures() -> void:
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ extends TestBase
|
|||
func _init() -> void:
|
||||
await _test_join_and_repeat()
|
||||
await _test_repeat_reroll()
|
||||
await _test_repeat_one_column()
|
||||
await _test_list_save()
|
||||
await _test_only_option()
|
||||
_test_save_load()
|
||||
|
|
@ -88,6 +89,24 @@ func _test_repeat_reroll() -> void:
|
|||
_check(str(col["text"]).count(" & ") <= 1, "rolling again on the repeat row keeps it to two: %s" % col["text"])
|
||||
|
||||
|
||||
## A combine row set to the 1st column only: the 2nd column just shows its
|
||||
## own cell when the row comes up there.
|
||||
func _test_repeat_one_column() -> void:
|
||||
var b := _surface_board()
|
||||
var r := b.get_table("surface").find_entry("r")
|
||||
r.repeat = TableEntry.clean_repeat({"count": 2, "reroll": ["r"], "columns": [0]})
|
||||
_eq(r.repeat.get("columns"), [0], "the columns list is kept")
|
||||
var plain_second := false
|
||||
for s in 60:
|
||||
var tree := await Roller.roll_async(b, "start", _ctx(b, s))
|
||||
for kid: Dictionary in tree["children"]:
|
||||
var second: Dictionary = kid["columns"][1]
|
||||
_check(not str(second["text"]).contains(" & "), "the 2nd column doesn't roll again: %s" % second["text"])
|
||||
plain_second = plain_second or str(second["text"]) == "Roll twice and combine"
|
||||
_check(plain_second, "it shows the row's own cell there instead")
|
||||
_check(RollColumns.repeats_in(r, 0) and not RollColumns.repeats_in(r, 1), "repeats_in follows the list")
|
||||
|
||||
|
||||
func _test_list_save() -> void:
|
||||
var b := TowerBoard.new()
|
||||
var res := RollTable.new("res", "Resource")
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ func _init() -> void:
|
|||
await _test_columns_each()
|
||||
_test_dice_override()
|
||||
_test_reroll()
|
||||
_test_only_if_results()
|
||||
_test_save_load()
|
||||
_test_lint()
|
||||
finish()
|
||||
|
|
@ -180,6 +181,7 @@ func _test_reroll() -> void:
|
|||
for f: Dictionary in kid.get("why", []):
|
||||
if f["type"] == "reroll":
|
||||
skipped = true
|
||||
_eq(str((f["skipped"] as Array)[0].get("entry_id", "")), "f96", "a skipped roll names its result, so the animation can show it")
|
||||
_check(skipped, "a reroll why fact is recorded")
|
||||
_eq(DescribeCards.pipe(e, "feat", b), "again on 96–00", "the label lists the numbers")
|
||||
e.set_pipe_reroll("feat", ["f1", "f71", "f96"])
|
||||
|
|
@ -187,6 +189,33 @@ func _test_reroll() -> void:
|
|||
_eq(str(tree2["children"][0]["stop"]), RollCards.ALL_REROLLED, "rolling again on everything stops")
|
||||
|
||||
|
||||
## A roll table's result with "Can come up only if" (show_if) is rolled
|
||||
## again while its condition is false.
|
||||
func _test_only_if_results() -> void:
|
||||
var b := TowerBoard.new()
|
||||
var t := RollTable.new("loot", "Loot")
|
||||
for item: Array in [["a", "Copper"], ["b", "Silver"], ["c", "Dragon hoard"]]:
|
||||
t.entries.append(TableEntry.new(item[0], item[1]))
|
||||
t.entries[2].show_if = "@level >= 5"
|
||||
b.tables.append(t)
|
||||
var low := Roller.new_context(b, RandomNumberGenerator.new(), {"level": {"value": 1}}, {})
|
||||
var saw_hoard := false
|
||||
for s in 60:
|
||||
low.rng.seed = s
|
||||
saw_hoard = saw_hoard or ((RollCards.pick_for(t, low, {})["entry"] as TableEntry).id == "c")
|
||||
_check(not saw_hoard, "a result whose Only if is false never comes up")
|
||||
var high := Roller.new_context(b, RandomNumberGenerator.new(), {"level": {"value": 9}}, {})
|
||||
var got_hoard := false
|
||||
for s in 60:
|
||||
high.rng.seed = s
|
||||
got_hoard = got_hoard or ((RollCards.pick_for(t, high, {})["entry"] as TableEntry).id == "c")
|
||||
_check(got_hoard, "it comes up once its Only if is true")
|
||||
for e in t.entries:
|
||||
e.show_if = "@level >= 5"
|
||||
_eq(str(RollCards.pick_for(t, low, {}).get("stop", "")), RollCards.NONE_ALLOWED, "when nothing is allowed the card says so")
|
||||
_check(RollLint.lint_options(t).is_empty(), "Only if on a roll result isn't flagged as doing nothing")
|
||||
|
||||
|
||||
func _test_save_load() -> void:
|
||||
var b := _board()
|
||||
b.tables.append(_type_card(RollTable.COLUMNS_EACH))
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ func _init() -> void:
|
|||
await _test_resize()
|
||||
await _test_compact()
|
||||
await _test_play_drag_selects()
|
||||
await _test_show_less()
|
||||
finish()
|
||||
|
||||
|
||||
|
|
@ -86,3 +87,21 @@ func _test_play_drag_selects() -> void:
|
|||
_check(main.selection.has("road"), "it selects what the box touches")
|
||||
main.clear_selection()
|
||||
|
||||
|
||||
## A long card opened with "show all" has "▲ Show less" to fold it up again.
|
||||
func _test_show_less() -> void:
|
||||
var t := main.data.get_table("trinkets")
|
||||
if not t.collapsed:
|
||||
main.toggle_collapse("trinkets")
|
||||
await _frames(2)
|
||||
main.toggle_collapse("trinkets")
|
||||
await _frames(2)
|
||||
var less: Array = []
|
||||
for node in main.card_for("trinkets").find_children("*", "Button", true, false):
|
||||
if node.has_meta("show_less"):
|
||||
less.append(node)
|
||||
_check(not t.collapsed and less.size() == 1, "an opened long card shows Show less")
|
||||
if less.size() == 1:
|
||||
(less[0] as Button).pressed.emit()
|
||||
await _frames(2)
|
||||
_check(t.collapsed, "Show less collapses it again")
|
||||
|
|
|
|||
|
|
@ -40,9 +40,32 @@ func _init() -> void:
|
|||
_check(main.current.get("done", false) and main.current.get("fast", false), "the interrupted roll doesn't overwrite the fast result")
|
||||
|
||||
await _test_deck_waits()
|
||||
await _test_batch_history()
|
||||
_test_reroll_mark()
|
||||
finish()
|
||||
|
||||
|
||||
## "Roll again" shows: the skipped result flickers with a floating note.
|
||||
func _test_reroll_mark() -> void:
|
||||
var card := main.card_for("names")
|
||||
var eid: String = card.rows.keys()[0]
|
||||
card.mark_rerolled(eid)
|
||||
var notes := card.get_parent().find_children("*", "Label", false, false).filter(func(l: Label) -> bool: return l.text.contains("rolled again"))
|
||||
_check(not notes.is_empty(), "a rolled-again result gets a floating note")
|
||||
|
||||
|
||||
## A batch of rolls goes into the tray's Earlier list, newest first.
|
||||
func _test_batch_history() -> void:
|
||||
var before := main.history.size()
|
||||
var texts: Array[String] = await BatchRoll.run(main, "names", 3)
|
||||
_eq(texts.size(), 3, "a batch rolls the asked number of times")
|
||||
_eq(main.history.size(), mini(before + 4, Main.HISTORY_SIZE), "each batch roll joins Earlier (after the roll on screen)")
|
||||
_eq(str(main.history[0].get("batch", "")), "3 of 3", "the newest is the batch's last roll")
|
||||
for node in main.get_children():
|
||||
if node is ModalCard:
|
||||
(node as ModalCard).close()
|
||||
|
||||
|
||||
## Deck mode: an animated roll fades the drawn result only once it lights;
|
||||
## a fast roll fades it at once.
|
||||
func _test_deck_waits() -> void:
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ func _init() -> void:
|
|||
main.mark_dirty()
|
||||
await _frames()
|
||||
var mark := main.card_for("a").group_mark
|
||||
_check(mark.visible and mark._color == Style.GROUP, "a member shows the theme's group mark")
|
||||
_check(mark.visible and mark._color == GroupMark.DEFAULT_COLOR, "a member shows the default group mark (the same in every theme)")
|
||||
_check(not main.card_for("c").group_mark.visible, "a card outside the group has no mark")
|
||||
|
||||
Actions.set_group_colour(main, g, "#3c8dd8")
|
||||
|
|
@ -29,7 +29,7 @@ func _init() -> void:
|
|||
_eq(TableGroup.from_dict(g.to_dict()).color, "#3c8dd8", "the group colour is saved")
|
||||
main.undo_redo.undo()
|
||||
await _frames()
|
||||
_check(main.card_for("b").group_mark._color == Style.GROUP, "undo puts the theme colour back")
|
||||
_check(main.card_for("b").group_mark._color == GroupMark.DEFAULT_COLOR, "undo puts the default colour back")
|
||||
|
||||
# Lying inside the frame isn't membership: no mark until it joins.
|
||||
var c := main.card_for("c")
|
||||
|
|
@ -44,4 +44,15 @@ func _init() -> void:
|
|||
main.mark_dirty()
|
||||
await _frames()
|
||||
_check(not main.card_for("c").group_mark.visible, "leaving the group clears the mark")
|
||||
_check(GroupMark.outline_for(Color.WHITE) != GroupMark.outline_for(Color.BLACK), "the tab's outline stands out from light and dark colours")
|
||||
main.toggle_group(g.id)
|
||||
await _frames()
|
||||
var marks: Array = main.group_node(g.id).find_children("*", "GroupMark", true, false)
|
||||
_check(marks.size() == 1 and (marks[0] as GroupMark).visible and (marks[0] as GroupMark)._color == GroupMark.color_of(g), "a collapsed group shows its own corner tab")
|
||||
var menu := Actions.group(main, g)
|
||||
var colour_menu: Dictionary = {}
|
||||
for item: Dictionary in menu:
|
||||
if str(item.get("text", "")) == "Colour":
|
||||
colour_menu = item
|
||||
_check((colour_menu.get("sub", []) as Array).any(func(item: Dictionary) -> bool: return str(item["text"]).ends_with("Any colour…")), "the group Colour menu ends with Any colour…")
|
||||
finish()
|
||||
|
|
|
|||
|
|
@ -389,6 +389,20 @@ func _test_nested() -> void:
|
|||
var back := TowerBoard.new()
|
||||
back.load_dict(d)
|
||||
_check(back.groups.size() == main.data.groups.size(), "groups survive saving")
|
||||
# A box over an open group selects its cards, not always the frame:
|
||||
# grouping then nests the open group instead of emptying it.
|
||||
main.clear_selection()
|
||||
_check(not inner.collapsed, "(the inner group is open)")
|
||||
for tid: String in inner.members:
|
||||
main.editing.toggle_selected(tid)
|
||||
main.editing.toggle_selected("loose")
|
||||
var kept := inner.members.duplicate()
|
||||
var wrapper := main.grouping.group_selection()
|
||||
await _frames(3)
|
||||
_check(wrapper != null and inner.parent == wrapper.id and inner.members == kept, "selecting every card of an open group nests the group")
|
||||
_eq(wrapper.members if wrapper else [], ["loose"], "and only the loose card joins the new group directly")
|
||||
main.ungroup(wrapper.id)
|
||||
await _frames(3)
|
||||
|
||||
|
||||
func _shown(tid: String) -> bool:
|
||||
|
|
|
|||
|
|
@ -97,6 +97,9 @@ func _test_selection() -> void:
|
|||
_eq(insp.selection.get("to"), "loot", "select_pipe")
|
||||
_eq(insp.pipe_parts.keys(), ["loot"], "a thread shows only its own box")
|
||||
_eq(main.board.pipes.select_key, "beyond:e2>loot", "the selected thread is highlighted on the spread")
|
||||
var plain_target: bool = not main.data.get_table("loot").is_ranged()
|
||||
var hints := insp.find_children("*", "Label", true, false).filter(func(l: Label) -> bool: return l.has_meta("dice_hint"))
|
||||
_check(not plain_target or hints.size() == 1, "a thread into a card without ranges says where Roll it with … instead is")
|
||||
main.clear_inspector()
|
||||
_check(insp.selection.is_empty(), "clear_inspector")
|
||||
main.open_pipe_options("beyond:e2>curios", Vector2(10, 10))
|
||||
|
|
@ -350,6 +353,22 @@ func _test_collection() -> void:
|
|||
InspectorCard.remove_member(insp, t, "gun_combat")
|
||||
_eq(insp.members(t), [["pilot", "2"]], "× removes a member")
|
||||
_eq(Describe.label("@skill_pilot", main.data), "Pilot", "(members are labelled through the spread)")
|
||||
_eq(t.members, [{"name": "pilot", "start": "2"}], "the entries are saved on the card")
|
||||
var copy := RollTable.from_dict(t.to_dict())
|
||||
_eq(copy.members, t.members, "and survive a save and load (copies, exports)")
|
||||
main.persistent_vars["skill_pilot"] = {"value": 5, "source": "roll"}
|
||||
main.reset_variable("skill_pilot")
|
||||
_eq(main.persistent_vars.get("skill_pilot", {}).get("value"), 2, "Reset puts an entry back to its start")
|
||||
main.undo_redo.undo()
|
||||
_eq(t.members, [{"name": "pilot", "start": "2"}, {"name": "gun_combat", "start": "0"}], "undo brings a removed entry back")
|
||||
_eq(main.persistent_vars.get("skill_gun_combat", {}).get("value"), 0, "with its value")
|
||||
main.undo_redo.redo()
|
||||
var old := RollTable.create(RollTable.KIND_VARIABLE, "old_ledger", "Feats", RollTable.VAR_COLLECTION)
|
||||
var made := {"feat_dodge": {"value": 3, "source": "old_ledger"}, "feat_luck": {"value": 1, "source": "a_roll"}}
|
||||
var board := TowerBoard.new()
|
||||
board.tables.append(old)
|
||||
_check(LedgerMembers.adopt(board, made), "an older Ledger takes in the entries made on it")
|
||||
_eq(old.members, [{"name": "dodge", "start": "3"}], "but not values that rolls added")
|
||||
await _frames()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -56,6 +56,10 @@ func _test_json() -> void:
|
|||
var res2 := JsonIO.import_json(JsonIO.export_json(small))
|
||||
_check(res2["ok"] and res2["collection"] == JsonIO.canonical(small), "small spread round-trips exactly")
|
||||
_check(not JsonIO.export_json({"tables": [], "state": {"draws": 1}}).contains("state"), "export drops unknown/local keys")
|
||||
var coloured := _small()
|
||||
coloured["groups"] = [{"id": "g1", "name": "Gear", "members": ["loot"], "color": "#7a3fa8"}]
|
||||
var cres := JsonIO.import_json(JsonIO.export_json(coloured))
|
||||
_check(cres["ok"] and cres["collection"]["groups"][0].get("color", "") == "#7a3fa8", "a group's colour survives export and import")
|
||||
|
||||
# Legacy keys: triggers, die, collection name.
|
||||
var legacy := JsonIO.import_json('{"format_version":1,"collection":"Old","tables":[{"id":"a","name":"A","die":20,"entries":[{"text":"x","triggers":["a"]}]}]}')
|
||||
|
|
|
|||
49
tests/test_lists.gd
Normal file
49
tests/test_lists.gd
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
extends TestBase
|
||||
## List values: the "Add to list" change row (picking a list, the result's own
|
||||
## text as the item, a new value made there is a list), and "Allow repeats".
|
||||
## Run: godot --headless --path . -s res://tests/test_lists.gd -- --sample
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
if not await start_main():
|
||||
return
|
||||
main.set_mode(Main.Mode.BUILD)
|
||||
main.data.load_dict({"format_version": 2, "id": "list-test", "name": "List test", "tables": [
|
||||
{"id": "groc", "name": "Groceries", "kind": "variable", "var_name": "groceries", "var_type": "list", "x": 40, "y": 40, "entries": []},
|
||||
{"id": "shop", "name": "Shop", "x": 340, "y": 40, "entries": [{"id": "e1", "text": "[b]Eggs[/b]"}]},
|
||||
]})
|
||||
main.persistent_vars.clear()
|
||||
main._rebuild_cards()
|
||||
await _frames(4)
|
||||
await _test_add_to_list_row()
|
||||
_test_repeats()
|
||||
finish()
|
||||
|
||||
|
||||
func _test_add_to_list_row() -> void:
|
||||
main.select_result("shop", "e1")
|
||||
await _frames(2)
|
||||
var fx := main.inspector.effects
|
||||
fx.add_row()
|
||||
fx.set_row_op(0, "append")
|
||||
_eq(fx.rows[0]["amount"], "Eggs", "Add to list offers the result's own text")
|
||||
fx.set_row_var(0, "@groceries")
|
||||
_eq(main.data.get_table("shop").find_entry("e1").effects, "@groceries += \"Eggs\"", "and writes it as the item")
|
||||
var picker := ValuePicker.new(main)
|
||||
picker.kinds = ["list", "text"]
|
||||
var made := picker.create_value("Inventory", true)
|
||||
var card := main.variable_card(made.trim_prefix("@"))
|
||||
_check(card != null and card.var_type == "list", "a new value made from a list picker is a list")
|
||||
picker.free()
|
||||
|
||||
|
||||
func _test_repeats() -> void:
|
||||
_eq(Effects.list_with("Eggs", "eggs"), "Eggs", "without repeats an item already there isn't added again")
|
||||
_eq(Effects.list_with("Eggs", "Eggs", false, true), "Eggs, Eggs", "with repeats it's added every time, in order")
|
||||
_eq(Effects.list_with("Eggs, Milk, Eggs", "Eggs", true), "Milk, Eggs", "removing takes out the first match")
|
||||
var groc := main.data.get_table("groc")
|
||||
groc.list_repeats = true
|
||||
_check(RollTable.from_dict(groc.to_dict()).list_repeats, "Allow repeats is saved with the card")
|
||||
var ctx := Roller.new_context(main.data, main.rng, {}, {})
|
||||
Effects.run("@groceries += \"Eggs\"\n@groceries += \"Eggs\"", ctx, "shop")
|
||||
_eq(ctx.get_value("@groceries"), "Eggs, Eggs", "a list that allows repeats collects each one")
|
||||
1
tests/test_lists.gd.uid
Normal file
1
tests/test_lists.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dct2cpq3ic6dx
|
||||
|
|
@ -14,6 +14,7 @@ func _init() -> void:
|
|||
_test_words()
|
||||
_test_problems()
|
||||
_test_editor_forms()
|
||||
_test_plain_shift()
|
||||
finish()
|
||||
|
||||
|
||||
|
|
@ -177,3 +178,27 @@ func _test_editor_forms() -> void:
|
|||
_eq(ModifierEditor.compose(W.SUBTRACT, "@fatigue"), "-@fatigue", "compose subtract")
|
||||
_eq(ModifierEditor.compose(W.DM, "@str"), "dm(@str)", "compose dm")
|
||||
_eq(ModifierEditor.compose(W.ADD, ""), "", "no value yet, no text")
|
||||
|
||||
|
||||
## A plain (unranged) table's modifier moves the pick by rows; the ends catch
|
||||
## anything past them; the Why line says so; it's saved; a switch clears it.
|
||||
func _test_plain_shift() -> void:
|
||||
var t := RollTable.new("finds", "Finds")
|
||||
for item in ["Nothing", "Coins", "Gem", "Relic"]:
|
||||
t.entries.append(TableEntry.new("f%d" % t.entries.size(), item))
|
||||
t.entries[0].weight = 1
|
||||
for k in [1, 2, 3]:
|
||||
t.entries[k].weight = 0
|
||||
t.dice_mod = "@luck"
|
||||
var b := TowerBoard.new()
|
||||
b.tables.append(t)
|
||||
var ctx := Roller.new_context(b, RandomNumberGenerator.new(), {"luck": {"value": 2}}, {})
|
||||
var node := RollCards.pick_node(t, ctx)
|
||||
_eq((node["entry"] as TableEntry).text, "Gem", "+2 moves Nothing down two rows to Gem")
|
||||
var fact: Dictionary = node["why"][0]
|
||||
_eq(DescribeWhy._why_roll(fact, Describe._labels(b), true), "Rolled 1 on d4, moved down 2 rows for Luck, to row 3", "the Why line explains the move")
|
||||
var far := Roller.new_context(b, RandomNumberGenerator.new(), {"luck": {"value": 9}}, {})
|
||||
_eq((RollCards.pick_node(t, far)["entry"] as TableEntry).text, "Relic", "past the last row counts as the last row")
|
||||
_eq(RollTable.from_dict(t.to_dict()).dice_mod, "@luck", "a plain table's modifier is saved")
|
||||
TableSettingsRules.apply_settings(t, {"ranged": true, "dice": "1d4"})
|
||||
_eq(t.dice_mod, "", "switching to ranged clears it, since it would mean something else")
|
||||
|
|
|
|||
|
|
@ -379,8 +379,11 @@ func _test_build_rows() -> void:
|
|||
var adds := _with_meta(main.card_for("skills"), "collection_add")
|
||||
_check(adds.size() == 1 and (adds[0] as Button).text == "+ Add skill", "the spread card has + Add skill in Build")
|
||||
if adds.size() == 1:
|
||||
var before: int = main.data.get_table("skills").members.size()
|
||||
(adds[0] as Button).emit_signal("pressed")
|
||||
_eq(main.get("picked").back(), ["card", "skills"], "+ Add selects the card for the inspector")
|
||||
_eq(main.data.get_table("skills").members.size(), before + 1, "+ Add adds an entry right on the card")
|
||||
var fields := _with_meta(main.card_for("skills"), "ledger_name")
|
||||
_check(fields.size() == before + 1, "each entry is a name field on the card in Build")
|
||||
_check(_has(main.card_for("loot"), "Input Tier · starts at 1"), "the inputs box shows in Build too")
|
||||
main.set_mode(Main.Mode.PLAY)
|
||||
await process_frame
|
||||
|
|
|
|||
|
|
@ -7,9 +7,11 @@ extends TestBase
|
|||
|
||||
func _init() -> void:
|
||||
_test_combine()
|
||||
_test_no_repeats()
|
||||
await _test_choose()
|
||||
await _test_pause()
|
||||
await _test_costs()
|
||||
await _test_card_costs()
|
||||
_test_limits()
|
||||
finish()
|
||||
|
||||
|
|
@ -39,6 +41,30 @@ func _kids(tree: Dictionary, tid: String) -> Array:
|
|||
return (tree["children"] as Array).filter(func(k: Dictionary) -> bool: return (k["table"] as RollTable).id == tid)
|
||||
|
||||
|
||||
## "No repeats": three rolls of a six-result card all differ, and with as
|
||||
## many rolls as results every result comes up once; saved and loaded.
|
||||
func _test_no_repeats() -> void:
|
||||
for seed_value in 30:
|
||||
var b := _board("all")
|
||||
var e: TableEntry = b.get_table("start").entries[0]
|
||||
e.pipe_distinct["gold"] = true
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = seed_value
|
||||
var ids := {}
|
||||
for k: Dictionary in _kids(Roller.roll(b, "start", rng), "gold"):
|
||||
ids[(k["entry"] as TableEntry).id] = true
|
||||
_check(ids.size() == 3, "no repeats: three different results (seed %d)" % seed_value)
|
||||
var six := _board("all")
|
||||
var six_e: TableEntry = six.get_table("start").entries[0]
|
||||
six_e.pipe_distinct["gold"] = true
|
||||
six_e.add_pipe("gold", 6, "loot")
|
||||
var all_ids := {}
|
||||
for k: Dictionary in _kids(Roller.roll(six, "start", RandomNumberGenerator.new()), "gold"):
|
||||
all_ids[(k["entry"] as TableEntry).id] = true
|
||||
_eq(all_ids.size(), 6, "six rolls of six results give each one once")
|
||||
_check(TableEntry.from_dict(six_e.to_dict()).pipe_distinct.has("gold"), "No repeats is saved with the thread")
|
||||
|
||||
|
||||
func _test_combine() -> void:
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = 7
|
||||
|
|
@ -111,6 +137,34 @@ func _test_pause() -> void:
|
|||
_check(back.pipe_pause.has("gold"), "the pause is saved")
|
||||
|
||||
|
||||
## A card that costs 1 point to roll: its own roll pays or stops; a thread
|
||||
## that reaches it asks first (Continue pays, Stop skips it).
|
||||
func _test_card_costs() -> void:
|
||||
var b := _board("all")
|
||||
var gold := b.get_table("gold")
|
||||
gold.cost_value = "@points"
|
||||
gold.cost_amount = "1"
|
||||
var ctx := Roller.new_context(b, RandomNumberGenerator.new(), {"points": {"value": 2}})
|
||||
var tree: Dictionary = await Roller.roll_async(b, "gold", ctx)
|
||||
_check(not tree.has("stop") and int(ctx.lookup("@points")) == 1, "rolling the card itself pays its cost")
|
||||
_check((tree.get("why", []) as Array).any(func(f: Dictionary) -> bool: return f.get("type") == "effect"), "the payment shows in Why this?")
|
||||
ctx = Roller.new_context(b, RandomNumberGenerator.new(), {"points": {"value": 0}})
|
||||
tree = await Roller.roll_async(b, "gold", ctx)
|
||||
_check(str(tree.get("stop", "")).begins_with("Can't roll"), "with nothing to pay it doesn't roll: %s" % tree.get("stop", ""))
|
||||
var asked: Array = []
|
||||
ctx = Roller.new_context(b, RandomNumberGenerator.new(), {"points": {"value": 5}})
|
||||
ctx.prompt = func(req: Dictionary) -> Variant:
|
||||
asked.append(req)
|
||||
return asked.size() == 1
|
||||
tree = await Roller.roll_async(b, "start", ctx)
|
||||
_check(asked.size() == 3 and str(asked[0].get("cost", "")) != "", "a thread into it asks before each roll")
|
||||
var golds := _kids(tree, "gold")
|
||||
_check(golds.size() == 3 and not golds[0].has("stop") and golds[1].has("stop"), "Continue pays and rolls; not paying skips it")
|
||||
_check(int(ctx.lookup("@points")) == 4, "only the paid roll took a point")
|
||||
var back := RollTable.from_dict(gold.to_dict())
|
||||
_check(back.cost_value == "@points" and back.cost_amount == "1", "the card's cost is saved")
|
||||
|
||||
|
||||
## A pick card whose "Reroll" option costs 1 point.
|
||||
func _test_costs() -> void:
|
||||
var b := TowerBoard.new()
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
extends TestBase
|
||||
## Small UI items: backwards ranges warn and block rolling (no auto-swap), the
|
||||
## inspector's thread lists, replacing a template, the tray chip's bold source
|
||||
## name, and the export menu's Other formats.
|
||||
## name, and the export menu's diagram formats.
|
||||
## Run: godot --headless --path . -s res://tests/test_small_ui.gd -- --sample
|
||||
|
||||
|
||||
|
|
@ -81,7 +81,7 @@ func _test_chip_and_export() -> void:
|
|||
_check(bold, "the chip names its card in bold")
|
||||
var pm := main.top_bar._board_menu.get_popup()
|
||||
var subs := pm.find_children("*", "PopupMenu", false, false)
|
||||
_check(subs.size() == 1 and (subs[0] as PopupMenu).item_count == IoMenu.EXPORTS.size() - 1, "rare formats sit under Other formats")
|
||||
_check(subs.size() == 1 and (subs[0] as PopupMenu).item_count == IoMenu.EXPORTS.size() - 1, "diagram formats sit under Export as a diagram")
|
||||
|
||||
|
||||
## Deck mode: drawn results fade, an empty deck that waits for Shuffle gives
|
||||
|
|
|
|||
39
tests/test_spread_links.gd
Normal file
39
tests/test_spread_links.gd
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
extends TestBase
|
||||
## Rolling a card from another spread: [[Treasure::Loot]] rolls Loot in the
|
||||
## Treasure spread (its own references resolve there), changes this spread's
|
||||
## values, and a missing spread or card shows the missing marker.
|
||||
## Run: godot --headless --path . -s res://tests/test_spread_links.gd
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
var treasure := TowerBoard.new()
|
||||
treasure.id = "treasure"
|
||||
treasure.name = "Treasure"
|
||||
treasure.load_dict({"tables": [
|
||||
{"id": "loot", "name": "Loot", "entries": [{"id": "l1", "text": "A [[Gem]] worth gold", "effects": "@gold += 10"}]},
|
||||
{"id": "gem", "name": "Gem", "entries": [{"id": "g1", "text": "ruby"}]},
|
||||
]})
|
||||
var dungeon := TowerBoard.new()
|
||||
dungeon.id = "dungeon"
|
||||
dungeon.name = "Dungeon"
|
||||
dungeon.load_dict({"tables": [
|
||||
{"id": "room", "name": "Room", "entries": [{"id": "r1", "text": "A chest: [[Treasure::Loot]]"}]},
|
||||
{"id": "lost", "name": "Lost", "entries": [{"id": "x1", "text": "[[Nowhere::Loot]] and [[Treasure::Nothing]]"}]},
|
||||
]})
|
||||
SpreadLinks.loader = func(key: String) -> TowerBoard:
|
||||
return treasure if key.to_lower() in ["treasure", "treasure"] else null
|
||||
_eq(Roller.resolve(dungeon, "Treasure::Loot"), "treasure::loot", "a link resolves to the other spread's card")
|
||||
_check(Roller.ref_targets(dungeon, "[[Treasure::Loot]]").is_empty(), "links draw no reference line on this spread")
|
||||
var ctx := Roller.new_context(dungeon, RandomNumberGenerator.new(), {"gold": {"value": 1}})
|
||||
var tree: Dictionary = await Roller.roll_async(dungeon, "room", ctx)
|
||||
_eq(Formatter.strip_tags(str(tree["summary"])), "A chest: A ruby worth gold", "the other spread's card rolls, with its own references")
|
||||
_eq(int(ctx.lookup("@gold")), 11, "its changes land on this spread's values")
|
||||
_check(ctx.board == dungeon, "the roll ends back on this spread")
|
||||
var linked: Dictionary = (tree["children"] as Array)[0]
|
||||
_check(linked.get("spread") == "Treasure" and ((linked["children"] as Array)[0] as Dictionary).get("spread") == "Treasure", "every node from there is marked with its spread")
|
||||
var sync_tree := Roller.roll(dungeon, "room", RandomNumberGenerator.new())
|
||||
_check(Formatter.strip_tags(str(sync_tree["summary"])).contains("ruby"), "headless rolls follow links too")
|
||||
var lost := Roller.roll(dungeon, "lost", RandomNumberGenerator.new())
|
||||
_check(str(lost["summary"]).contains("missing:"), "a missing spread or card shows the missing marker")
|
||||
SpreadLinks.loader = Callable()
|
||||
finish()
|
||||
1
tests/test_spread_links.gd.uid
Normal file
1
tests/test_spread_links.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dsmnft4015lrf
|
||||
|
|
@ -55,8 +55,15 @@ func _test_library() -> void:
|
|||
_check(lib.rename("fantasy-loot", "Dark Loot"), "rename succeeds")
|
||||
_check(lib.load_collection("fantasy-loot").name == "Dark Loot", "rename keeps id, changes name")
|
||||
|
||||
var dark := lib.load_collection("fantasy-loot")
|
||||
CollectionSwitcher.set_folder(lib, dark, " Campaign ")
|
||||
_eq(lib.load_collection("fantasy-loot").folder, "Campaign", "a spread can be put in a folder (saved, trimmed)")
|
||||
_check(lib.list().any(func(entry: Dictionary) -> bool: return entry["folder"] == "Campaign"), "the library lists its folder")
|
||||
var copy := lib.duplicate("fantasy-loot", "Dark Loot Copy")
|
||||
_check(copy != null and copy.id == "dark-loot-copy" and copy.tables.size() == a.tables.size(), "duplicate copies tables")
|
||||
_eq(copy.folder, "Campaign", "a copy stays in the same folder")
|
||||
CollectionSwitcher.set_folder(lib, copy, "")
|
||||
_eq(lib.load_collection("dark-loot-copy").folder, "", "an empty folder takes it out again")
|
||||
var names: Array = []
|
||||
for e in lib.list():
|
||||
names.append(e["name"])
|
||||
|
|
@ -152,7 +159,7 @@ func _test_state() -> void:
|
|||
st.set_variable("c1", "weapon", "Dagger", "t1")
|
||||
st.set_variable("c1", "armor", "Plate", "t2")
|
||||
st.set_setting("last_collection", "c1")
|
||||
for i in 60:
|
||||
for i in StateStore.HISTORY_CAP + 10:
|
||||
st.add_history({"collection": "c1", "n": i})
|
||||
_check(st.is_dirty(), "mutation sets dirty")
|
||||
_check(st.save() and not st.is_dirty(), "save clears dirty")
|
||||
|
|
@ -165,8 +172,9 @@ func _test_state() -> void:
|
|||
_check(st2.get_variables("c1")["weapon"] == {"value": "Dagger", "source": "t1"}, "variable round trip")
|
||||
_check(st2.get_setting("last_collection") == "c1" and st2.get_setting("none", "d") == "d", "settings round trip")
|
||||
var h := st2.get_history()
|
||||
_check(h.size() == StateStore.HISTORY_CAP, "history capped at 50 (got %d)" % h.size())
|
||||
_check(h[0]["n"] == 59.0 and h[49]["n"] == 10.0, "history is most recent first")
|
||||
_check(h.size() == StateStore.HISTORY_CAP, "history capped at HISTORY_CAP (got %d)" % h.size())
|
||||
var last := StateStore.HISTORY_CAP - 1
|
||||
_check(h[0]["n"] == float(last + 10) and h[last]["n"] == 10.0, "history is most recent first")
|
||||
|
||||
st2.clear_variable("c1", "weapon")
|
||||
_check(not st2.get_variables("c1").has("weapon") and st2.get_variables("c1").has("armor"), "clear one variable")
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ var _rolls: Dictionary = {}
|
|||
func _init() -> void:
|
||||
_test_expander()
|
||||
_test_formatter()
|
||||
_test_format_menu()
|
||||
finish()
|
||||
|
||||
|
||||
|
|
@ -206,3 +207,25 @@ func _test_formatter() -> void:
|
|||
|
||||
_eq(RollContext.normalize_name(" [b]Gems[/b] "), "gems", "normalize_name")
|
||||
|
||||
|
||||
## Right-click formatting and the app's own text effects.
|
||||
func _test_format_menu() -> void:
|
||||
var line := LineEdit.new()
|
||||
line.text = "A legendary sword"
|
||||
FormatMenu.attach(line)
|
||||
var menu := line.get_menu()
|
||||
var labels: Array[String] = []
|
||||
for i in menu.item_count:
|
||||
labels.append(menu.get_item_text(i))
|
||||
_check(labels.has("Bold") and labels.has("Effect"), "a text field's right-click menu has Bold and Effect: %s" % ", ".join(labels))
|
||||
var changed := []
|
||||
line.text_changed.connect(func(text: String) -> void: changed.append(text))
|
||||
line.select(2, 11)
|
||||
FormatMenu.wrap_selection(line, "[sparkle]", "[/sparkle]")
|
||||
_eq(line.text, "A [sparkle]legendary[/sparkle] sword", "it wraps the selected words")
|
||||
_eq(changed.size(), 1, "and tells the field's listeners")
|
||||
_eq(Formatter.strip_tags(line.text), "A legendary sword", "the app's own effects count as tags (stripped from plain text)")
|
||||
var label := RichText.label("[shimmer]Rare[/shimmer]", 15, Color.WHITE, false)
|
||||
_eq(label.get_parsed_text(), "Rare", "a label draws the shimmer effect instead of showing its tag")
|
||||
label.free()
|
||||
line.free()
|
||||
|
|
|
|||
|
|
@ -74,6 +74,7 @@ func _test_dialog() -> void:
|
|||
main.add_child(d)
|
||||
await _frames()
|
||||
_check(d._content.find_children("*", "FillEditor", true, false).size() == 2, "background and panel fill editors")
|
||||
_check(bool(d._work.get("builtin", false)) and not d._delete_button.visible, "a built-in theme doesn't offer Delete")
|
||||
var basic := d._content.find_children("*", "ColorPickerButton", true, false).size()
|
||||
d._more = true
|
||||
d._rebuild()
|
||||
|
|
|
|||
|
|
@ -78,6 +78,10 @@ func _test_frames_and_threads() -> void:
|
|||
if FrameSet.active and FrameSet.active.corner_fixed:
|
||||
var frame := CardFrame.new()
|
||||
_check(frame._fixed != null, "%s: fixed corner pieces get their own layer" % theme_set["id"])
|
||||
main.add_child(frame)
|
||||
frame.size = Vector2(300, 200)
|
||||
frame.size = Vector2(420, 260)
|
||||
_check(frame._fixed.size == frame.size, "%s: the corner layer follows the frame's size (so it redraws on resize)" % theme_set["id"])
|
||||
frame.free()
|
||||
if ThreadStrip.active:
|
||||
var rid := RenderingServer.canvas_item_create()
|
||||
|
|
@ -101,3 +105,14 @@ func _test_sounds() -> void:
|
|||
_check(not playing, "nothing plays when the sound is off")
|
||||
main.sound.set_volume(SoundBoard.DEFAULT_VOLUME)
|
||||
_eq(main.sound.level_name(), "Quiet", "the default level is Quiet")
|
||||
var panel := SoundPanel.open(main, Vector2(40, 40))
|
||||
var sliders := panel.find_children("*", "HSlider", true, false)
|
||||
_check(sliders.size() == 1 and is_equal_approx((sliders[0] as HSlider).value, SoundBoard.DEFAULT_VOLUME * 100.0), "Sound… opens a slider at the current volume")
|
||||
(sliders[0] as HSlider).value = 65
|
||||
_check(is_equal_approx(main.sound.volume, 0.65), "moving the slider changes the volume")
|
||||
panel.hide()
|
||||
main.sound.set_volume(SoundBoard.DEFAULT_VOLUME)
|
||||
var view_items: Array[String] = []
|
||||
for i in main.top_bar.view_menu.get_popup().item_count:
|
||||
view_items.append(main.top_bar.view_menu.get_popup().get_item_text(i))
|
||||
_check(view_items.has("Sound…"), "View ▾ has Sound…")
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080"><defs><radialGradient id="gothic_vignette" cx="0.5" cy="0.5" r="0.5" fx="0.5" fy="0.5"><stop offset="0.4" stop-color="#030909" stop-opacity="0"/><stop offset="1" stop-color="#030909" stop-opacity="1"/></radialGradient><linearGradient id="gothic_window" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#65060e" stop-opacity="1"/><stop offset="1" stop-color="#65060e" stop-opacity="0"/></linearGradient></defs><rect x="-384" y="-432" width="2688" height="1728" fill="url(#gothic_vignette)"/><path d="M940 360 V80 A120 120 0 0 1 1180 80 V360 Z" fill="url(#gothic_window)" opacity=".5"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080"><defs><radialGradient id="gothic_vignette" cx="0.5" cy="0.5" r="0.5" fx="0.5" fy="0.5"><stop offset="0.4" stop-color="#030909" stop-opacity="0"/><stop offset="1" stop-color="#030909" stop-opacity="1"/></radialGradient></defs><rect x="-384" y="-432" width="2688" height="1728" fill="url(#gothic_vignette)"/></svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 690 B After Width: | Height: | Size: 404 B |
|
|
@ -10,7 +10,7 @@ const DATA := {
|
|||
"logo": "fortune_teller",
|
||||
"card_frame": "art",
|
||||
"font_body": "imfell",
|
||||
"font_display": "unifraktur",
|
||||
"font_display": "imfellsc",
|
||||
"background": {
|
||||
"kind": "radial",
|
||||
"colors": [
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ const DATA := {
|
|||
"logo": "fortune_teller",
|
||||
"card_frame": "art",
|
||||
"font_body": "imfell",
|
||||
"font_display": "uncial",
|
||||
"font_display": "alegreya",
|
||||
"background": {
|
||||
"kind": "radial",
|
||||
"colors": [
|
||||
|
|
|
|||
|
|
@ -96,7 +96,7 @@ def aero_scene(scene):
|
|||
f'stroke-width="3" opacity=".45"/>')
|
||||
return defs, in_spread_space(body, 180), "bottom"
|
||||
|
||||
|
||||
"""Dark edges (a vignette)."""
|
||||
def vignette_scene(scene):
|
||||
"""Dark edges and a faint red arched window glow at the top."""
|
||||
# CSS radial-gradient(70% 80% at 50% 40%, transparent 40%, s1): radii are 70% / 80% of the scene.
|
||||
|
|
@ -104,8 +104,8 @@ def vignette_scene(scene):
|
|||
defs = radial_gradient("gothic_vignette", [(0.4, scene["s1"], 0), (1, scene["s1"], 1)])
|
||||
body = (f'<rect x="{num(centre[0] - radii[0])}" y="{num(centre[1] - radii[1])}" width="{num(radii[0] * 2)}" '
|
||||
f'height="{num(radii[1] * 2)}" fill="url(#gothic_vignette)"/>')
|
||||
defs += vertical_gradient("gothic_window", [(0, scene["s2"], 1), (1, scene["s2"], 0)])
|
||||
body += '<path d="M940 360 V80 A120 120 0 0 1 1180 80 V360 Z" fill="url(#gothic_window)" opacity=".5"/>'
|
||||
# The red arch "window glow" read as a stray red patch (playtest 2026-11-14),
|
||||
# so the stand-in is the vignette alone; a real window is the user's art.
|
||||
return defs, body, "center"
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -88,7 +88,7 @@ THEMES = {
|
|||
"overrides": {"ON_BG_MUTED": "#3e6688"},
|
||||
},
|
||||
"gothic": {
|
||||
"name": "Gothic", "fonts": ("imfell", "unifraktur"),
|
||||
"name": "Gothic", "fonts": ("imfell", "imfellsc"),
|
||||
"background": {"kind": "radial", "colors": ["#223330", "#1b2826", "#081919"], "center": [0.5, 0.4]},
|
||||
"panel": {"kind": "solid", "colors": ["#060f0f"]},
|
||||
"colors": {"bg": "#1b2826", "onp": "#d9d4cc", "onpm": "#8f8a82", "card": "#d8d3c8", "card2": "#e2ddd3",
|
||||
|
|
@ -180,7 +180,7 @@ THEMES = {
|
|||
"overrides": {},
|
||||
},
|
||||
"map": {
|
||||
"name": "Cartographer", "fonts": ("imfell", "uncial"),
|
||||
"name": "Cartographer", "fonts": ("imfell", "alegreya"),
|
||||
"background": {"kind": "radial", "colors": ["#f0e2bf", "#dcc391"], "center": [0.5, 0.4]},
|
||||
# Deeper parchment, so the dark ink text reads on it and on the page.
|
||||
"panel": {"kind": "linear", "colors": ["#e3cf9f", "#cdb47e"], "angle": 90},
|
||||
|
|
|
|||
|
|
@ -66,11 +66,17 @@ static func popup_at(host: Control, list: Array, at: Vector2) -> PopupMenu:
|
|||
return pm
|
||||
|
||||
|
||||
## A "Colour ▸" submenu: Theme plus the ColorChoice presets.
|
||||
static func colours(current: String, on_pick: Callable) -> Dictionary:
|
||||
var sub: Array = [{"text": ("✓ " if current == "" else "") + "Theme colour", "do": on_pick.bind("")}]
|
||||
## A "Colour ▸" submenu: the default (`default_label`), the ColorChoice
|
||||
## presets and, with `m`, "Any colour…" (a full colour picker).
|
||||
static func colours(current: String, on_pick: Callable, m: Main = null, default_label: String = "Theme colour") -> Dictionary:
|
||||
var sub: Array = [{"text": ("✓ " if current == "" else "") + default_label, "do": on_pick.bind("")}]
|
||||
var matched := current == ""
|
||||
for p: Array in ColorChoice.PRESETS:
|
||||
sub.append({"text": ("✓ " if current.to_lower() == str(p[1]) else "") + str(p[0]), "do": on_pick.bind(str(p[1]))})
|
||||
var on := current.to_lower() == str(p[1])
|
||||
matched = matched or on
|
||||
sub.append({"text": ("✓ " if on else "") + str(p[0]), "do": on_pick.bind(str(p[1]))})
|
||||
if m:
|
||||
sub.append({"text": ("✓ " if not matched else "") + "Any colour…", "do": func() -> void: ColourDialog.open(m, current, on_pick)})
|
||||
return {"text": "Colour", "tip": COLOUR_TIP, "sub": sub}
|
||||
|
||||
|
||||
|
|
@ -91,7 +97,7 @@ static func card(m: Main, t: RollTable) -> Array:
|
|||
if build:
|
||||
list.append({"sep": ""})
|
||||
list.append({"text": "Table settings…", "do": m.request_table_settings.bind(t.id)})
|
||||
list.append(colours(t.color, func(hex: String) -> void: set_card_colour(m, t, hex)))
|
||||
list.append(colours(t.color, func(hex: String) -> void: set_card_colour(m, t, hex), m))
|
||||
list.append({"text": "Save as template…", "do": m.save_template_from.bind([t.id], "card")})
|
||||
list.append({"sep": ""})
|
||||
list.append({"text": "Delete table", "do": m.delete_table.bind(t.id)})
|
||||
|
|
@ -137,7 +143,7 @@ static func thread(m: Main, key: String) -> Array:
|
|||
e.pipe_color[to] = hex
|
||||
m.mark_dirty()
|
||||
m.board.geometry_rev += 1
|
||||
m.undo_redo._end_edit()))
|
||||
m.undo_redo._end_edit(), m))
|
||||
list.append({"sep": ""})
|
||||
list.append({"text": "Delete thread", "do": m.remove_pipe.bind(key)})
|
||||
return list
|
||||
|
|
@ -147,7 +153,7 @@ static func group(m: Main, g: TableGroup) -> Array:
|
|||
var list: Array = [{"text": "Expand" if g.collapsed else "Collapse", "do": m.toggle_group.bind(g.id)}]
|
||||
if m.mode == Main.Mode.BUILD:
|
||||
list.append({"text": "Details…", "do": m.edit_group_details.bind(g.id)})
|
||||
list.append(colours(g.color, func(hex: String) -> void: set_group_colour(m, g, hex)))
|
||||
list.append(colours(g.color, func(hex: String) -> void: set_group_colour(m, g, hex), m, "Default (blue)"))
|
||||
list.append({"text": "Save as template…", "do": m.save_template_from.bind([], "group", [g.id])})
|
||||
list.append({"sep": ""})
|
||||
list.append({"text": "Ungroup (keep the cards)", "do": m.ungroup.bind(g.id)})
|
||||
|
|
@ -181,11 +187,8 @@ static func background(m: Main, at: Vector2) -> Array:
|
|||
list.append({"sep": ""})
|
||||
list.append({"text": "Theme…", "do": func() -> void: m.add_child(ThemeDialog.new(m))})
|
||||
if m.sound:
|
||||
var levels := []
|
||||
for level: Array in SoundBoard.LEVELS:
|
||||
var mark := "✓ " if m.sound.level_name() == level[0] else " "
|
||||
levels.append({"text": mark + str(level[0]), "do": m.sound.set_volume.bind(float(level[1]))})
|
||||
list.append({"text": "Sound", "sub": levels, "tip": "How loud the theme's sounds are"})
|
||||
list.append({"text": "Sound…", "do": func() -> void: SoundPanel.open(m, m.get_global_mouse_position()),
|
||||
"tip": "How loud the theme's sounds are"})
|
||||
if m.mobile:
|
||||
# The phone layout has no room for these on the bar.
|
||||
var build := m.mode == Main.Mode.BUILD
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@ extends RefCounted
|
|||
## Batches: roll a card's whole chain several times ("5 NPCs") and get every
|
||||
## result at the end, in one window with Copy all. Questions on the way are
|
||||
## asked each time. Values and decks change as they would for single rolls.
|
||||
## Each roll goes into the tray's Earlier list (and the saved history), and
|
||||
## the batch plays one roll sound.
|
||||
|
||||
const MAX := 100
|
||||
|
||||
|
|
@ -24,6 +26,9 @@ static func ask(m: Main, tid: String) -> void:
|
|||
static func run(m: Main, tid: String, n: int) -> Array[String]:
|
||||
var t := m.data.get_table(tid)
|
||||
var texts: Array[String] = []
|
||||
if m.sound:
|
||||
m.sound.play("roll")
|
||||
m.rolling._archive_current()
|
||||
for i in n:
|
||||
var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, m.decks)
|
||||
ctx.prompt = m.prompt_hook
|
||||
|
|
@ -32,6 +37,11 @@ static func run(m: Main, tid: String, n: int) -> Array[String]:
|
|||
break
|
||||
var steps := Roller.flatten(tree, [])
|
||||
texts.append(m.rolling.result_text(steps, ResultTray.COPY_TEXT))
|
||||
var rec := {"collection": m.data.id, "root": tid, "root_name": t.name, "time": Time.get_unix_time_from_system(),
|
||||
"steps": steps, "all": steps, "done": true, "archived": true, "batch": "%d of %d" % [i + 1, n]}
|
||||
m.history.push_front(rec)
|
||||
if m.history.size() > Main.HISTORY_SIZE:
|
||||
m.history.resize(Main.HISTORY_SIZE)
|
||||
if m.state:
|
||||
m.local_state._store_decks()
|
||||
if ctx.persistent_changed:
|
||||
|
|
@ -41,6 +51,7 @@ static func run(m: Main, tid: String, n: int) -> Array[String]:
|
|||
if m.state:
|
||||
m.state.save()
|
||||
m.refresh_live()
|
||||
m.tray.render()
|
||||
if not texts.is_empty():
|
||||
m._add_modal(dialog(t, texts))
|
||||
return texts
|
||||
|
|
|
|||
|
|
@ -89,6 +89,15 @@ func refresh() -> void:
|
|||
editor.show_page(null)
|
||||
|
||||
|
||||
## After undo or redo: the page in the editor is shown again from the
|
||||
## restored spread, so its fields show the undone text at once.
|
||||
func reload_page() -> void:
|
||||
if editor == null or editor.page == null:
|
||||
return
|
||||
editor.show_page(m.data.get_page(editor.page.id))
|
||||
refresh()
|
||||
|
||||
|
||||
func set_width(px: float) -> void:
|
||||
custom_minimum_size.x = px
|
||||
|
||||
|
|
|
|||
|
|
@ -22,8 +22,12 @@ func _init() -> void:
|
|||
_fixed.use_parent_material = false
|
||||
_fixed.texture_filter = TEXTURE_FILTER_LINEAR_WITH_MIPMAPS
|
||||
_fixed.draw.connect(_draw_fixed)
|
||||
# It must follow the frame's size: a Control only redraws itself when
|
||||
# its own size changes, so a zero-size layer kept the old corners.
|
||||
_fixed.set_anchors_preset(Control.PRESET_FULL_RECT)
|
||||
add_child(_fixed)
|
||||
set_trim(Color(0, 0, 0, 0))
|
||||
item_rect_changed.connect(_on_rect_changed)
|
||||
|
||||
|
||||
## Recolours the frame; a transparent colour means the theme's TRIM.
|
||||
|
|
@ -39,6 +43,14 @@ static func material_for(trim: Color) -> ShaderMaterial:
|
|||
return (FrameSet.active if FrameSet.active else FrameSet.beaded()).material_for(trim)
|
||||
|
||||
|
||||
## The frame is drawn around the card's rectangle, so a move inside the card
|
||||
## (new margins) or a resize redraws both layers.
|
||||
func _on_rect_changed() -> void:
|
||||
queue_redraw()
|
||||
if _fixed:
|
||||
_fixed.queue_redraw()
|
||||
|
||||
|
||||
func _frame_rect() -> Rect2:
|
||||
var host := get_parent() as Control
|
||||
return Rect2(-position, host.size).grow(FrameSet.active.outset)
|
||||
|
|
|
|||
|
|
@ -138,7 +138,7 @@ func preview_for_option(k: int) -> Control:
|
|||
var mentioned: Array[String] = []
|
||||
for name in TextExpander.references(e.text, func(n: String) -> String: return Roller.resolve(d.board, n)):
|
||||
var rid := Roller.resolve(d.board, name)
|
||||
if rid != "" and not shown.has(rid) and not mentioned.has(rid):
|
||||
if rid != "" and not SpreadLinks.is_link(rid) and not shown.has(rid) and not mentioned.has(rid):
|
||||
mentioned.append(rid)
|
||||
if not mentioned.is_empty():
|
||||
any = true
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
class_name CollectionSwitcher
|
||||
extends MenuButton
|
||||
## Top-bar dropdown that names the current collection and offers switching,
|
||||
## New, Rename, Duplicate and Delete. The storage rules are static functions
|
||||
## New, Rename, Duplicate, Move to folder and Delete. Spreads in a folder are
|
||||
## listed in that folder's submenu. The storage rules are static functions
|
||||
## (create_collection and friends) so tests can run them on a temporary
|
||||
## LibraryStore; Main does the UI side (rebuilding cards, dialogs).
|
||||
|
||||
|
|
@ -9,6 +10,7 @@ const ID_NEW := 1000
|
|||
const ID_RENAME := 1001
|
||||
const ID_DUPLICATE := 1002
|
||||
const ID_DELETE := 1003
|
||||
const ID_FOLDER := 1004
|
||||
const MAX_LABEL := 22
|
||||
|
||||
var main: Main
|
||||
|
|
@ -30,7 +32,8 @@ func setup(p_main: Main) -> void:
|
|||
func refresh() -> void:
|
||||
var n := main.data.name if main.data.name != "" else "Untitled"
|
||||
text = "%s ▾" % (n if n.length() <= MAX_LABEL else n.substr(0, MAX_LABEL - 1) + "…")
|
||||
tooltip_text = "Spread: %s" % n
|
||||
var where := " (in %s)" % main.data.folder if main.data.folder != "" else ""
|
||||
tooltip_text = "%s%s · %d cards\nSwitch spreads, or make, rename, copy, sort into folders or delete one" % [n, where, main.data.tables.size()]
|
||||
|
||||
|
||||
func _fill() -> void:
|
||||
|
|
@ -38,12 +41,31 @@ func _fill() -> void:
|
|||
pm.clear()
|
||||
_ids.clear()
|
||||
var can := main.collections_enabled()
|
||||
for child in pm.get_children():
|
||||
if child is PopupMenu:
|
||||
pm.remove_child(child)
|
||||
child.queue_free()
|
||||
if can:
|
||||
var folders := {}
|
||||
for entry in main.library.list():
|
||||
var id := str(entry["id"])
|
||||
var current := id == main.data.id
|
||||
pm.add_item(("● " if current else " ") + str(entry["name"]), _ids.size())
|
||||
_ids.append(id)
|
||||
var folder := str(entry.get("folder", ""))
|
||||
if folder != "":
|
||||
if not folders.has(folder):
|
||||
folders[folder] = []
|
||||
(folders[folder] as Array).append(entry)
|
||||
continue
|
||||
_add_spread(pm, entry)
|
||||
var names: Array = folders.keys()
|
||||
names.sort_custom(func(left: String, right: String) -> bool: return left.naturalnocasecmp_to(right) < 0)
|
||||
for folder: String in names:
|
||||
var sub := PopupMenu.new()
|
||||
ModalCard.style_popup(sub)
|
||||
sub.id_pressed.connect(_on_id)
|
||||
var holds_current := false
|
||||
for entry: Dictionary in folders[folder]:
|
||||
_add_spread(sub, entry)
|
||||
holds_current = holds_current or str(entry["id"]) == main.data.id
|
||||
pm.add_submenu_node_item(("● " if holds_current else " ") + folder, sub)
|
||||
else:
|
||||
pm.add_item("● " + main.data.name, 0)
|
||||
pm.set_item_disabled(0, true)
|
||||
|
|
@ -52,9 +74,10 @@ func _fill() -> void:
|
|||
pm.add_item("New spread…", ID_NEW)
|
||||
pm.add_item("Rename…", ID_RENAME)
|
||||
pm.add_item("Duplicate", ID_DUPLICATE)
|
||||
pm.add_item("Move to folder…", ID_FOLDER)
|
||||
pm.add_item("Delete…", ID_DELETE)
|
||||
if not can:
|
||||
for id in [ID_NEW, ID_RENAME, ID_DUPLICATE, ID_DELETE]:
|
||||
for id in [ID_NEW, ID_RENAME, ID_DUPLICATE, ID_FOLDER, ID_DELETE]:
|
||||
pm.set_item_disabled(pm.get_item_index(id), true)
|
||||
pm.add_separator()
|
||||
pm.add_item("Saving is off in this session", -1)
|
||||
|
|
@ -67,13 +90,39 @@ func _on_id(id: int) -> void:
|
|||
ID_RENAME: main.rename_collection()
|
||||
ID_DUPLICATE: main.duplicate_collection()
|
||||
ID_DELETE: main.delete_collection()
|
||||
ID_FOLDER: _ask_folder()
|
||||
_:
|
||||
if id >= 0 and id < _ids.size() and _ids[id] != main.data.id:
|
||||
main.switch_collection(_ids[id])
|
||||
|
||||
|
||||
func _add_spread(menu: PopupMenu, entry: Dictionary) -> void:
|
||||
var id := str(entry["id"])
|
||||
menu.add_item(("● " if id == main.data.id else " ") + str(entry["name"]), _ids.size())
|
||||
_ids.append(id)
|
||||
|
||||
|
||||
## Asks for the folder to list the current spread under (empty = none).
|
||||
func _ask_folder() -> void:
|
||||
var known := {}
|
||||
for entry in main.library.list():
|
||||
if str(entry.get("folder", "")) != "":
|
||||
known[str(entry["folder"])] = true
|
||||
var prompt := "Folder (leave empty for none)"
|
||||
if not known.is_empty():
|
||||
prompt += ". Folders so far: " + ", ".join(known.keys())
|
||||
main._add_modal(ModalCard.ask_text("Move to folder", prompt, main.data.folder, "Move", func(folder: String) -> void:
|
||||
set_folder(main.library, main.data, folder)
|
||||
refresh(), true))
|
||||
|
||||
|
||||
# ---------- Storage rules (no UI) ----------
|
||||
|
||||
## Lists `current` under `folder` ("" = none) and saves it.
|
||||
static func set_folder(library: LibraryStore, current: TowerBoard, folder: String) -> void:
|
||||
current.folder = folder.strip_edges()
|
||||
library.save(current)
|
||||
|
||||
## Saves `current`, then makes and returns a new empty collection.
|
||||
static func create_collection(library: LibraryStore, current: TowerBoard, coll_name: String) -> TowerBoard:
|
||||
if current:
|
||||
|
|
|
|||
19
ui/colour_dialog.gd
Normal file
19
ui/colour_dialog.gd
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
class_name ColourDialog
|
||||
extends RefCounted
|
||||
## "Any colour…" from a right-click Colour menu: a pop-up with a full colour
|
||||
## picker (wheel, sliders and hex code). Choose calls `on_pick` with "#rrggbb".
|
||||
|
||||
|
||||
static func open(main: Main, start: String, on_pick: Callable) -> ModalCard:
|
||||
var dialog := ModalCard.new("Choose a colour", 360.0)
|
||||
var picker := ColorPicker.new()
|
||||
picker.edit_alpha = false
|
||||
picker.color = Color.from_string(start, GroupMark.DEFAULT_COLOR)
|
||||
picker.presets_visible = false
|
||||
dialog.body.add_child(picker)
|
||||
dialog.add_button("Cancel", "plain", dialog.close)
|
||||
dialog.add_button("Choose", "primary", func() -> void:
|
||||
dialog.close()
|
||||
on_pick.call("#" + picker.color.to_html(false)))
|
||||
main.add_child(dialog)
|
||||
return dialog
|
||||
1
ui/colour_dialog.gd.uid
Normal file
1
ui/colour_dialog.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://3cajehoxahyr
|
||||
85
ui/delete_key.gd
Normal file
85
ui/delete_key.gd
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
class_name DeleteKey
|
||||
extends RefCounted
|
||||
## The Delete key in Build mode: deletes what's selected (the selected cards
|
||||
## and groups, else the inspector's thread, result or card), as one undo step.
|
||||
## It asks "Are you sure?" first unless View ▾ → Ask before deleting is off
|
||||
## (the setting "confirm_delete", on by default).
|
||||
|
||||
const SETTING := "confirm_delete"
|
||||
## Used when saving is off (--sample / --screenshot) and there's no state.
|
||||
static var _asks_mem := true
|
||||
|
||||
|
||||
static func asks(m: Main) -> bool:
|
||||
return bool(m.state.get_setting(SETTING, true)) if m.state else _asks_mem
|
||||
|
||||
|
||||
static func set_asks(m: Main, on: bool) -> void:
|
||||
_asks_mem = on
|
||||
if m.state:
|
||||
m.state.set_setting(SETTING, on)
|
||||
m.state.save()
|
||||
|
||||
|
||||
## What the key would delete now: {"what": words for the question, "do":
|
||||
## Callable}, or {} when nothing is selected.
|
||||
static func target(m: Main) -> Dictionary:
|
||||
var cards: Array[String] = []
|
||||
for t in m.data.tables:
|
||||
if m.selection.has(t.id):
|
||||
cards.append(t.id)
|
||||
var groups: Array = m.selecting.groups.keys()
|
||||
if not cards.is_empty() or not groups.is_empty():
|
||||
var parts := PackedStringArray()
|
||||
if not cards.is_empty():
|
||||
parts.append(_name(m, cards[0]) if cards.size() == 1 else "%d cards" % cards.size())
|
||||
if not groups.is_empty():
|
||||
parts.append("%d %s and the cards in %s" % [groups.size(), "group" if groups.size() == 1 else "groups", "it" if groups.size() == 1 else "them"])
|
||||
return {"what": " and ".join(parts), "do": func() -> void: _delete_many(m, cards, groups)}
|
||||
var sel: Dictionary = m.inspector.selection if m.inspector else {}
|
||||
match str(sel.get("kind", "")):
|
||||
"pipe":
|
||||
var key := "%s:%s>%s" % [sel["tid"], sel["eid"], sel["to"]]
|
||||
return {"what": "the thread to %s" % _name(m, str(sel["to"])), "do": m.remove_pipe.bind(key)}
|
||||
"result":
|
||||
var t := m.data.get_table(str(sel["tid"]))
|
||||
var e := t.find_entry(str(sel["eid"])) if t else null
|
||||
if e:
|
||||
return {"what": "“%s”" % Formatter.strip_tags(e.text).strip_edges(), "do": m.delete_entry.bind(t.id, e.id)}
|
||||
"card":
|
||||
if m.data.get_table(str(sel["tid"])):
|
||||
return {"what": _name(m, str(sel["tid"])), "do": m.delete_table.bind(str(sel["tid"]))}
|
||||
return {}
|
||||
|
||||
|
||||
## Handles the key: asks first (unless turned off), then deletes.
|
||||
static func press(m: Main) -> void:
|
||||
var found := target(m)
|
||||
if found.is_empty():
|
||||
return
|
||||
if not asks(m):
|
||||
(found["do"] as Callable).call()
|
||||
return
|
||||
var dialog := ModalCard.confirm("Delete?", "Delete %s? You can undo it with Ctrl+Z." % found["what"], "Delete", found["do"], true)
|
||||
var dont_ask := InspectorKit.check_box("Don't ask again (View ▾ → Ask before deleting)", false)
|
||||
dont_ask.toggled.connect(func(on: bool) -> void: set_asks(m, not on))
|
||||
dialog.body.add_child(dont_ask)
|
||||
m._add_modal(dialog)
|
||||
|
||||
|
||||
static func _delete_many(m: Main, cards: Array[String], groups: Array) -> void:
|
||||
m.undo_redo._begin_edit()
|
||||
for gid: String in groups:
|
||||
m.grouping.delete_group(gid, false)
|
||||
for tid in cards:
|
||||
if m.data.get_table(tid):
|
||||
m.editing.delete_table(tid, false)
|
||||
m.selecting.clear()
|
||||
m.clear_selection()
|
||||
m.undo_redo._end_edit("Delete")
|
||||
m.toast("Deleted", true)
|
||||
|
||||
|
||||
static func _name(m: Main, tid: String) -> String:
|
||||
var t := m.data.get_table(tid)
|
||||
return Formatter.strip_tags(t.name).strip_edges() if t else "the card"
|
||||
1
ui/delete_key.gd.uid
Normal file
1
ui/delete_key.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dbtni4kflrep0
|
||||
|
|
@ -136,7 +136,7 @@ func _place() -> void:
|
|||
# ---------- Content ----------
|
||||
|
||||
func show_table(owner: Control, tid: String, only_if_details: bool = false) -> void:
|
||||
var t := main.data.get_table(tid) if main.data else null
|
||||
var t := SpreadLinks.card(tid) if SpreadLinks.is_link(tid) else (main.data.get_table(tid) if main.data else null)
|
||||
if t == null:
|
||||
return
|
||||
if only_if_details and t.details.strip_edges() == "":
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue