Merge branch 'worktree-agent-a2900db2ff6409443' into pipe-board
This commit is contained in:
commit
6a873810b0
10 changed files with 895 additions and 42 deletions
106
core/deck_state.gd
Normal file
106
core/deck_state.gd
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
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
core/deck_state.gd.uid
Normal file
1
core/deck_state.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dxnqme8pv84v4
|
||||
116
core/dice.gd
Normal file
116
core/dice.gd
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
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
core/dice.gd.uid
Normal file
1
core/dice.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://oqwt4gld3dfa
|
||||
|
|
@ -2,18 +2,30 @@ class_name RollTable
|
|||
extends RefCounted
|
||||
## A named list of entries placed on the board.
|
||||
##
|
||||
## 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.
|
||||
## 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"
|
||||
|
||||
var id: String = ""
|
||||
var name: String = ""
|
||||
var position: Vector2 = Vector2.ZERO
|
||||
var collapsed: bool = false
|
||||
## Die size for ranged tables. 0 means the default (100).
|
||||
var die: int = 0
|
||||
## 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"
|
||||
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
|
||||
|
|
@ -27,16 +39,46 @@ 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 die if die > 0 else 100
|
||||
return dice_obj().max_value()
|
||||
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:
|
||||
if die_size() == 100:
|
||||
var two_digit := dice_obj().is_d100() if is_ranged() else entries.size() == 100
|
||||
if two_digit:
|
||||
return "00" if value == 100 else "%02d" % value
|
||||
return str(value)
|
||||
|
||||
|
|
@ -49,8 +91,14 @@ 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:
|
||||
return float(e.span()) / float(maxi(1, die_size()))
|
||||
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
|
||||
|
||||
|
||||
func entry_index_for(value: int) -> int:
|
||||
|
|
@ -68,31 +116,38 @@ func find_entry(eid: String) -> TableEntry:
|
|||
return null
|
||||
|
||||
|
||||
## Describes gaps and overlaps in a ranged table, or "" when the ranges are clean.
|
||||
## Describes gaps, overlaps and out-of-span ranges in a ranged table, or "" when clean.
|
||||
func range_problems() -> String:
|
||||
if not is_ranged():
|
||||
return ""
|
||||
var n := die_size()
|
||||
var lo := min_value()
|
||||
var hi := die_size()
|
||||
var hits := PackedInt32Array()
|
||||
hits.resize(n + 1)
|
||||
hits.resize(hi + 1)
|
||||
var outside := PackedStringArray()
|
||||
for e in entries:
|
||||
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)
|
||||
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)
|
||||
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, n: int, test: Callable) -> String:
|
||||
func _runs(hits: PackedInt32Array, lo: int, n: int, test: Callable) -> String:
|
||||
var out := PackedStringArray()
|
||||
var start := -1
|
||||
for v in range(1, n + 2):
|
||||
for v in range(lo, n + 2):
|
||||
var on: bool = v <= n and test.call(hits[v])
|
||||
if on and start < 0:
|
||||
start = v
|
||||
|
|
@ -109,8 +164,16 @@ 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 die > 0:
|
||||
d["die"] = die
|
||||
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
|
||||
return d
|
||||
|
||||
|
||||
|
|
@ -118,8 +181,16 @@ 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.die = int(d.get("die", 0))
|
||||
for ed in d.get("entries", []):
|
||||
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", []):
|
||||
if ed is Dictionary:
|
||||
t.entries.append(TableEntry.from_dict(ed))
|
||||
return t
|
||||
|
|
|
|||
101
core/roller.gd
101
core/roller.gd
|
|
@ -9,7 +9,11 @@ extends RefCounted
|
|||
const MAX_DEPTH := 12
|
||||
|
||||
|
||||
static func roll(board: TowerBoard, table_id: String, rng: RandomNumberGenerator, depth: int = 0) -> Dictionary:
|
||||
## 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:
|
||||
var t := board.get_table(table_id)
|
||||
if t == null:
|
||||
return {}
|
||||
|
|
@ -19,21 +23,103 @@ 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
|
||||
if t.is_ranged():
|
||||
value = rng.randi_range(1, t.die_size())
|
||||
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)
|
||||
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 = rng.randi_range(0, t.entries.size() - 1)
|
||||
index = _pick_weighted(t, rng)
|
||||
if index < 0:
|
||||
return {"table": t, "stop": "No result can come up", "children": []}
|
||||
value = index + 1
|
||||
var e := t.entries[index]
|
||||
var children: Array = []
|
||||
for p in e.pipes:
|
||||
var child := roll(board, p, rng, depth + 1)
|
||||
if not child.is_empty():
|
||||
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
|
||||
children.append(child)
|
||||
return {"table": t, "index": index, "value": value, "entry": e, "children": children}
|
||||
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
|
||||
|
||||
|
||||
## One line of the result tray for a single node.
|
||||
|
|
@ -44,6 +130,7 @@ 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,48 +36,68 @@ static func create() -> TowerBoard:
|
|||
var trinket_rows: Array = []
|
||||
for s in TRINKETS:
|
||||
trinket_rows.append([s])
|
||||
# [id, name, position, entries: [text, pipes?, range?], options?]
|
||||
# [id, name, position, entries: [text, pipes?, range?, {details?, weight?}?], options?]
|
||||
# options: dice, collapsed, details, tags, card_mode
|
||||
var spec: Array = [
|
||||
["wilderness", "Wilderness Travel", Vector2(40, 180), [
|
||||
["Travelers on the road", ["road"], [1, 30]],
|
||||
["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."}],
|
||||
["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]],
|
||||
], {"die": 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"]}],
|
||||
["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"]], ["Giant spider"], ["Troll", ["loot"]], ["Wyvern"]]],
|
||||
["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"]}],
|
||||
["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"], ["A weapon", ["weapons"]], ["A healing potion"],
|
||||
["A pouch of gold", [], null, {"weight": 3}], ["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.die = int(opts.get("die", 0))
|
||||
t.dice = str(opts.get("dice", RollTable.DEFAULT_DICE))
|
||||
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.pipes.append(p)
|
||||
if row.size() > 2:
|
||||
e.add_pipe(p)
|
||||
if row.size() > 2 and row[2] != null:
|
||||
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
|
||||
|
|
|
|||
|
|
@ -3,10 +3,21 @@ 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 = ""
|
||||
## IDs of the tables this entry rolls on next.
|
||||
## 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).
|
||||
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
|
||||
|
|
@ -22,10 +33,68 @@ 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():
|
||||
d["pipes"] = pipes.duplicate()
|
||||
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
|
||||
if has_range:
|
||||
d["range"] = [range_lo, range_hi]
|
||||
return d
|
||||
|
|
@ -33,8 +102,15 @@ func to_dict() -> Dictionary:
|
|||
|
||||
static func from_dict(d: Dictionary) -> TableEntry:
|
||||
var e := TableEntry.new(str(d.get("id", "")), str(d.get("text", "")))
|
||||
for p in d.get("pipes", []):
|
||||
e.pipes.append(str(p))
|
||||
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))
|
||||
var r: Variant = d.get("range")
|
||||
if r is Array and r.size() == 2:
|
||||
e.has_range = true
|
||||
|
|
|
|||
374
tests/test_model.gd
Normal file
374
tests/test_model.gd
Normal file
|
|
@ -0,0 +1,374 @@
|
|||
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
tests/test_model.gd.uid
Normal file
1
tests/test_model.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dut8l77y7pcoa
|
||||
Loading…
Reference in a new issue