TableTower/core/roller.gd

90 lines
2.7 KiB
GDScript3
Raw Normal View History

class_name Roller
extends RefCounted
## Rolls a table and follows its pipes, producing a result tree.
##
## Each node is a Dictionary:
## table: RollTable, value: int (die value), index: int, entry: TableEntry,
## children: Array of nodes, and "stop": String when the chain couldn't continue.
const MAX_DEPTH := 12
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 {}
if depth > MAX_DEPTH:
return {"table": t, "stop": "Chain stopped after %d tables" % MAX_DEPTH, "children": []}
if t.entries.is_empty():
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())
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)
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():
children.append(child)
return {"table": t, "index": index, "value": value, "entry": e, "children": children}
## One line of the result tray for a single node.
static func step_of(n: Dictionary) -> Dictionary:
var t: RollTable = n["table"]
var text: String = n["stop"] if n.has("stop") else (n["entry"] as TableEntry).text
return {
"table": t.name,
"num": t.fmt(n["value"]) if n.has("value") else "",
"die": t.die_size(),
"text": text,
}
## The whole chain in the order it was rolled.
static func flatten(n: Dictionary, out: Array = []) -> Array:
if n.is_empty():
return out
out.append(step_of(n))
for c in n["children"]:
flatten(c, out)
return out
static func reaches(n: Dictionary, table_id: String) -> bool:
if n.is_empty():
return false
if (n["table"] as RollTable).id == table_id:
return true
for c in n["children"]:
if reaches(c, table_id):
return true
return false
## Marks every entry and pipe along the chain as lit.
static func collect_lit(n: Dictionary, entries: Dictionary, pipes: Dictionary) -> void:
if n.is_empty() or n.has("stop"):
return
var t: RollTable = n["table"]
var e: TableEntry = n["entry"]
entries[entry_key(t.id, e.id)] = true
for c in n["children"]:
pipes[pipe_key(t.id, e.id, (c["table"] as RollTable).id)] = true
collect_lit(c, entries, pipes)
static func entry_key(table_id: String, entry_id: String) -> String:
return table_id + ":" + entry_id
static func pipe_key(table_id: String, entry_id: String, to_id: String) -> String:
return "%s:%s>%s" % [table_id, entry_id, to_id]