Compare commits
No commits in common. "6a873810b0ec63a0ac7d8131be00228f00d12ecf" and "60c2d03147e8c88a4d5a928e1b4c0a98c9c53072" have entirely different histories.
6a873810b0
...
60c2d03147
22 changed files with 61 additions and 1656 deletions
6
.gitignore
vendored
6
.gitignore
vendored
|
|
@ -11,9 +11,3 @@
|
|||
.DS_Store
|
||||
Thumbs.db
|
||||
.vscode/
|
||||
|
||||
# Temporary file written by tools/test_window.sh
|
||||
override.cfg
|
||||
|
||||
# Agent worktrees
|
||||
.claude/worktrees/
|
||||
|
|
|
|||
|
|
@ -51,10 +51,8 @@ godot --headless --path . -s res://tests/test_roller.gd
|
|||
## Screenshots from the command line
|
||||
|
||||
```sh
|
||||
tools/test_window.sh -- --screenshot=/tmp/board.png [--build] [--expand-all] [--collapse-all] \
|
||||
godot --path . -- --screenshot=/tmp/board.png [--build] [--expand-all] [--collapse-all] \
|
||||
[--roll=wilderness] [--shot-delay=0.75]
|
||||
```
|
||||
|
||||
This uses the sample board and doesn't save anything. `tools/test_window.sh` runs the game
|
||||
under the window class "TableTower Test" (via a temporary `override.cfg`), which a KWin
|
||||
window rule keeps in the background without focus.
|
||||
This uses the sample board and doesn't save anything.
|
||||
|
|
|
|||
|
|
@ -1,106 +0,0 @@
|
|||
class_name DeckState
|
||||
extends RefCounted
|
||||
## Which cards have been drawn from one card-mode table.
|
||||
##
|
||||
## Weighted tables treat an entry's weight as its number of copies. Ranged
|
||||
## tables treat each ranged entry as one card, drawn in proportion to the
|
||||
## probability of its range. State is kept per entry id, so edits behave:
|
||||
## deleted entries drop out, new entries start undrawn, raising a weight adds
|
||||
## copies.
|
||||
|
||||
## entry id -> number of copies drawn.
|
||||
var drawn: Dictionary = {}
|
||||
|
||||
|
||||
func to_dict() -> Dictionary:
|
||||
return {"drawn": drawn.duplicate()}
|
||||
|
||||
|
||||
static func from_dict(d: Dictionary) -> DeckState:
|
||||
var s := DeckState.new()
|
||||
var src: Variant = d.get("drawn", {})
|
||||
if src is Dictionary:
|
||||
for k: Variant in src:
|
||||
var n: int = int(src[k])
|
||||
if n > 0:
|
||||
s.drawn[str(k)] = n
|
||||
return s
|
||||
|
||||
|
||||
func reshuffle() -> void:
|
||||
drawn.clear()
|
||||
|
||||
|
||||
## Copies of this entry that are in the deck in total.
|
||||
static func copies_of(table: RollTable, e: TableEntry) -> int:
|
||||
if table.is_ranged():
|
||||
return 1 if e.has_range and table.chance(e) > 0.0 else 0
|
||||
return maxi(0, e.weight)
|
||||
|
||||
|
||||
func _remaining(table: RollTable, e: TableEntry) -> int:
|
||||
return maxi(0, copies_of(table, e) - int(drawn.get(e.id, 0)))
|
||||
|
||||
|
||||
## Vector2i(cards left, total cards) for the table as it is now.
|
||||
func cards_left(table: RollTable) -> Vector2i:
|
||||
var left := 0
|
||||
var total := 0
|
||||
for e in table.entries:
|
||||
total += copies_of(table, e)
|
||||
left += _remaining(table, e)
|
||||
return Vector2i(left, total)
|
||||
|
||||
|
||||
## Draws one card. Returns {"index": int, "value": int} or {} if nothing is left.
|
||||
func draw(table: RollTable, rng: RandomNumberGenerator) -> Dictionary:
|
||||
_prune(table)
|
||||
var weights: Array[float] = []
|
||||
var sum := 0.0
|
||||
for e in table.entries:
|
||||
var w := float(_remaining(table, e))
|
||||
if table.is_ranged():
|
||||
w *= table.chance(e)
|
||||
weights.append(w)
|
||||
sum += w
|
||||
if sum <= 0.0:
|
||||
return {}
|
||||
var pick := rng.randf() * sum
|
||||
var index := -1
|
||||
for i in weights.size():
|
||||
if weights[i] <= 0.0:
|
||||
continue
|
||||
index = i
|
||||
if pick < weights[i]:
|
||||
break
|
||||
pick -= weights[i]
|
||||
var chosen := table.entries[index]
|
||||
drawn[chosen.id] = int(drawn.get(chosen.id, 0)) + 1
|
||||
var value := index + 1
|
||||
if table.is_ranged():
|
||||
value = _value_in(table, chosen, rng)
|
||||
return {"index": index, "value": value}
|
||||
|
||||
|
||||
## A die value inside the entry's range, weighted by the dice distribution.
|
||||
func _value_in(table: RollTable, e: TableEntry, rng: RandomNumberGenerator) -> int:
|
||||
var dist := table.dice_obj().distribution()
|
||||
var vals: Array[int] = []
|
||||
var mass := 0.0
|
||||
for v in range(e.range_lo, e.range_hi + 1):
|
||||
if dist.has(v):
|
||||
vals.append(v)
|
||||
mass += float(dist[v])
|
||||
var pick := rng.randf() * mass
|
||||
for v in vals:
|
||||
pick -= float(dist[v])
|
||||
if pick < 0.0:
|
||||
return v
|
||||
return vals[vals.size() - 1]
|
||||
|
||||
|
||||
## Forgets draws for entries that no longer exist.
|
||||
func _prune(table: RollTable) -> void:
|
||||
for k: Variant in drawn.keys():
|
||||
if table.find_entry(str(k)) == null:
|
||||
drawn.erase(k)
|
||||
|
|
@ -1 +0,0 @@
|
|||
uid://dxnqme8pv84v4
|
||||
116
core/dice.gd
116
core/dice.gd
|
|
@ -1,116 +0,0 @@
|
|||
class_name Dice
|
||||
extends RefCounted
|
||||
## A dice expression such as "1d100", "2d6" or "1d8+2".
|
||||
##
|
||||
## Parse with Dice.parse(); check `valid` before use. Invalid expressions never
|
||||
## roll and have min/max of 0.
|
||||
|
||||
const MAX_COUNT := 20
|
||||
const MAX_SIDES := 1000
|
||||
const MAX_BONUS := 9999
|
||||
|
||||
var valid: bool = false
|
||||
var count: int = 1
|
||||
var sides: int = 100
|
||||
var bonus: int = 0
|
||||
|
||||
var _dist: Dictionary = {}
|
||||
|
||||
|
||||
## Parses "NdM", "dM", "NdM+K" or "NdM-K". Spaces and case are ignored.
|
||||
static func parse(text: String) -> Dice:
|
||||
var rx := RegEx.new()
|
||||
rx.compile("^(\\d*)d(\\d+)([+-]\\d+)?$")
|
||||
var m := rx.search(text.strip_edges().to_lower().replace(" ", ""))
|
||||
if m == null:
|
||||
var bad := Dice.new()
|
||||
return bad
|
||||
var n: int = m.get_string(1).to_int() if m.get_string(1) != "" else 1
|
||||
var k: int = m.get_string(3).to_int() if m.get_string(3) != "" else 0
|
||||
return Dice.make(n, m.get_string(2).to_int(), k)
|
||||
|
||||
|
||||
static func make(p_count: int, p_sides: int, p_bonus: int = 0) -> Dice:
|
||||
var d := Dice.new()
|
||||
d.count = p_count
|
||||
d.sides = p_sides
|
||||
d.bonus = p_bonus
|
||||
d.valid = p_count >= 1 and p_count <= MAX_COUNT and p_sides >= 2 and p_sides <= MAX_SIDES and absi(p_bonus) <= MAX_BONUS
|
||||
return d
|
||||
|
||||
|
||||
static func is_valid_text(text: String) -> bool:
|
||||
return parse(text).valid
|
||||
|
||||
|
||||
func min_value() -> int:
|
||||
return count + bonus if valid else 0
|
||||
|
||||
|
||||
func max_value() -> int:
|
||||
return count * sides + bonus if valid else 0
|
||||
|
||||
|
||||
## Normalized expression, e.g. "1d100", "2d6", "1d8+2".
|
||||
func expression() -> String:
|
||||
var s := "%dd%d" % [count, sides]
|
||||
if bonus > 0:
|
||||
s += "+%d" % bonus
|
||||
elif bonus < 0:
|
||||
s += str(bonus)
|
||||
return s
|
||||
|
||||
|
||||
## Short label: "d100" for a single die with no bonus, otherwise the expression.
|
||||
func label() -> String:
|
||||
return "d%d" % sides if count == 1 and bonus == 0 else expression()
|
||||
|
||||
|
||||
## True only for exactly 1d100.
|
||||
func is_d100() -> bool:
|
||||
return valid and count == 1 and sides == 100 and bonus == 0
|
||||
|
||||
|
||||
func roll(rng: RandomNumberGenerator) -> int:
|
||||
if not valid:
|
||||
return 0
|
||||
var total := bonus
|
||||
for i in count:
|
||||
total += rng.randi_range(1, sides)
|
||||
return total
|
||||
|
||||
|
||||
## Exact probability of every total: value -> probability (sums to 1).
|
||||
func distribution() -> Dictionary:
|
||||
if not valid:
|
||||
return {}
|
||||
if not _dist.is_empty():
|
||||
return _dist
|
||||
# cur[i] = probability of total (count_so_far + i); each die is a sliding-window sum.
|
||||
var cur := PackedFloat64Array([1.0])
|
||||
var face := 1.0 / float(sides)
|
||||
for k in count:
|
||||
var next := PackedFloat64Array()
|
||||
next.resize(cur.size() + sides - 1)
|
||||
var run := 0.0
|
||||
for i in next.size():
|
||||
if i < cur.size():
|
||||
run += cur[i]
|
||||
if i >= sides:
|
||||
run -= cur[i - sides]
|
||||
next[i] = run * face
|
||||
cur = next
|
||||
var lo := count + bonus
|
||||
for i in cur.size():
|
||||
_dist[lo + i] = cur[i]
|
||||
return _dist
|
||||
|
||||
|
||||
## Probability that the total falls within lo..hi inclusive.
|
||||
func probability_between(lo: int, hi: int) -> float:
|
||||
var sum := 0.0
|
||||
var dist := distribution()
|
||||
for v: int in dist:
|
||||
if v >= lo and v <= hi:
|
||||
sum += float(dist[v])
|
||||
return sum
|
||||
|
|
@ -1 +0,0 @@
|
|||
uid://oqwt4gld3dfa
|
||||
|
|
@ -1,176 +0,0 @@
|
|||
class_name LibraryStore
|
||||
extends RefCounted
|
||||
## The saved collections: one JSON file per collection in <root>/collections/.
|
||||
## The file name is the collection id. Local state (decks, variables, history)
|
||||
## lives in the paired StateStore and is dropped when a collection is deleted.
|
||||
|
||||
const LEGACY_NAME := "My Tables"
|
||||
|
||||
## Folder that contains collections/. Default user://.
|
||||
var root: String
|
||||
var state: StateStore
|
||||
## Messages about files that couldn't be read or written (most recent last).
|
||||
var errors: PackedStringArray = []
|
||||
|
||||
|
||||
func _init(p_root: String = "user://", p_state: StateStore = null) -> void:
|
||||
root = p_root
|
||||
state = p_state if p_state else StateStore.new(p_root)
|
||||
|
||||
|
||||
func collections_dir() -> String:
|
||||
return root.path_join("collections")
|
||||
|
||||
|
||||
func path_for(id: String) -> String:
|
||||
return collections_dir().path_join(id + ".json")
|
||||
|
||||
|
||||
## True for ids that are safe to use as a file name.
|
||||
static func is_valid_id(id: String) -> bool:
|
||||
if id == "":
|
||||
return false
|
||||
for c in id:
|
||||
if not (c in "abcdefghijklmnopqrstuvwxyz0123456789-_"):
|
||||
return false
|
||||
return true
|
||||
|
||||
|
||||
## Lowercase letters, digits and dashes; "collection" if nothing is left.
|
||||
static func slugify(text: String) -> String:
|
||||
var out := ""
|
||||
for c in text.to_lower():
|
||||
if c in "abcdefghijklmnopqrstuvwxyz0123456789":
|
||||
out += c
|
||||
elif not out.ends_with("-"):
|
||||
out += "-"
|
||||
out = out.trim_prefix("-").trim_suffix("-")
|
||||
return out if out != "" else "collection"
|
||||
|
||||
|
||||
func exists(id: String) -> bool:
|
||||
return is_valid_id(id) and FileAccess.file_exists(path_for(id))
|
||||
|
||||
|
||||
## [{id, name}] sorted by name. Unreadable files are skipped and noted in errors.
|
||||
func list() -> Array[Dictionary]:
|
||||
var out: Array[Dictionary] = []
|
||||
var dir := DirAccess.open(collections_dir())
|
||||
if dir == null:
|
||||
return out
|
||||
for fname in dir.get_files():
|
||||
if fname.get_extension() != "json":
|
||||
continue
|
||||
var id := fname.get_basename()
|
||||
if not is_valid_id(id):
|
||||
continue
|
||||
var b := load_collection(id)
|
||||
if b:
|
||||
out.append({"id": id, "name": b.name})
|
||||
out.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
|
||||
return str(a["name"]).naturalnocasecmp_to(str(b["name"])) < 0)
|
||||
return out
|
||||
|
||||
|
||||
## Loads a collection, or returns null (and records why in errors) if it's
|
||||
## missing or unreadable. The id always comes from the file name.
|
||||
func load_collection(id: String) -> TowerBoard:
|
||||
if not exists(id):
|
||||
return _fail("No collection '%s'." % id)
|
||||
var b := TowerBoard.new()
|
||||
if not b.load_json(FileAccess.get_file_as_string(path_for(id))):
|
||||
return _fail("Collection file %s is unreadable or not a collection." % path_for(id))
|
||||
b.id = id
|
||||
if b.name == "":
|
||||
b.name = id
|
||||
return b
|
||||
|
||||
|
||||
## Saves a collection under its id. Returns false (and records why) on failure.
|
||||
func save(board: TowerBoard) -> bool:
|
||||
if not is_valid_id(board.id):
|
||||
_fail("Can't save a collection with id '%s'." % board.id)
|
||||
return false
|
||||
var err := TowerBoard.write_text_atomic(path_for(board.id), board.to_json())
|
||||
if err != OK:
|
||||
_fail("Couldn't save %s: %s" % [path_for(board.id), error_string(err)])
|
||||
return false
|
||||
return true
|
||||
|
||||
|
||||
## Makes and saves an empty collection with a unique id taken from the name.
|
||||
func create(coll_name: String) -> TowerBoard:
|
||||
var b := TowerBoard.new()
|
||||
b.name = coll_name.strip_edges() if coll_name.strip_edges() != "" else "Untitled"
|
||||
b.id = unique_id(slugify(b.name))
|
||||
save(b)
|
||||
return b
|
||||
|
||||
|
||||
## Changes the display name only; the id (and so the file and state) stays.
|
||||
func rename(id: String, new_name: String) -> bool:
|
||||
var b := load_collection(id)
|
||||
if b == null or new_name.strip_edges() == "":
|
||||
return false
|
||||
b.name = new_name.strip_edges()
|
||||
return save(b)
|
||||
|
||||
|
||||
## Copies a collection (tables only; local state isn't copied). Returns the copy or null.
|
||||
func duplicate(id: String, new_name: String) -> TowerBoard:
|
||||
var b := load_collection(id)
|
||||
if b == null:
|
||||
return null
|
||||
b.name = new_name.strip_edges() if new_name.strip_edges() != "" else b.name + " copy"
|
||||
b.id = unique_id(slugify(b.name))
|
||||
return b if save(b) else null
|
||||
|
||||
|
||||
## Deletes the file and the collection's local state.
|
||||
func delete(id: String) -> bool:
|
||||
if not exists(id):
|
||||
return false
|
||||
if DirAccess.remove_absolute(path_for(id)) != OK:
|
||||
_fail("Couldn't delete %s." % path_for(id))
|
||||
return false
|
||||
state.forget_collection(id)
|
||||
state.save()
|
||||
return true
|
||||
|
||||
|
||||
## base, or base-2, base-3 ... whichever isn't taken.
|
||||
func unique_id(base: String) -> String:
|
||||
var id := base
|
||||
var n := 2
|
||||
while exists(id):
|
||||
id = "%s-%d" % [base, n]
|
||||
n += 1
|
||||
return id
|
||||
|
||||
|
||||
## First run: if the old single-board file exists and there are no collections,
|
||||
## imports it as a collection and renames the old file to board.json.bak.
|
||||
## Returns the imported collection, or null if nothing was migrated.
|
||||
func migrate_legacy(legacy_path: String = "") -> TowerBoard:
|
||||
if legacy_path == "":
|
||||
legacy_path = root.path_join("board.json")
|
||||
if not FileAccess.file_exists(legacy_path) or not list().is_empty():
|
||||
return null
|
||||
var b := TowerBoard.load_saved(legacy_path)
|
||||
if b == null:
|
||||
_fail("Old board file %s is unreadable; leaving it alone." % legacy_path)
|
||||
return null
|
||||
b.name = LEGACY_NAME
|
||||
b.id = unique_id(slugify(LEGACY_NAME))
|
||||
if not save(b):
|
||||
return null
|
||||
DirAccess.remove_absolute(legacy_path + ".bak")
|
||||
if DirAccess.rename_absolute(legacy_path, legacy_path + ".bak") != OK:
|
||||
_fail("Imported %s but couldn't rename it to .bak." % legacy_path)
|
||||
return b
|
||||
|
||||
|
||||
func _fail(message: String) -> TowerBoard:
|
||||
errors.append(message)
|
||||
push_warning(message)
|
||||
return null
|
||||
|
|
@ -1 +0,0 @@
|
|||
uid://c0pij64vq2ydy
|
||||
|
|
@ -2,30 +2,18 @@ class_name RollTable
|
|||
extends RefCounted
|
||||
## A named list of entries placed on the board.
|
||||
##
|
||||
## Plain tables pick by entry weight (6 equal entries = d6). If any entry has a
|
||||
## range, the table becomes a ranged dice table (1d100 by default, or any dice
|
||||
## expression) where the probability mass of each range sets its chance.
|
||||
|
||||
const DEFAULT_DICE := "1d100"
|
||||
## Plain tables roll one die face per entry (6 entries = d6). If any entry has a
|
||||
## range, the table becomes a ranged dice table (d100 by default) where the size
|
||||
## of each range sets its chance.
|
||||
|
||||
var id: String = ""
|
||||
var name: String = ""
|
||||
var position: Vector2 = Vector2.ZERO
|
||||
var collapsed: bool = false
|
||||
## Longer description (may contain BBCode).
|
||||
var details: String = ""
|
||||
var tags: Array[String] = []
|
||||
## Dice expression for ranged tables, e.g. "1d100", "2d6", "1d8+2".
|
||||
var dice: String = DEFAULT_DICE
|
||||
## Card mode: entries are drawn without replacement until the deck is empty.
|
||||
var card_mode: bool = false
|
||||
## What happens when the deck runs out: "reshuffle" or "stop".
|
||||
var deck_empty: String = "reshuffle"
|
||||
## Die size for ranged tables. 0 means the default (100).
|
||||
var die: int = 0
|
||||
var entries: Array[TableEntry] = []
|
||||
|
||||
var _dice_cache: Dice = null
|
||||
var _dice_cache_text: String = ""
|
||||
|
||||
|
||||
func _init(p_id: String = "", p_name: String = "") -> void:
|
||||
id = p_id
|
||||
|
|
@ -39,46 +27,16 @@ func is_ranged() -> bool:
|
|||
return false
|
||||
|
||||
|
||||
## The parsed dice expression (falls back to 1d100 if `dice` is invalid).
|
||||
func dice_obj() -> Dice:
|
||||
if _dice_cache == null or _dice_cache_text != dice:
|
||||
var d := Dice.parse(dice)
|
||||
_dice_cache = d if d.valid else Dice.make(1, 100)
|
||||
_dice_cache_text = dice
|
||||
return _dice_cache
|
||||
|
||||
|
||||
## Label for the dice: "d100", "2d6", "1d8+2". Plain tables label by entry count.
|
||||
func dice_label() -> String:
|
||||
if is_ranged():
|
||||
return dice_obj().label()
|
||||
return "d%d" % die_size()
|
||||
|
||||
|
||||
## Lowest value that can be rolled (1 on plain tables).
|
||||
func min_value() -> int:
|
||||
return dice_obj().min_value() if is_ranged() else 1
|
||||
|
||||
|
||||
## Highest value that can be rolled. Plain tables: the entry count.
|
||||
func die_size() -> int:
|
||||
if is_ranged():
|
||||
return dice_obj().max_value()
|
||||
return die if die > 0 else 100
|
||||
return entries.size()
|
||||
|
||||
|
||||
func total_weight() -> int:
|
||||
var w := 0
|
||||
for e in entries:
|
||||
w += maxi(0, e.weight)
|
||||
return w
|
||||
|
||||
|
||||
## Formats a die value the way printed tables do: d100 values are two digits
|
||||
## and 100 is written "00".
|
||||
func fmt(value: int) -> String:
|
||||
var two_digit := dice_obj().is_d100() if is_ranged() else entries.size() == 100
|
||||
if two_digit:
|
||||
if die_size() == 100:
|
||||
return "00" if value == 100 else "%02d" % value
|
||||
return str(value)
|
||||
|
||||
|
|
@ -91,14 +49,8 @@ func num_label(e: TableEntry, index: int) -> String:
|
|||
return "%s–%s" % [fmt(e.range_lo), fmt(e.range_hi)]
|
||||
|
||||
|
||||
## Chance (0–1) that a roll lands on this entry.
|
||||
func chance(e: TableEntry) -> float:
|
||||
if is_ranged():
|
||||
if not e.has_range:
|
||||
return 0.0
|
||||
return dice_obj().probability_between(e.range_lo, e.range_hi)
|
||||
var total := total_weight()
|
||||
return float(maxi(0, e.weight)) / float(total) if total > 0 else 0.0
|
||||
return float(e.span()) / float(maxi(1, die_size()))
|
||||
|
||||
|
||||
func entry_index_for(value: int) -> int:
|
||||
|
|
@ -116,38 +68,31 @@ func find_entry(eid: String) -> TableEntry:
|
|||
return null
|
||||
|
||||
|
||||
## Describes gaps, overlaps and out-of-span ranges in a ranged table, or "" when clean.
|
||||
## Describes gaps and overlaps in a ranged table, or "" when the ranges are clean.
|
||||
func range_problems() -> String:
|
||||
if not is_ranged():
|
||||
return ""
|
||||
var lo := min_value()
|
||||
var hi := die_size()
|
||||
var n := die_size()
|
||||
var hits := PackedInt32Array()
|
||||
hits.resize(hi + 1)
|
||||
var outside := PackedStringArray()
|
||||
hits.resize(n + 1)
|
||||
for e in entries:
|
||||
if not e.has_range:
|
||||
continue
|
||||
for v in range(maxi(lo, e.range_lo), mini(hi, e.range_hi) + 1):
|
||||
hits[v] += 1
|
||||
if e.range_lo < lo or e.range_hi > hi:
|
||||
outside.append("%s–%s" % [fmt(e.range_lo), fmt(e.range_hi)])
|
||||
var gaps := _runs(hits, lo, hi, func(h: int) -> bool: return h == 0)
|
||||
var overlaps := _runs(hits, lo, hi, func(h: int) -> bool: return h > 1)
|
||||
if e.has_range:
|
||||
for v in range(maxi(1, e.range_lo), mini(n, e.range_hi) + 1):
|
||||
hits[v] += 1
|
||||
var gaps := _runs(hits, n, func(h: int) -> bool: return h == 0)
|
||||
var overlaps := _runs(hits, n, func(h: int) -> bool: return h > 1)
|
||||
var parts := PackedStringArray()
|
||||
if gaps != "":
|
||||
parts.append("No result for %s." % gaps)
|
||||
if overlaps != "":
|
||||
parts.append("%s matches more than one result." % overlaps)
|
||||
if not outside.is_empty():
|
||||
parts.append("%s is outside %s–%s." % [", ".join(outside), fmt(lo), fmt(hi)])
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
func _runs(hits: PackedInt32Array, lo: int, n: int, test: Callable) -> String:
|
||||
func _runs(hits: PackedInt32Array, n: int, test: Callable) -> String:
|
||||
var out := PackedStringArray()
|
||||
var start := -1
|
||||
for v in range(lo, n + 2):
|
||||
for v in range(1, n + 2):
|
||||
var on: bool = v <= n and test.call(hits[v])
|
||||
if on and start < 0:
|
||||
start = v
|
||||
|
|
@ -164,16 +109,8 @@ func to_dict() -> Dictionary:
|
|||
var d := {"id": id, "name": name, "x": roundi(position.x), "y": roundi(position.y), "entries": list}
|
||||
if collapsed:
|
||||
d["collapsed"] = true
|
||||
if details != "":
|
||||
d["details"] = details
|
||||
if not tags.is_empty():
|
||||
d["tags"] = tags.duplicate()
|
||||
if is_ranged():
|
||||
d["dice"] = dice
|
||||
if card_mode:
|
||||
d["card_mode"] = true
|
||||
if deck_empty != "reshuffle":
|
||||
d["deck_empty"] = deck_empty
|
||||
if die > 0:
|
||||
d["die"] = die
|
||||
return d
|
||||
|
||||
|
||||
|
|
@ -181,16 +118,8 @@ static func from_dict(d: Dictionary) -> RollTable:
|
|||
var t := RollTable.new(str(d.get("id", "")), str(d.get("name", "")))
|
||||
t.position = Vector2(float(d.get("x", 0)), float(d.get("y", 0)))
|
||||
t.collapsed = bool(d.get("collapsed", false))
|
||||
t.details = str(d.get("details", ""))
|
||||
for tag: Variant in d.get("tags", []):
|
||||
t.tags.append(str(tag))
|
||||
if d.has("dice"):
|
||||
t.dice = str(d["dice"])
|
||||
elif int(d.get("die", 0)) > 1:
|
||||
t.dice = "1d%d" % int(d["die"])
|
||||
t.card_mode = bool(d.get("card_mode", false))
|
||||
t.deck_empty = "stop" if str(d.get("deck_empty", "reshuffle")) == "stop" else "reshuffle"
|
||||
for ed: Variant in d.get("entries", []):
|
||||
t.die = int(d.get("die", 0))
|
||||
for ed in d.get("entries", []):
|
||||
if ed is Dictionary:
|
||||
t.entries.append(TableEntry.from_dict(ed))
|
||||
return t
|
||||
|
|
|
|||
101
core/roller.gd
101
core/roller.gd
|
|
@ -9,11 +9,7 @@ extends RefCounted
|
|||
const MAX_DEPTH := 12
|
||||
|
||||
|
||||
## Rolls `table_id` and everything its pipes lead to. `decks` maps table id to
|
||||
## DeckState for card-mode tables; missing decks are created in it on demand.
|
||||
## Extra node keys: "save_as" (on nodes reached through a pipe that saves),
|
||||
## "reshuffled" (card deck was refilled for this draw).
|
||||
static func roll(board: TowerBoard, table_id: String, rng: RandomNumberGenerator, depth: int = 0, decks: Dictionary = {}) -> Dictionary:
|
||||
static func roll(board: TowerBoard, table_id: String, rng: RandomNumberGenerator, depth: int = 0) -> Dictionary:
|
||||
var t := board.get_table(table_id)
|
||||
if t == null:
|
||||
return {}
|
||||
|
|
@ -23,103 +19,21 @@ static func roll(board: TowerBoard, table_id: String, rng: RandomNumberGenerator
|
|||
return {"table": t, "stop": "This table has no results", "children": []}
|
||||
var index: int
|
||||
var value: int
|
||||
var reshuffled := false
|
||||
if t.card_mode:
|
||||
if not decks.has(t.id):
|
||||
decks[t.id] = DeckState.new()
|
||||
var deck: DeckState = decks[t.id]
|
||||
if deck.cards_left(t).y <= 0:
|
||||
return {"table": t, "stop": "This table has no results", "children": []}
|
||||
if deck.cards_left(t).x <= 0:
|
||||
if t.deck_empty == "stop":
|
||||
return {"table": t, "stop": "Deck empty", "children": []}
|
||||
deck.reshuffle()
|
||||
reshuffled = true
|
||||
var card := deck.draw(t, rng)
|
||||
index = int(card["index"])
|
||||
value = int(card["value"])
|
||||
elif t.is_ranged():
|
||||
value = t.dice_obj().roll(rng)
|
||||
if t.is_ranged():
|
||||
value = rng.randi_range(1, t.die_size())
|
||||
index = t.entry_index_for(value)
|
||||
if index < 0:
|
||||
return {"table": t, "value": value, "stop": "No result for %s" % t.fmt(value), "children": []}
|
||||
else:
|
||||
index = _pick_weighted(t, rng)
|
||||
if index < 0:
|
||||
return {"table": t, "stop": "No result can come up", "children": []}
|
||||
index = rng.randi_range(0, t.entries.size() - 1)
|
||||
value = index + 1
|
||||
var e := t.entries[index]
|
||||
var children: Array = []
|
||||
for p in e.pipes:
|
||||
var save := e.save_for(p)
|
||||
for k in e.count_for(p):
|
||||
var child := roll(board, p, rng, depth + 1, decks)
|
||||
if child.is_empty():
|
||||
break
|
||||
if save != "":
|
||||
child["save_as"] = save
|
||||
var child := roll(board, p, rng, depth + 1)
|
||||
if not child.is_empty():
|
||||
children.append(child)
|
||||
var node := {"table": t, "index": index, "value": value, "entry": e, "children": children}
|
||||
if reshuffled:
|
||||
node["reshuffled"] = true
|
||||
return node
|
||||
|
||||
|
||||
## Index of a weighted random entry, or -1 if every weight is 0.
|
||||
static func _pick_weighted(t: RollTable, rng: RandomNumberGenerator) -> int:
|
||||
var total := t.total_weight()
|
||||
if total <= 0:
|
||||
return -1
|
||||
var pick := rng.randi_range(0, total - 1)
|
||||
for i in t.entries.size():
|
||||
pick -= maxi(0, t.entries[i].weight)
|
||||
if pick < 0:
|
||||
return i
|
||||
return -1
|
||||
|
||||
|
||||
## Ids of tables that can never finish rolling: every result they can give
|
||||
## leads, through pipes, back into such a table. A table that loops on only
|
||||
## some of its entries is fine.
|
||||
static func endless_cycles(board: TowerBoard) -> Array[String]:
|
||||
var done := {}
|
||||
var changed := true
|
||||
while changed:
|
||||
changed = false
|
||||
for t in board.tables:
|
||||
if done.has(t.id):
|
||||
continue
|
||||
if _can_finish(t, board, done):
|
||||
done[t.id] = true
|
||||
changed = true
|
||||
var out: Array[String] = []
|
||||
for t in board.tables:
|
||||
if not done.has(t.id):
|
||||
out.append(t.id)
|
||||
return out
|
||||
|
||||
|
||||
static func _can_finish(t: RollTable, board: TowerBoard, done: Dictionary) -> bool:
|
||||
if t.entries.is_empty():
|
||||
return true
|
||||
for e in t.entries:
|
||||
if t.is_ranged():
|
||||
if not e.has_range or t.chance(e) <= 0.0:
|
||||
continue
|
||||
elif e.weight <= 0:
|
||||
continue
|
||||
var ok := true
|
||||
for p in e.pipes:
|
||||
if board.get_table(p) != null and not done.has(p):
|
||||
ok = false
|
||||
break
|
||||
if ok:
|
||||
return true
|
||||
# No entry can come up at all: the roll just stops.
|
||||
for e in t.entries:
|
||||
if (t.is_ranged() and e.has_range and t.chance(e) > 0.0) or (not t.is_ranged() and e.weight > 0):
|
||||
return false
|
||||
return true
|
||||
return {"table": t, "index": index, "value": value, "entry": e, "children": children}
|
||||
|
||||
|
||||
## One line of the result tray for a single node.
|
||||
|
|
@ -130,7 +44,6 @@ static func step_of(n: Dictionary) -> Dictionary:
|
|||
"table": t.name,
|
||||
"num": t.fmt(n["value"]) if n.has("value") else "",
|
||||
"die": t.die_size(),
|
||||
"dice": t.dice_label(),
|
||||
"text": text,
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -36,68 +36,48 @@ static func create() -> TowerBoard:
|
|||
var trinket_rows: Array = []
|
||||
for s in TRINKETS:
|
||||
trinket_rows.append([s])
|
||||
# [id, name, position, entries: [text, pipes?, range?, {details?, weight?}?], options?]
|
||||
# options: dice, collapsed, details, tags, card_mode
|
||||
# [id, name, position, entries: [text, pipes?, range?], options?]
|
||||
var spec: Array = [
|
||||
["wilderness", "Wilderness Travel", Vector2(40, 180), [
|
||||
["Travelers on the road", ["road"], [1, 30], {"details": "Most days the road is just the road. Roll on the Road Encounter table to see who is on it."}],
|
||||
["Travelers on the road", ["road"], [1, 30]],
|
||||
["Beasts on the hunt", ["monsters"], [31, 50]],
|
||||
["A peddler's cart", ["wares"], [51, 65]],
|
||||
["Something glints in the grass", ["loot"], [66, 80]],
|
||||
["A stranger at the campfire", ["names"], [81, 95]],
|
||||
["An odd find", ["trinkets"], [96, 100]],
|
||||
], {"dice": "1d100", "details": "Roll once per [b]travel day[/b]. Each result sends you to a table for the details of what the party meets.", "tags": ["travel"]}],
|
||||
], {"die": 100}],
|
||||
["road", "Road Encounter", Vector2(390, 40), [
|
||||
["Bandits ambush the party", ["loot"]], ["A merchant caravan", ["wares"]],
|
||||
["Something big in the trees", ["monsters"]], ["A quiet stretch of road"],
|
||||
["A sudden storm rolls in"], ["A lost traveler", ["names"]],
|
||||
]],
|
||||
["trinkets", "Curious Trinkets", Vector2(390, 420), trinket_rows, {"collapsed": true}],
|
||||
["monsters", "Monsters", Vector2(740, 20), [
|
||||
["Owlbear", ["loot"], null, {"details": "[b]Owlbear[/b]: AC 13, 59 HP. Multiattack: beak and claws. Grabs and crushes anything that comes close to its nest."}],
|
||||
["Giant spider"],
|
||||
["Troll", ["loot"], null, {"details": "[b]Troll[/b]: AC 15, 84 HP. Regenerates 10 HP each turn unless hit by [i]fire[/i] or [i]acid[/i]."}],
|
||||
["Wyvern"],
|
||||
], {"tags": ["combat"]}],
|
||||
["monsters", "Monsters", Vector2(740, 20), [["Owlbear", ["loot"]], ["Giant spider"], ["Troll", ["loot"]], ["Wyvern"]]],
|
||||
["wares", "Merchant Wares", Vector2(740, 300), [["Bolts of silk"], ["Rare spices"], ["Lamp oil"], ["A crate of strange eggs"]]],
|
||||
["loot", "Loot", Vector2(1090, 60), [
|
||||
["A pouch of gold", [], null, {"weight": 3}], ["A weapon", ["weapons"]], ["A healing potion"],
|
||||
["A pouch of gold"], ["A weapon", ["weapons"]], ["A healing potion"],
|
||||
["A torn map"], ["A gemstone"], ["Nothing but lint"],
|
||||
], {"tags": ["treasure"]}],
|
||||
]],
|
||||
["names", "Traveler Names", Vector2(1090, 400), [["Aldric"], ["Brenna"], ["Corvin"], ["Dagny"], ["Elowen"], ["Fenn"]]],
|
||||
["weapons", "Weapons", Vector2(1440, 60), [["Dagger"], ["Sword", ["quality"]], ["Hand axe"], ["Shortbow"]]],
|
||||
["quality", "Sword Quality", Vector2(1790, 130), [["Rusty"], ["Notched"], ["Fine"], ["Elven-forged"]]],
|
||||
["party_roles", "Party Roles", Vector2(1440, 330), [
|
||||
["Scout"], ["Map keeper"], ["Quartermaster"], ["Lookout"], ["Cook"], ["Diplomat"],
|
||||
], {"card_mode": true, "details": "Hand out one role per player. Each role is dealt once until everyone has had one, then the deck is reshuffled."}],
|
||||
["weather", "Weather", Vector2(1790, 380), [
|
||||
["Storm", [], [2, 3]], ["Rain", [], [4, 5]], ["Overcast", [], [6, 8]],
|
||||
["Clear skies", [], [9, 10]], ["Heat wave", [], [11, 12]],
|
||||
], {"dice": "2d6", "details": "Roll [b]2d6[/b]. Middling weather is the most common."}],
|
||||
]
|
||||
var board := TowerBoard.new()
|
||||
for s in spec:
|
||||
var t := RollTable.new(s[0], s[1])
|
||||
t.position = s[2]
|
||||
var opts: Dictionary = s[4] if s.size() > 4 else {}
|
||||
t.dice = str(opts.get("dice", RollTable.DEFAULT_DICE))
|
||||
t.die = int(opts.get("die", 0))
|
||||
t.collapsed = bool(opts.get("collapsed", false))
|
||||
t.details = str(opts.get("details", ""))
|
||||
for tag in opts.get("tags", []):
|
||||
t.tags.append(tag)
|
||||
t.card_mode = bool(opts.get("card_mode", false))
|
||||
for row in s[3]:
|
||||
var e := TableEntry.new(TowerBoard.new_id("e"), row[0])
|
||||
if row.size() > 1:
|
||||
for p in row[1]:
|
||||
e.add_pipe(p)
|
||||
if row.size() > 2 and row[2] != null:
|
||||
e.pipes.append(p)
|
||||
if row.size() > 2:
|
||||
e.has_range = true
|
||||
e.range_lo = row[2][0]
|
||||
e.range_hi = row[2][1]
|
||||
if row.size() > 3:
|
||||
e.details = str(row[3].get("details", ""))
|
||||
e.weight = int(row[3].get("weight", 1))
|
||||
t.entries.append(e)
|
||||
board.tables.append(t)
|
||||
return board
|
||||
|
|
|
|||
|
|
@ -1,204 +0,0 @@
|
|||
class_name StateStore
|
||||
extends RefCounted
|
||||
## Local state that is never exported: Card mode decks, persistent variables,
|
||||
## roll history and small settings. Everything is keyed by collection and table
|
||||
## ids, so renaming a collection or table doesn't break it.
|
||||
##
|
||||
## Stored as one file, <root>/state/state.json. Mutators only mark the store
|
||||
## dirty (cheap); call save() to write, which does nothing if nothing changed.
|
||||
## Decks are opaque Dictionaries (whatever DeckState.to_dict() produces).
|
||||
|
||||
const FORMAT_VERSION := 1
|
||||
const HISTORY_CAP := 50
|
||||
|
||||
## Folder that contains state/. Default user://.
|
||||
var root: String
|
||||
var _data: Dictionary = {}
|
||||
var _loaded := false
|
||||
var _dirty := false
|
||||
|
||||
|
||||
func _init(p_root: String = "user://") -> void:
|
||||
root = p_root
|
||||
|
||||
|
||||
func state_path() -> String:
|
||||
return root.path_join("state/state.json")
|
||||
|
||||
|
||||
# ---------- Decks ----------
|
||||
|
||||
func get_deck(cid: String, tid: String) -> Dictionary:
|
||||
var by_c: Dictionary = _section("decks").get(cid, {})
|
||||
var d: Variant = by_c.get(tid, {})
|
||||
return (d as Dictionary).duplicate(true) if d is Dictionary else {}
|
||||
|
||||
|
||||
func set_deck(cid: String, tid: String, deck: Dictionary) -> void:
|
||||
_bucket("decks", cid)[tid] = deck.duplicate(true)
|
||||
_dirty = true
|
||||
|
||||
|
||||
## Reshuffle: forgets the deck so the next draw starts a fresh one.
|
||||
func clear_deck(cid: String, tid: String) -> void:
|
||||
var by_c: Dictionary = _section("decks").get(cid, {})
|
||||
if by_c.erase(tid):
|
||||
_dirty = true
|
||||
|
||||
|
||||
# ---------- Persistent variables ----------
|
||||
# {name: {"value": String, "source": table_id}}
|
||||
|
||||
func get_variables(cid: String) -> Dictionary:
|
||||
var v: Variant = _section("variables").get(cid, {})
|
||||
return (v as Dictionary).duplicate(true) if v is Dictionary else {}
|
||||
|
||||
|
||||
func set_variable(cid: String, var_name: String, value: String, source: String = "") -> void:
|
||||
_bucket("variables", cid)[var_name] = {"value": value, "source": source}
|
||||
_dirty = true
|
||||
|
||||
|
||||
func clear_variable(cid: String, var_name: String) -> void:
|
||||
var by_c: Dictionary = _section("variables").get(cid, {})
|
||||
if by_c.erase(var_name):
|
||||
_dirty = true
|
||||
|
||||
|
||||
func clear_variables(cid: String) -> void:
|
||||
if _section("variables").erase(cid):
|
||||
_dirty = true
|
||||
|
||||
|
||||
# ---------- History ----------
|
||||
# One global list, most recent first, capped at HISTORY_CAP. Callers put a
|
||||
# "collection" id in each record; get_history(cid) filters by it.
|
||||
|
||||
func add_history(record: Dictionary) -> void:
|
||||
var list: Array = _section_list("history")
|
||||
list.push_front(record.duplicate(true))
|
||||
if list.size() > HISTORY_CAP:
|
||||
list.resize(HISTORY_CAP)
|
||||
_dirty = true
|
||||
|
||||
|
||||
## All records, or only those whose "collection" is cid when cid isn't empty.
|
||||
func get_history(cid: String = "") -> Array[Dictionary]:
|
||||
var out: Array[Dictionary] = []
|
||||
for r in _section_list("history"):
|
||||
if r is Dictionary and (cid == "" or str((r as Dictionary).get("collection", "")) == cid):
|
||||
out.append((r as Dictionary).duplicate(true))
|
||||
return out
|
||||
|
||||
|
||||
## Clears all history, or only a collection's records when cid isn't empty.
|
||||
func clear_history(cid: String = "") -> void:
|
||||
var list: Array = _section_list("history")
|
||||
if cid == "":
|
||||
list.clear()
|
||||
else:
|
||||
for i in range(list.size() - 1, -1, -1):
|
||||
if list[i] is Dictionary and str((list[i] as Dictionary).get("collection", "")) == cid:
|
||||
list.remove_at(i)
|
||||
_dirty = true
|
||||
|
||||
|
||||
# ---------- Settings ----------
|
||||
|
||||
func get_setting(key: String, default: Variant = null) -> Variant:
|
||||
return _section("settings").get(key, default)
|
||||
|
||||
|
||||
func set_setting(key: String, value: Variant) -> void:
|
||||
var s := _section("settings")
|
||||
if not s.has(key) or s[key] != value:
|
||||
s[key] = value
|
||||
_dirty = true
|
||||
|
||||
|
||||
# ---------- Forgetting ----------
|
||||
|
||||
## Drops everything stored for a collection (decks, variables, its history).
|
||||
func forget_collection(cid: String) -> void:
|
||||
_section("decks").erase(cid)
|
||||
_section("variables").erase(cid)
|
||||
clear_history(cid)
|
||||
if str(_section("settings").get("last_collection", "")) == cid:
|
||||
_section("settings").erase("last_collection")
|
||||
_dirty = true
|
||||
|
||||
|
||||
## Drops a table's deck and the variables it set.
|
||||
func forget_table(cid: String, tid: String) -> void:
|
||||
clear_deck(cid, tid)
|
||||
var vars: Dictionary = _section("variables").get(cid, {})
|
||||
for k in vars.keys():
|
||||
var v: Variant = vars[k]
|
||||
if v is Dictionary and str((v as Dictionary).get("source", "")) == tid:
|
||||
vars.erase(k)
|
||||
_dirty = true
|
||||
|
||||
|
||||
# ---------- Saving ----------
|
||||
|
||||
func is_dirty() -> bool:
|
||||
return _dirty
|
||||
|
||||
|
||||
## Writes the file if anything changed. Returns false only on a write error.
|
||||
func save() -> bool:
|
||||
if not _loaded or not _dirty:
|
||||
return true
|
||||
var out := _data.duplicate()
|
||||
out["format_version"] = FORMAT_VERSION
|
||||
var err := TowerBoard.write_text_atomic(state_path(), JSON.stringify(out, " "))
|
||||
if err != OK:
|
||||
push_warning("Couldn't save local state to %s: %s" % [state_path(), error_string(err)])
|
||||
return false
|
||||
_dirty = false
|
||||
return true
|
||||
|
||||
|
||||
## Re-reads the file, dropping unsaved changes. A corrupt file is moved aside to
|
||||
## state.json.corrupt and the store starts empty.
|
||||
func reload() -> void:
|
||||
_loaded = true
|
||||
_dirty = false
|
||||
_data = {}
|
||||
var path := state_path()
|
||||
if not FileAccess.file_exists(path):
|
||||
return
|
||||
var parsed: Variant = JSON.parse_string(FileAccess.get_file_as_string(path))
|
||||
if parsed is Dictionary:
|
||||
_data = parsed
|
||||
return
|
||||
push_warning("Local state file %s is unreadable; starting fresh (old copy kept as .corrupt)." % path)
|
||||
DirAccess.rename_absolute(path, path + ".corrupt")
|
||||
|
||||
|
||||
# ---------- Internals ----------
|
||||
|
||||
func _ensure() -> void:
|
||||
if not _loaded:
|
||||
reload()
|
||||
|
||||
|
||||
func _section(key: String) -> Dictionary:
|
||||
_ensure()
|
||||
if not (_data.get(key) is Dictionary):
|
||||
_data[key] = {}
|
||||
return _data[key]
|
||||
|
||||
|
||||
func _section_list(key: String) -> Array:
|
||||
_ensure()
|
||||
if not (_data.get(key) is Array):
|
||||
_data[key] = []
|
||||
return _data[key]
|
||||
|
||||
|
||||
func _bucket(section: String, cid: String) -> Dictionary:
|
||||
var s := _section(section)
|
||||
if not (s.get(cid) is Dictionary):
|
||||
s[cid] = {}
|
||||
return s[cid]
|
||||
|
|
@ -1 +0,0 @@
|
|||
uid://bhci5uoa7vbhp
|
||||
|
|
@ -3,21 +3,10 @@ extends RefCounted
|
|||
## One possible result on a table. An entry may pipe into other tables, and on a
|
||||
## ranged (dice) table it covers a span of die values such as 01–30.
|
||||
|
||||
const MAX_PIPE_COUNT := 99
|
||||
|
||||
var id: String = ""
|
||||
var text: String = ""
|
||||
## Optional longer description (may contain BBCode).
|
||||
var details: String = ""
|
||||
## Relative chance on a plain table; also the number of copies in card mode.
|
||||
## 0 means it never comes up. Ignored on ranged tables.
|
||||
var weight: int = 1
|
||||
## IDs of the tables this entry rolls on next (unique; one pipe per target).
|
||||
## IDs of the tables this entry rolls on next.
|
||||
var pipes: Array[String] = []
|
||||
## target table id -> how many times to roll it (missing = 1).
|
||||
var pipe_count: Dictionary = {}
|
||||
## target table id -> variable name to save the result under (missing = none).
|
||||
var pipe_save: Dictionary = {}
|
||||
var has_range: bool = false
|
||||
var range_lo: int = 1
|
||||
var range_hi: int = 1
|
||||
|
|
@ -33,68 +22,10 @@ func span() -> int:
|
|||
return range_hi - range_lo + 1 if has_range else 1
|
||||
|
||||
|
||||
## How many times the pipe to `target` rolls.
|
||||
func count_for(target: String) -> int:
|
||||
return clampi(int(pipe_count.get(target, 1)), 1, MAX_PIPE_COUNT)
|
||||
|
||||
|
||||
## Variable name the pipe to `target` saves into, or "".
|
||||
func save_for(target: String) -> String:
|
||||
return str(pipe_save.get(target, ""))
|
||||
|
||||
|
||||
func set_pipe_count(target: String, n: int) -> void:
|
||||
n = clampi(n, 1, MAX_PIPE_COUNT)
|
||||
if n == 1:
|
||||
pipe_count.erase(target)
|
||||
else:
|
||||
pipe_count[target] = n
|
||||
|
||||
|
||||
func set_pipe_save(target: String, name: String) -> void:
|
||||
name = name.strip_edges()
|
||||
if name == "":
|
||||
pipe_save.erase(target)
|
||||
else:
|
||||
pipe_save[target] = name
|
||||
|
||||
|
||||
## Adds a pipe if it isn't there already.
|
||||
func add_pipe(target: String, count: int = 1, save_as: String = "") -> void:
|
||||
if not pipes.has(target):
|
||||
pipes.append(target)
|
||||
set_pipe_count(target, count)
|
||||
set_pipe_save(target, save_as)
|
||||
|
||||
|
||||
## Removes a pipe along with its options.
|
||||
func remove_pipe(target: String) -> void:
|
||||
pipes.erase(target)
|
||||
pipe_count.erase(target)
|
||||
pipe_save.erase(target)
|
||||
|
||||
|
||||
func to_dict() -> Dictionary:
|
||||
var d := {"id": id, "text": text}
|
||||
if details != "":
|
||||
d["details"] = details
|
||||
if weight != 1:
|
||||
d["weight"] = weight
|
||||
if not pipes.is_empty():
|
||||
var list: Array = []
|
||||
for p in pipes:
|
||||
var n := count_for(p)
|
||||
var s := save_for(p)
|
||||
if n == 1 and s == "":
|
||||
list.append(p)
|
||||
else:
|
||||
var po := {"table": p}
|
||||
if n != 1:
|
||||
po["count"] = n
|
||||
if s != "":
|
||||
po["save_as"] = s
|
||||
list.append(po)
|
||||
d["pipes"] = list
|
||||
d["pipes"] = pipes.duplicate()
|
||||
if has_range:
|
||||
d["range"] = [range_lo, range_hi]
|
||||
return d
|
||||
|
|
@ -102,15 +33,8 @@ func to_dict() -> Dictionary:
|
|||
|
||||
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)))
|
||||
for p: Variant in d.get("pipes", []):
|
||||
if p is Dictionary:
|
||||
var target := str(p.get("table", ""))
|
||||
if target != "":
|
||||
e.add_pipe(target, int(p.get("count", 1)), str(p.get("save_as", "")))
|
||||
elif str(p) != "":
|
||||
e.add_pipe(str(p))
|
||||
for p in d.get("pipes", []):
|
||||
e.pipes.append(str(p))
|
||||
var r: Variant = d.get("range")
|
||||
if r is Array and r.size() == 2:
|
||||
e.has_range = true
|
||||
|
|
|
|||
|
|
@ -1,18 +1,13 @@
|
|||
class_name TowerBoard
|
||||
extends RefCounted
|
||||
## A collection: every table on the board, plus loading and saving as JSON.
|
||||
## Files carry a format_version; older versions are upgraded by migrate().
|
||||
## Every table on the board, plus loading and saving as JSON.
|
||||
|
||||
const SAVE_PATH := "user://board.json" # The single-board file of format version 1.
|
||||
const FORMAT_VERSION := 2
|
||||
const SAVE_PATH := "user://board.json"
|
||||
const FORMAT_VERSION := 1
|
||||
|
||||
static var _counter: int = 0
|
||||
static var _salt: String = ""
|
||||
|
||||
## Stable slug used as the file name and as the key for local state.
|
||||
var id: String = ""
|
||||
## Display name; free to change.
|
||||
var name: String = ""
|
||||
var tables: Array[RollTable] = []
|
||||
|
||||
|
||||
|
|
@ -40,105 +35,40 @@ func remove_table(id: String) -> void:
|
|||
e.pipes.erase(id)
|
||||
|
||||
|
||||
## 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
|
||||
|
||||
|
||||
func to_dict() -> Dictionary:
|
||||
var list: Array = []
|
||||
for t in tables:
|
||||
list.append(t.to_dict())
|
||||
return {"format_version": FORMAT_VERSION, "id": id, "name": name, "tables": list}
|
||||
return {"format_version": FORMAT_VERSION, "tables": list}
|
||||
|
||||
|
||||
func to_json() -> String:
|
||||
return JSON.stringify(to_dict(), " ")
|
||||
|
||||
|
||||
## Replaces the board's tables (and id/name, when the text has them) from JSON
|
||||
## text of any known version. Returns false if the text isn't a board.
|
||||
## Replaces the board's tables from JSON text. Returns false if the text isn't a board.
|
||||
func load_json(text: String) -> bool:
|
||||
var parsed: Variant = JSON.parse_string(text)
|
||||
if not (parsed is Dictionary) or not (parsed.get("tables") is Array):
|
||||
return false
|
||||
return load_dict(parsed as Dictionary)
|
||||
|
||||
|
||||
## Same as load_json for an already parsed Dictionary.
|
||||
func load_dict(src: Dictionary) -> bool:
|
||||
if not (src.get("tables") is Array):
|
||||
return false
|
||||
var d: Dictionary = migrate(src.duplicate())
|
||||
var loaded: Array[RollTable] = []
|
||||
for td in d["tables"]:
|
||||
for td in parsed["tables"]:
|
||||
if td is Dictionary:
|
||||
loaded.append(RollTable.from_dict(td))
|
||||
tables = loaded
|
||||
if str(d.get("id", "")) != "":
|
||||
id = str(d["id"])
|
||||
if str(d.get("name", "")) != "":
|
||||
name = str(d["name"])
|
||||
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
|
||||
|
||||
|
||||
func save(path: String = SAVE_PATH) -> bool:
|
||||
var err := write_text_atomic(path, to_json())
|
||||
if err != OK:
|
||||
push_warning("Couldn't save the board to %s: %s" % [path, error_string(err)])
|
||||
var f := FileAccess.open(path, FileAccess.WRITE)
|
||||
if f == null:
|
||||
push_warning("Couldn't save the board to %s: %s" % [path, error_string(FileAccess.get_open_error())])
|
||||
return false
|
||||
f.store_string(to_json())
|
||||
return true
|
||||
|
||||
|
||||
## Loads a board file, or returns null if there isn't a usable one.
|
||||
## Loads the saved board, or returns null if there isn't a usable one.
|
||||
static func load_saved(path: String = SAVE_PATH) -> TowerBoard:
|
||||
if not FileAccess.file_exists(path):
|
||||
return null
|
||||
|
|
|
|||
|
|
@ -1,25 +0,0 @@
|
|||
[preset.0]
|
||||
|
||||
name="Linux"
|
||||
platform="Linux"
|
||||
runnable=true
|
||||
dedicated_server=false
|
||||
custom_features=""
|
||||
export_filter="all_resources"
|
||||
include_filter=""
|
||||
exclude_filter="tests/*"
|
||||
export_path="build/linux/TableTower.x86_64"
|
||||
encryption_include_filters=""
|
||||
encryption_exclude_filters=""
|
||||
encrypt_pck=false
|
||||
encrypt_directory=false
|
||||
script_export_mode=2
|
||||
|
||||
[preset.0.options]
|
||||
|
||||
custom_template/debug=""
|
||||
custom_template/release=""
|
||||
debug/export_console_wrapper=1
|
||||
binary_format/embed_pck=true
|
||||
binary_format/architecture="x86_64"
|
||||
ssh_remote_deploy/enabled=false
|
||||
|
|
@ -1,374 +0,0 @@
|
|||
extends SceneTree
|
||||
## Headless checks for dice, weights, pipe options, card mode and JSON.
|
||||
## Run: godot --headless --path . -s res://tests/test_model.gd
|
||||
|
||||
var _failures := 0
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
_test_dice()
|
||||
_test_weights()
|
||||
_test_ranged_dice()
|
||||
_test_pipes()
|
||||
_test_cards()
|
||||
_test_cycles()
|
||||
_test_seed()
|
||||
_test_json()
|
||||
_test_sample()
|
||||
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
|
||||
quit(1 if _failures else 0)
|
||||
|
||||
|
||||
func _entry(id: String, text: String, weight: int = 1) -> TableEntry:
|
||||
var e := TableEntry.new(id, text)
|
||||
e.weight = weight
|
||||
return e
|
||||
|
||||
|
||||
func _ranged(id: String, dice: String, spans: Array) -> RollTable:
|
||||
var t := RollTable.new(id, id)
|
||||
t.dice = dice
|
||||
for i in spans.size():
|
||||
var e := _entry("%s%d" % [id, i], "r%d" % i)
|
||||
e.has_range = true
|
||||
e.range_lo = spans[i][0]
|
||||
e.range_hi = spans[i][1]
|
||||
t.entries.append(e)
|
||||
return t
|
||||
|
||||
|
||||
func _board(tables: Array) -> TowerBoard:
|
||||
var b := TowerBoard.new()
|
||||
for t in tables:
|
||||
b.tables.append(t)
|
||||
return b
|
||||
|
||||
|
||||
func _rng(seed_value: int) -> RandomNumberGenerator:
|
||||
var r := RandomNumberGenerator.new()
|
||||
r.seed = seed_value
|
||||
return r
|
||||
|
||||
|
||||
func _test_dice() -> void:
|
||||
var d := Dice.parse("2d6")
|
||||
_check(d.valid and d.min_value() == 2 and d.max_value() == 12, "2d6 parses with range 2–12")
|
||||
var d2 := Dice.parse(" 1D8 + 2 ")
|
||||
_check(d2.valid and d2.min_value() == 3 and d2.max_value() == 10 and d2.expression() == "1d8+2", "1d8+2 parses (spaces, case)")
|
||||
var d3 := Dice.parse("3d4-1")
|
||||
_check(d3.valid and d3.min_value() == 2 and d3.max_value() == 11, "3d4-1 parses")
|
||||
_check(Dice.parse("d20").valid and Dice.parse("d20").count == 1, "d20 means 1d20")
|
||||
for bad in ["", "abc", "0d6", "21d6", "1d1", "1d1001", "2d", "2d6+", "1d6*2", "-1d6", "1d6+x", "1d6+99999"]:
|
||||
_check(not Dice.parse(bad).valid, "invalid dice rejected: '%s'" % bad)
|
||||
_check(Dice.parse("nope").min_value() == 0 and Dice.parse("nope").roll(_rng(1)) == 0, "invalid dice roll nothing")
|
||||
_check(d.label() == "2d6" and Dice.parse("1d100").label() == "d100" and d2.label() == "1d8+2", "dice labels")
|
||||
|
||||
for expr in ["2d6", "1d100", "1d8+2", "20d1000", "3d4-1"]:
|
||||
var dist := Dice.parse(expr).distribution()
|
||||
var sum := 0.0
|
||||
for v: int in dist:
|
||||
sum += float(dist[v])
|
||||
_check(absf(sum - 1.0) < 1e-9, "distribution of %s sums to 1 (%.12f)" % [expr, sum])
|
||||
var two := d.distribution()
|
||||
_check(absf(float(two[7]) - 1.0 / 6.0) < 1e-12 and absf(float(two[2]) - 1.0 / 36.0) < 1e-12, "2d6: P(7)=1/6, P(2)=1/36")
|
||||
_check(not two.has(1) and not two.has(13), "2d6 has no impossible totals")
|
||||
_check(d2.distribution().has(3) and not d2.distribution().has(2), "1d8+2 distribution starts at 3")
|
||||
|
||||
var r := _rng(7)
|
||||
var seen := {}
|
||||
for i in 3000:
|
||||
var v := d.roll(r)
|
||||
seen[v] = seen.get(v, 0) + 1
|
||||
_check(seen.size() == 11, "2d6 rolls cover 2–12")
|
||||
_check(absf(float(seen[7]) / 3000.0 - 1.0 / 6.0) < 0.03, "2d6 rolls land on 7 about 1/6 of the time")
|
||||
|
||||
|
||||
func _test_weights() -> void:
|
||||
var t := RollTable.new("w", "W")
|
||||
t.entries.append(_entry("a", "Gold", 3))
|
||||
t.entries.append(_entry("b", "Silver", 1))
|
||||
t.entries.append(_entry("c", "Never", 0))
|
||||
_check(absf(t.chance(t.entries[0]) - 0.75) < 1e-9 and t.chance(t.entries[2]) == 0.0, "weighted chance() is weight/total")
|
||||
_check(t.die_size() == 3 and t.dice_label() == "d3", "plain table die size stays the entry count")
|
||||
_check(t.num_label(t.entries[2], 2) == "3", "plain num_label stays the row number")
|
||||
var b := _board([t])
|
||||
var r := _rng(99)
|
||||
var counts := {}
|
||||
for i in 8000:
|
||||
var n := Roller.roll(b, "w", r)
|
||||
var text: String = (n["entry"] as TableEntry).text
|
||||
counts[text] = counts.get(text, 0) + 1
|
||||
_check(absf(float(counts["Gold"]) / 8000.0 - 0.75) < 0.02, "weight 3 of 4 comes up about 75%")
|
||||
_check(not counts.has("Never"), "weight 0 never comes up")
|
||||
t.entries[0].weight = 0
|
||||
t.entries[1].weight = 0
|
||||
_check(Roller.roll(b, "w", r).has("stop"), "all-zero weights stop instead of crashing")
|
||||
_check(t.chance(t.entries[0]) == 0.0, "all-zero weights give 0 chance")
|
||||
|
||||
|
||||
func _test_ranged_dice() -> void:
|
||||
var t := _ranged("wx", "2d6", [[2, 4], [5, 9], [10, 12]])
|
||||
_check(t.is_ranged() and t.die_size() == 12 and t.min_value() == 2, "2d6 ranged table spans 2–12")
|
||||
_check(t.dice_label() == "2d6", "dice_label is 2d6")
|
||||
_check(t.range_problems() == "", "2d6 ranges 2–12 are clean")
|
||||
var total := 0.0
|
||||
for e in t.entries:
|
||||
total += t.chance(e)
|
||||
_check(absf(total - 1.0) < 1e-9, "2d6 chances sum to 1")
|
||||
_check(absf(t.chance(t.entries[0]) - 6.0 / 36.0) < 1e-9, "2–4 on 2d6 is 6/36")
|
||||
_check(absf(t.chance(t.entries[1]) - 24.0 / 36.0) < 1e-9, "5–9 on 2d6 is 24/36")
|
||||
var seven := _ranged("s", "2d6", [[2, 6], [7, 7], [8, 12]])
|
||||
_check(seven.chance(seven.entries[1]) > seven.chance(seven.entries[0]) / 5.0, "7 is the most likely single value")
|
||||
_check(t.fmt(5) == "5" and t.num_label(t.entries[1], 1) == "5–9", "2d6 uses plain numbers")
|
||||
|
||||
var gappy := _ranged("g", "2d6", [[2, 5], [7, 14]])
|
||||
_check(gappy.range_problems().contains("No result for 6."), "gap inside 2–12 reported: %s" % gappy.range_problems())
|
||||
_check(gappy.range_problems().contains("outside"), "out-of-span range reported: %s" % gappy.range_problems())
|
||||
var one_low := _ranged("l", "2d6", [[1, 12]])
|
||||
_check(one_low.range_problems().contains("outside"), "range starting below min reported")
|
||||
var d100 := _ranged("h", "1d100", [[1, 50], [51, 100]])
|
||||
_check(d100.fmt(100) == "00" and d100.fmt(7) == "07", "1d100 table formats 00 and two digits")
|
||||
var d6 := _ranged("k", "1d8+2", [[3, 10]])
|
||||
_check(d6.fmt(10) == "10" and d6.fmt(3) == "3" and d6.dice_label() == "1d8+2", "1d8+2 uses plain numbers")
|
||||
|
||||
var r := _rng(5)
|
||||
var b := _board([t])
|
||||
var low := 0
|
||||
for i in 4000:
|
||||
var n := Roller.roll(b, "wx", r)
|
||||
_check(int(n["value"]) >= 2 and int(n["value"]) <= 12, "ranged value in span")
|
||||
if int(n["index"]) == 0:
|
||||
low += 1
|
||||
_check(absf(float(low) / 4000.0 - 6.0 / 36.0) < 0.025, "ranged 2d6 roll frequencies follow the distribution")
|
||||
|
||||
|
||||
func _test_pipes() -> void:
|
||||
var src := RollTable.new("src", "Src")
|
||||
var e := _entry("e1", "Go")
|
||||
e.add_pipe("dst", 3, "foe")
|
||||
e.add_pipe("other")
|
||||
e.add_pipe("dst", 3, "foe")
|
||||
src.entries.append(e)
|
||||
_check(e.pipes.size() == 2, "pipe targets stay unique")
|
||||
var dst := RollTable.new("dst", "Dst")
|
||||
dst.entries.append(_entry("d1", "Thing"))
|
||||
var other := RollTable.new("other", "Other")
|
||||
other.entries.append(_entry("o1", "Else"))
|
||||
var b := _board([src, dst, other])
|
||||
var n := Roller.roll(b, "src", _rng(1))
|
||||
var kids: Array = n["children"]
|
||||
_check(kids.size() == 4, "count 3 plus one plain pipe gives 4 children (got %d)" % kids.size())
|
||||
var saved := 0
|
||||
for c: Dictionary in kids:
|
||||
if c.get("save_as", "") == "foe":
|
||||
saved += 1
|
||||
_check(saved == 3, "save_as is set on the 3 counted children")
|
||||
_check(not (kids[3] as Dictionary).has("save_as"), "plain pipe has no save_as")
|
||||
_check(not n.has("save_as"), "root node has no save_as")
|
||||
_check(Roller.flatten(n, []).size() == 5, "flatten walks counted children")
|
||||
var lit_e := {}
|
||||
var lit_p := {}
|
||||
Roller.collect_lit(n, lit_e, lit_p)
|
||||
_check(lit_p.has(Roller.pipe_key("src", "e1", "dst")), "counted pipe is lit")
|
||||
|
||||
e.remove_pipe("dst")
|
||||
_check(e.pipes == ["other"] and e.pipe_count.is_empty() and e.pipe_save.is_empty(), "remove_pipe clears options")
|
||||
_check(e.count_for("other") == 1 and e.save_for("other") == "", "defaults are count 1, no save")
|
||||
e.set_pipe_count("other", 0)
|
||||
_check(e.count_for("other") == 1, "count below 1 clamps to 1")
|
||||
e.set_pipe_save("other", "@loot")
|
||||
_check(e.to_dict()["pipes"] == [{"table": "other", "save_as": "@loot"}], "save-only pipe serializes as object")
|
||||
|
||||
|
||||
func _test_cards() -> void:
|
||||
var t := RollTable.new("deck", "Deck")
|
||||
t.card_mode = true
|
||||
t.entries.append(_entry("a", "A"))
|
||||
t.entries.append(_entry("b", "B", 2))
|
||||
t.entries.append(_entry("c", "C"))
|
||||
t.entries.append(_entry("z", "Z", 0))
|
||||
var b := _board([t])
|
||||
var decks := {}
|
||||
var r := _rng(21)
|
||||
var got := {}
|
||||
for i in 4:
|
||||
var n := Roller.roll(b, "deck", r, 0, decks)
|
||||
var tx: String = (n["entry"] as TableEntry).text
|
||||
got[tx] = got.get(tx, 0) + 1
|
||||
_check(not n.has("reshuffled"), "no reshuffle mid-deck")
|
||||
_check(got.get("A", 0) == 1 and got.get("B", 0) == 2 and got.get("C", 0) == 1 and not got.has("Z"), "4 draws deal each copy once: %s" % str(got))
|
||||
var dk: DeckState = decks["deck"]
|
||||
_check(dk.cards_left(t) == Vector2i(0, 4), "deck shows 0 of 4 left")
|
||||
var n5 := Roller.roll(b, "deck", r, 0, decks)
|
||||
_check(n5.get("reshuffled", false) == true and not n5.has("stop"), "empty deck reshuffles and flags the node")
|
||||
_check(dk.cards_left(t) == Vector2i(3, 4), "after reshuffle one card is drawn")
|
||||
|
||||
# Persisting through a dict.
|
||||
var restored := DeckState.from_dict(dk.to_dict())
|
||||
_check(restored.cards_left(t) == dk.cards_left(t), "DeckState round-trips through a dictionary")
|
||||
|
||||
# Stop mode.
|
||||
t.deck_empty = "stop"
|
||||
var d2 := {}
|
||||
for i in 4:
|
||||
Roller.roll(b, "deck", r, 0, d2)
|
||||
var stopped := Roller.roll(b, "deck", r, 0, d2)
|
||||
_check(stopped.get("stop", "") == "Deck empty", "stop mode returns Deck empty")
|
||||
(d2["deck"] as DeckState).reshuffle()
|
||||
_check(not Roller.roll(b, "deck", r, 0, d2).has("stop"), "manual reshuffle deals again")
|
||||
|
||||
# Edits.
|
||||
t.deck_empty = "reshuffle"
|
||||
var d3 := DeckState.new()
|
||||
for i in 4:
|
||||
d3.draw(t, r)
|
||||
_check(d3.cards_left(t) == Vector2i(0, 4), "fully drawn deck")
|
||||
t.entries[0].weight = 3
|
||||
_check(d3.cards_left(t) == Vector2i(2, 6), "raising a weight adds copies")
|
||||
t.entries.append(_entry("n", "New"))
|
||||
_check(d3.cards_left(t) == Vector2i(3, 7), "new entries start undrawn")
|
||||
t.entries.remove_at(1)
|
||||
_check(d3.cards_left(t) == Vector2i(3, 5), "deleted entries drop out")
|
||||
var first := d3.draw(t, r)
|
||||
_check(first.has("index"), "can still draw after edits")
|
||||
t.entries[0].weight = 1
|
||||
_check(d3.cards_left(t).x == 1 and d3.cards_left(t).y == 3, "lowering a weight removes copies (%s)" % str(d3.cards_left(t)))
|
||||
|
||||
# Ranged deck.
|
||||
var rt := _ranged("rd", "2d6", [[2, 6], [7, 7], [8, 12]])
|
||||
rt.card_mode = true
|
||||
var rb := _board([rt])
|
||||
var rd := {}
|
||||
var seen := {}
|
||||
for i in 3:
|
||||
var n := Roller.roll(rb, "rd", r, 0, rd)
|
||||
var idx: int = n["index"]
|
||||
var v: int = n["value"]
|
||||
seen[idx] = true
|
||||
var e: TableEntry = rt.entries[idx]
|
||||
_check(v >= e.range_lo and v <= e.range_hi, "ranged card value %d is inside its range" % v)
|
||||
_check(seen.size() == 3, "ranged deck deals every entry once")
|
||||
_check(Roller.roll(rb, "rd", r, 0, rd).get("reshuffled", false) == true, "ranged deck reshuffles")
|
||||
|
||||
|
||||
func _test_cycles() -> void:
|
||||
var a := RollTable.new("a", "A")
|
||||
var ea := _entry("ea", "to b")
|
||||
ea.add_pipe("b")
|
||||
a.entries.append(ea)
|
||||
var bt := RollTable.new("b", "B")
|
||||
var eb := _entry("eb", "to a")
|
||||
eb.add_pipe("a")
|
||||
bt.entries.append(eb)
|
||||
var board := _board([a, bt])
|
||||
_check(Roller.endless_cycles(board) == ["a", "b"], "two-table loop is endless")
|
||||
bt.entries.append(_entry("eb2", "exit"))
|
||||
_check(Roller.endless_cycles(board).is_empty(), "an exit entry fixes the loop")
|
||||
bt.entries[1].weight = 0
|
||||
_check(Roller.endless_cycles(board).size() == 2, "a zero-weight exit does not count")
|
||||
bt.entries[1].weight = 1
|
||||
var self_t := RollTable.new("s", "S")
|
||||
var es := _entry("es", "again")
|
||||
es.add_pipe("s")
|
||||
self_t.entries.append(es)
|
||||
_check(Roller.endless_cycles(_board([self_t])) == ["s"], "sole self-pipe is endless")
|
||||
self_t.entries.append(_entry("es2", "done"))
|
||||
_check(Roller.endless_cycles(_board([self_t])).is_empty(), "self-pipe on some entries is fine")
|
||||
# An entry that pipes into a cycle and a fine table is still stuck.
|
||||
var ok := RollTable.new("ok", "Ok")
|
||||
ok.entries.append(_entry("k", "fine"))
|
||||
var mix := RollTable.new("mix", "Mix")
|
||||
var em := _entry("em", "both")
|
||||
em.add_pipe("ok")
|
||||
em.add_pipe("mix")
|
||||
mix.entries.append(em)
|
||||
_check(Roller.endless_cycles(_board([ok, mix])) == ["mix"], "entry needing a cycle blocks its table")
|
||||
_check(Roller.endless_cycles(SampleBoard.create()).is_empty(), "sample board has no endless cycles")
|
||||
|
||||
|
||||
func _test_seed() -> void:
|
||||
var board := SampleBoard.create()
|
||||
var texts: Array[String] = []
|
||||
for run in 2:
|
||||
var r := _rng(2024)
|
||||
var decks := {}
|
||||
var out := PackedStringArray()
|
||||
for i in 25:
|
||||
for s in Roller.flatten(Roller.roll(board, "wilderness", r, 0, decks), []):
|
||||
out.append("%s=%s" % [s["table"], s["text"]])
|
||||
for s in Roller.flatten(Roller.roll(board, "party_roles", r, 0, decks), []):
|
||||
out.append("%s=%s" % [s["table"], s["text"]])
|
||||
texts.append("|".join(out))
|
||||
_check(texts[0] == texts[1] and texts[0].length() > 100, "same seed gives the same chains")
|
||||
var other := _rng(2025)
|
||||
var diff := PackedStringArray()
|
||||
for i in 25:
|
||||
for s in Roller.flatten(Roller.roll(board, "wilderness", other), []):
|
||||
diff.append("%s=%s" % [s["table"], s["text"]])
|
||||
_check(not texts[0].begins_with("|".join(diff)), "a different seed gives a different run")
|
||||
|
||||
|
||||
func _test_json() -> void:
|
||||
var legacy := {"tables": [{"id": "old", "name": "Old", "x": 1, "y": 2, "die": 20, "entries": [
|
||||
{"id": "e1", "text": "Low", "range": [1, 10], "pipes": ["x", {"table": "y", "count": 2, "save_as": "@pal"}]},
|
||||
{"id": "e2", "text": "High", "range": [11, 20], "weight": 4, "details": "[b]hi[/b]"}]}]}
|
||||
var b := TowerBoard.new()
|
||||
_check(b.load_json(JSON.stringify(legacy)), "legacy board loads")
|
||||
var t := b.get_table("old")
|
||||
_check(t.dice == "1d20" and t.die_size() == 20 and t.dice_label() == "d20", "legacy die 20 becomes 1d20")
|
||||
var e := t.entries[0]
|
||||
_check(e.pipes == ["x", "y"] and e.count_for("y") == 2 and e.save_for("y") == "@pal" and e.count_for("x") == 1, "mixed string/object pipes load")
|
||||
_check(t.entries[1].weight == 4 and t.entries[1].details == "[b]hi[/b]", "weight and entry details load")
|
||||
var d := t.to_dict()
|
||||
_check(not d.has("die") and d["dice"] == "1d20", "die is no longer written")
|
||||
var ed: Dictionary = d["entries"][0]
|
||||
_check(ed["pipes"] == ["x", {"table": "y", "count": 2, "save_as": "@pal"}], "pipes save in contract form")
|
||||
_check(not (d["entries"][1] as Dictionary).has("pipes"), "empty pipes omitted")
|
||||
|
||||
var plain := RollTable.new("p", "P")
|
||||
plain.entries.append(_entry("e", "x"))
|
||||
var pd := plain.to_dict()
|
||||
for k in ["collapsed", "details", "tags", "dice", "card_mode", "deck_empty"]:
|
||||
_check(not pd.has(k), "default %s omitted" % k)
|
||||
_check(not (pd["entries"][0] as Dictionary).has("weight") and not (pd["entries"][0] as Dictionary).has("details"), "default entry fields omitted")
|
||||
|
||||
plain.details = "Hello"
|
||||
plain.tags.append("a")
|
||||
plain.tags.append("b")
|
||||
plain.card_mode = true
|
||||
plain.deck_empty = "stop"
|
||||
var back := RollTable.from_dict(JSON.parse_string(JSON.stringify(plain.to_dict())))
|
||||
_check(back.details == "Hello" and back.tags == ["a", "b"] and back.card_mode and back.deck_empty == "stop", "details, tags, card mode round-trip")
|
||||
_check(back.to_dict() == plain.to_dict(), "table dict round-trips")
|
||||
|
||||
var sample := SampleBoard.create()
|
||||
var copy := TowerBoard.new()
|
||||
_check(copy.load_json(sample.to_json()) and copy.to_json() == sample.to_json(), "sample board JSON round-trips")
|
||||
|
||||
|
||||
func _test_sample() -> void:
|
||||
var s := SampleBoard.create()
|
||||
var ids := {}
|
||||
for t in s.tables:
|
||||
_check(not ids.has(t.id), "unique table id %s" % t.id)
|
||||
ids[t.id] = true
|
||||
var eids := {}
|
||||
for e in t.entries:
|
||||
_check(not eids.has(e.id), "unique entry ids in %s" % t.id)
|
||||
eids[e.id] = true
|
||||
for p in e.pipes:
|
||||
_check(s.get_table(p) != null, "pipe target %s exists" % p)
|
||||
var loot := s.get_table("loot")
|
||||
_check(loot.entries[0].weight == 3 and absf(loot.chance(loot.entries[0]) - 3.0 / 8.0) < 1e-9, "gold weight 3 of 8")
|
||||
var roles := s.get_table("party_roles")
|
||||
_check(roles.card_mode and roles.entries.size() == 6 and roles.position == Vector2(1440, 330), "Party Roles is a 6-card deck")
|
||||
var w := s.get_table("weather")
|
||||
_check(w.dice == "2d6" and w.position == Vector2(1790, 380) and w.range_problems() == "", "Weather is a clean 2d6 table")
|
||||
_check(s.get_table("monsters").entries[0].details != "" and s.get_table("wilderness").details != "", "sample has details")
|
||||
_check(s.get_table("wilderness").position == Vector2(40, 180) and s.get_table("quality").position == Vector2(1790, 130), "existing positions kept")
|
||||
|
||||
|
||||
func _check(ok: bool, what: String) -> void:
|
||||
if not ok:
|
||||
_failures += 1
|
||||
print(" ✗ ", what)
|
||||
|
|
@ -1 +0,0 @@
|
|||
uid://dut8l77y7pcoa
|
||||
|
|
@ -1,204 +0,0 @@
|
|||
extends SceneTree
|
||||
## Headless checks for collections, LibraryStore and StateStore.
|
||||
## Run: godot --headless --path . -s res://tests/test_storage.gd
|
||||
|
||||
const ROOT := "user://test_storage_tmp"
|
||||
|
||||
var _failures := 0
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
_wipe(ROOT)
|
||||
_test_versions()
|
||||
_test_library()
|
||||
_test_migration()
|
||||
_test_corrupt()
|
||||
_test_state()
|
||||
_wipe(ROOT)
|
||||
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
|
||||
quit(1 if _failures else 0)
|
||||
|
||||
|
||||
func _test_versions() -> void:
|
||||
var sample := SampleBoard.create()
|
||||
var v1 := JSON.stringify({"format_version": 1, "tables": sample.to_dict()["tables"]})
|
||||
var b := TowerBoard.new()
|
||||
_check(b.load_json(v1), "v1 text loads")
|
||||
_check(b.tables.size() == sample.tables.size(), "v1 keeps every table")
|
||||
_check(b.id == "" and b.name == "", "v1 has no id or name")
|
||||
var d := b.to_dict()
|
||||
_check(int(d["format_version"]) == 2, "saving writes format_version 2")
|
||||
var b2 := TowerBoard.new()
|
||||
b2.id = "x"
|
||||
b2.name = "X"
|
||||
b2.tables = b.tables
|
||||
var b3 := TowerBoard.new()
|
||||
_check(b3.load_json(b2.to_json()), "v2 text loads")
|
||||
_check(b3.id == "x" and b3.name == "X", "v2 round-trips id and name")
|
||||
_check(not TowerBoard.new().load_json("not json"), "garbage is rejected")
|
||||
_check(TowerBoard.migrate({"format_version": 1, "tables": []})["format_version"] == 2, "migrate steps 1 to 2")
|
||||
|
||||
|
||||
func _test_library() -> void:
|
||||
var root := ROOT + "/lib"
|
||||
var lib := LibraryStore.new(root)
|
||||
_check(lib.list().is_empty(), "empty library lists nothing")
|
||||
var a := lib.create("Fantasy Loot")
|
||||
_check(a.id == "fantasy-loot", "slug id from name")
|
||||
var a2 := lib.create("Fantasy Loot")
|
||||
_check(a2.id == "fantasy-loot-2", "duplicate names get unique ids")
|
||||
_check(LibraryStore.slugify(" !! ") == "collection", "empty slug falls back")
|
||||
_check(lib.exists("fantasy-loot") and not lib.exists("nope") and not lib.exists("../x"), "exists")
|
||||
|
||||
a.tables = SampleBoard.create().tables
|
||||
_check(lib.save(a), "save succeeds")
|
||||
var back := lib.load_collection("fantasy-loot")
|
||||
_check(back != null and back.tables.size() == a.tables.size() and back.name == "Fantasy Loot", "load round trip")
|
||||
|
||||
_check(lib.rename("fantasy-loot", "Dark Loot"), "rename succeeds")
|
||||
_check(lib.load_collection("fantasy-loot").name == "Dark Loot", "rename keeps id, changes name")
|
||||
|
||||
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")
|
||||
var names: Array = []
|
||||
for e in lib.list():
|
||||
names.append(e["name"])
|
||||
_check(names == ["Dark Loot", "Dark Loot Copy", "Fantasy Loot"], "list sorted by name: %s" % str(names))
|
||||
|
||||
# No temp files left behind by saves.
|
||||
var leftovers := 0
|
||||
for f in DirAccess.get_files_at(lib.collections_dir()):
|
||||
if not f.ends_with(".json"):
|
||||
leftovers += 1
|
||||
_check(leftovers == 0, "atomic save leaves no temp files")
|
||||
|
||||
# Delete removes the file and its state.
|
||||
lib.state.set_deck("fantasy-loot", "loot", {"drawn": [1]})
|
||||
lib.state.set_variable("fantasy-loot", "weapon", "Dagger", "loot")
|
||||
lib.state.add_history({"collection": "fantasy-loot", "root": "loot"})
|
||||
lib.state.add_history({"collection": "dark-loot-copy", "root": "loot"})
|
||||
lib.state.set_setting("last_collection", "fantasy-loot")
|
||||
_check(lib.delete("fantasy-loot"), "delete succeeds")
|
||||
_check(not lib.exists("fantasy-loot"), "deleted file is gone")
|
||||
_check(lib.state.get_deck("fantasy-loot", "loot").is_empty(), "delete drops decks")
|
||||
_check(lib.state.get_variables("fantasy-loot").is_empty(), "delete drops variables")
|
||||
_check(lib.state.get_history("fantasy-loot").is_empty() and lib.state.get_history().size() == 1, "delete drops only its history")
|
||||
_check(lib.state.get_setting("last_collection") == null, "delete clears last_collection if it pointed there")
|
||||
_check(not lib.delete("fantasy-loot"), "deleting twice returns false")
|
||||
_check(lib.load_collection("fantasy-loot") == null, "loading a missing collection returns null")
|
||||
|
||||
|
||||
func _test_migration() -> void:
|
||||
var root := ROOT + "/mig"
|
||||
DirAccess.make_dir_recursive_absolute(root)
|
||||
var legacy := root + "/board.json"
|
||||
var sample := SampleBoard.create()
|
||||
var f := FileAccess.open(legacy, FileAccess.WRITE)
|
||||
f.store_string(JSON.stringify({"format_version": 1, "tables": sample.to_dict()["tables"]}))
|
||||
f.close()
|
||||
var lib := LibraryStore.new(root)
|
||||
var b := lib.migrate_legacy()
|
||||
_check(b != null and b.name == "My Tables" and b.id == "my-tables", "legacy board imported as My Tables")
|
||||
_check(lib.load_collection("my-tables").tables.size() == sample.tables.size(), "imported tables are saved")
|
||||
_check(not FileAccess.file_exists(legacy) and FileAccess.file_exists(legacy + ".bak"), "old file renamed to .bak")
|
||||
_check(lib.migrate_legacy() == null, "migration is a no-op once done")
|
||||
|
||||
# Not run when collections already exist.
|
||||
var f2 := FileAccess.open(legacy, FileAccess.WRITE)
|
||||
f2.store_string(JSON.stringify({"format_version": 1, "tables": sample.to_dict()["tables"]}))
|
||||
f2.close()
|
||||
_check(lib.migrate_legacy() == null and FileAccess.file_exists(legacy), "no migration when collections exist")
|
||||
|
||||
|
||||
func _test_corrupt() -> void:
|
||||
var root := ROOT + "/bad"
|
||||
var lib := LibraryStore.new(root)
|
||||
lib.create("Good")
|
||||
var f := FileAccess.open(lib.path_for("broken"), FileAccess.WRITE)
|
||||
f.store_string("{ this is not json")
|
||||
f.close()
|
||||
var f2 := FileAccess.open(lib.path_for("wrongshape"), FileAccess.WRITE)
|
||||
f2.store_string("[1, 2, 3]")
|
||||
f2.close()
|
||||
_check(lib.load_collection("broken") == null, "corrupt collection loads as null")
|
||||
var ids: Array = []
|
||||
for e in lib.list():
|
||||
ids.append(e["id"])
|
||||
_check(ids == ["good"], "list skips unreadable files: %s" % str(ids))
|
||||
_check(not lib.errors.is_empty(), "errors are recorded")
|
||||
|
||||
# Corrupt legacy file is left alone.
|
||||
var legacy := root + "/board.json"
|
||||
var f3 := FileAccess.open(legacy, FileAccess.WRITE)
|
||||
f3.store_string("nope")
|
||||
f3.close()
|
||||
var lib2 := LibraryStore.new(root + "/empty")
|
||||
_check(lib2.migrate_legacy(legacy) == null and FileAccess.file_exists(legacy), "corrupt legacy file is not touched")
|
||||
|
||||
# Corrupt state file starts fresh.
|
||||
var st := StateStore.new(root)
|
||||
DirAccess.make_dir_recursive_absolute(root + "/state")
|
||||
var f4 := FileAccess.open(st.state_path(), FileAccess.WRITE)
|
||||
f4.store_string("garbage")
|
||||
f4.close()
|
||||
_check(st.get_variables("c").is_empty(), "corrupt state file reads as empty")
|
||||
st.set_setting("k", 1)
|
||||
_check(st.save() and FileAccess.file_exists(st.state_path() + ".corrupt"), "corrupt state moved aside, new one saved")
|
||||
|
||||
|
||||
func _test_state() -> void:
|
||||
var root := ROOT + "/state"
|
||||
var st := StateStore.new(root)
|
||||
_check(st.save() and not FileAccess.file_exists(st.state_path()), "saving an untouched store writes nothing")
|
||||
st.set_deck("c1", "t1", {"drawn": [3, 5], "n": 10})
|
||||
st.set_deck("c1", "t2", {"drawn": []})
|
||||
st.set_variable("c1", "weapon", "Dagger", "t1")
|
||||
st.set_variable("c1", "armor", "Plate", "t2")
|
||||
st.set_setting("last_collection", "c1")
|
||||
for i in 60:
|
||||
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")
|
||||
_check(not FileAccess.file_exists(st.state_path() + ".tmp"), "no temp file after state save")
|
||||
|
||||
var st2 := StateStore.new(root)
|
||||
var deck := st2.get_deck("c1", "t1")
|
||||
_check(deck.get("n") == 10.0 and (deck["drawn"] as Array).size() == 2, "deck round trip")
|
||||
_check(st2.get_deck("c1", "nope").is_empty() and st2.get_deck("zz", "t1").is_empty(), "missing deck is empty")
|
||||
_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")
|
||||
|
||||
st2.clear_variable("c1", "weapon")
|
||||
_check(not st2.get_variables("c1").has("weapon") and st2.get_variables("c1").has("armor"), "clear one variable")
|
||||
st2.forget_table("c1", "t2")
|
||||
_check(st2.get_deck("c1", "t2").is_empty() and not st2.get_variables("c1").has("armor"), "forget_table drops deck and its variables")
|
||||
_check(not st2.get_deck("c1", "t1").is_empty(), "forget_table leaves other tables")
|
||||
st2.clear_deck("c1", "t1")
|
||||
_check(st2.get_deck("c1", "t1").is_empty(), "clear_deck")
|
||||
st2.set_variable("c1", "a", "1")
|
||||
st2.clear_variables("c1")
|
||||
_check(st2.get_variables("c1").is_empty(), "clear all variables")
|
||||
st2.clear_history()
|
||||
_check(st2.get_history().is_empty(), "clear_history")
|
||||
st2.save()
|
||||
var st3 := StateStore.new(root)
|
||||
_check(st3.get_history().is_empty() and st3.get_deck("c1", "t1").is_empty(), "cleared state persists")
|
||||
|
||||
|
||||
func _wipe(path: String) -> void:
|
||||
if not DirAccess.dir_exists_absolute(path):
|
||||
return
|
||||
for d in DirAccess.get_directories_at(path):
|
||||
_wipe(path.path_join(d))
|
||||
for f in DirAccess.get_files_at(path):
|
||||
DirAccess.remove_absolute(path.path_join(f))
|
||||
DirAccess.remove_absolute(path)
|
||||
|
||||
|
||||
func _check(ok: bool, what: String) -> void:
|
||||
if not ok:
|
||||
_failures += 1
|
||||
print(" ✗ ", what)
|
||||
|
|
@ -1 +0,0 @@
|
|||
uid://d10dfnkj6mc2y
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
# Runs TableTower in a window for automated checks (screenshots, smoke tests).
|
||||
#
|
||||
# While it runs, a temporary override.cfg renames the project to "TableTower Test",
|
||||
# so its window class is "TableTower Test". A KWin window rule keeps windows of
|
||||
# that class in the background without focus. The file is removed on exit, so
|
||||
# normal runs from the editor are unaffected.
|
||||
#
|
||||
# Usage: tools/test_window.sh [project dir] -- [user args, e.g. --screenshot=/tmp/x.png]
|
||||
set -euo pipefail
|
||||
GODOT="${GODOT:-$HOME/apps/Godot_v4.7.2-stable_linux.x86_64}"
|
||||
PROJECT="$(pwd)"
|
||||
if [[ $# -gt 0 && "$1" != "--" ]]; then PROJECT="$(cd "$1" && pwd)"; shift; fi
|
||||
[[ "${1:-}" == "--" ]] && shift
|
||||
OVERRIDE="$PROJECT/override.cfg"
|
||||
if [[ -e "$OVERRIDE" ]]; then
|
||||
echo "override.cfg already exists in $PROJECT; is another test window running?" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '[application]\n\nconfig/name="TableTower Test"\n' > "$OVERRIDE"
|
||||
trap 'rm -f "$OVERRIDE"' EXIT
|
||||
"$GODOT" --path "$PROJECT" -- "$@"
|
||||
42
ui/main.gd
42
ui/main.gd
|
|
@ -13,8 +13,6 @@ const HINTS := {
|
|||
}
|
||||
|
||||
var data: TowerBoard
|
||||
var library: LibraryStore
|
||||
var state: StateStore
|
||||
var mode: Mode = Mode.PLAY
|
||||
var cards: Dictionary = {} # table id -> TableCard
|
||||
var lit_entries: Dictionary = {} # "tid:eid" -> true
|
||||
|
|
@ -51,11 +49,9 @@ func _ready() -> void:
|
|||
if args.has("--sample") or _arg_value(args, "--screenshot") != "":
|
||||
_saving_enabled = false
|
||||
if _saving_enabled:
|
||||
_open_library()
|
||||
data = TowerBoard.load_saved()
|
||||
if data == null:
|
||||
data = SampleBoard.create()
|
||||
data.id = "fantasy-loot"
|
||||
data.name = "Fantasy Loot"
|
||||
|
||||
_build_ui()
|
||||
_rebuild_cards()
|
||||
|
|
@ -69,35 +65,8 @@ func _ready() -> void:
|
|||
|
||||
|
||||
func _exit_tree() -> void:
|
||||
_save_now()
|
||||
|
||||
|
||||
## Migrates the old board.json if needed, then opens the last collection (or the
|
||||
## first one, or a new "Fantasy Loot" made from the sample tables).
|
||||
func _open_library() -> void:
|
||||
state = StateStore.new()
|
||||
library = LibraryStore.new("user://", state)
|
||||
library.migrate_legacy()
|
||||
var last := str(state.get_setting("last_collection", ""))
|
||||
if last != "":
|
||||
data = library.load_collection(last)
|
||||
if data == null:
|
||||
for entry in library.list():
|
||||
data = library.load_collection(str(entry["id"]))
|
||||
if data:
|
||||
break
|
||||
if data == null:
|
||||
data = library.create("Fantasy Loot")
|
||||
data.tables = SampleBoard.create().tables
|
||||
library.save(data)
|
||||
state.set_setting("last_collection", data.id)
|
||||
|
||||
|
||||
func _save_now() -> void:
|
||||
if _saving_enabled and data and library:
|
||||
library.save(data)
|
||||
state.set_setting("last_collection", data.id)
|
||||
state.save()
|
||||
if _saving_enabled and data:
|
||||
data.save()
|
||||
|
||||
|
||||
# ---------- UI ----------
|
||||
|
|
@ -121,7 +90,8 @@ func _build_ui() -> void:
|
|||
_save_timer.one_shot = true
|
||||
_save_timer.wait_time = SAVE_DELAY
|
||||
_save_timer.timeout.connect(func() -> void:
|
||||
_save_now()
|
||||
if _saving_enabled:
|
||||
data.save()
|
||||
)
|
||||
add_child(_save_timer)
|
||||
resized.connect(_place_toast)
|
||||
|
|
@ -378,7 +348,7 @@ func add_table() -> void:
|
|||
|
||||
func reset_sample() -> void:
|
||||
var snap := _snapshot()
|
||||
data.tables = SampleBoard.create().tables
|
||||
data = SampleBoard.create()
|
||||
lit_entries.clear()
|
||||
lit_pipes.clear()
|
||||
_rebuild_cards()
|
||||
|
|
|
|||
Loading…
Reference in a new issue