The execution loop, node helpers and live display stay in Roller; every Roller function and constant used elsewhere keeps a one-line delegator. No behaviour change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
267 lines
9.9 KiB
GDScript
267 lines
9.9 KiB
GDScript
class_name RollCards
|
|
extends RefCounted
|
|
## How the Roller runs each card kind other than choices: a plain roll's pick
|
|
## (card mode, ranges or weights), routers, checks and loops. The handlers
|
|
## build nodes with Roller's node helpers and push frames on its work stack.
|
|
|
|
|
|
## Rolls an entry the normal way (card mode, ranges or weights). Returns a node
|
|
## with no children yet, or a stop node.
|
|
static func pick_node(t: RollTable, ctx: RollContext) -> Dictionary:
|
|
var rng := ctx.rng
|
|
var index: int
|
|
var value: int
|
|
var reshuffled := false
|
|
var fact: Dictionary
|
|
if t.card_mode:
|
|
var decks: Dictionary = ctx.get_meta("decks", {})
|
|
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 Roller._stop(t, "This table has no results")
|
|
if deck.cards_left(t).x <= 0:
|
|
if t.deck_empty == "stop":
|
|
return Roller._stop(t, "Deck empty")
|
|
deck.reshuffle()
|
|
reshuffled = true
|
|
var card := deck.draw(t, rng)
|
|
index = int(card["index"])
|
|
value = int(card["value"])
|
|
fact = {"type": "roll", "pick": "card", "dice": t.dice_label(), "total": value}
|
|
elif t.is_ranged():
|
|
var was: Variant = ctx.faces
|
|
ctx.faces = []
|
|
var rv := t.roll_value(ctx)
|
|
var faces: Array = ctx.faces
|
|
ctx.faces = was
|
|
if was != null:
|
|
(was as Array).append_array(faces)
|
|
if rv["error"] != "":
|
|
return Roller._stop(t, "Can't roll %s: %s" % [t.dice, rv["error"]])
|
|
value = int(rv["value"])
|
|
fact = {"type": "roll", "pick": "dice", "dice": t.dice.strip_edges(), "faces": faces, "total": value}
|
|
if not faces.is_empty():
|
|
var nat := 0
|
|
for x: int in faces:
|
|
nat += x
|
|
fact["nat"] = nat
|
|
fact["mod"] = value - nat
|
|
index = t.entry_index_clamped(value) if t.is_expr_dice() else t.entry_index_for(value)
|
|
if index < 0:
|
|
return Roller._stop(t, "No result for %s" % t.fmt(value), {"value": value})
|
|
else:
|
|
index = pick_weighted(t, rng)
|
|
if index < 0:
|
|
return Roller._stop(t, "No result can come up")
|
|
value = index + 1
|
|
fact = {"type": "roll", "pick": "weighted", "dice": t.dice_label(), "total": value}
|
|
var node := {"table": t, "index": index, "value": value, "entry": t.entries[index], "children": [],
|
|
"summary": "", "why": [fact]}
|
|
if reshuffled:
|
|
node["reshuffled"] = true
|
|
# "nat" for the caller (Roller._do_roll sets the chain value and drops the key):
|
|
# the dice alone, or a plain table's die value. An expression without
|
|
# dice ("@terms") has none.
|
|
if fact.has("nat"):
|
|
node["nat"] = fact["nat"]
|
|
elif str(fact["pick"]) != "dice":
|
|
node["nat"] = value
|
|
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
|
|
|
|
|
|
# ---------- Routers ----------
|
|
|
|
## The index of the first router case whose condition is true (an empty
|
|
## condition, the Otherwise case, always matches), or -1. Errors count as
|
|
## false and add a line to `log`. `why` gets one fact per case tried:
|
|
## {"type": "case", "index", "expr" ("" for Otherwise), "values", "result",
|
|
## "error"?}.
|
|
static func route(t: RollTable, ctx: RollContext, log: Array = [], why: Array = []) -> int:
|
|
for k in t.entries.size():
|
|
var w := t.entries[k].when.strip_edges()
|
|
if w == "":
|
|
why.append({"type": "case", "index": k, "expr": "", "values": {}, "result": true})
|
|
return k
|
|
var r := Expr.evaluate(w, ctx)
|
|
var fact := {"type": "case", "index": k, "expr": w, "values": Expr.values_read(w, ctx), "result": false}
|
|
why.append(fact)
|
|
if r["error"] != "":
|
|
log.append({"text": "Case %s: %s" % [w, r["error"]], "error": true})
|
|
fact["error"] = str(r["error"])
|
|
elif Expr.truthy(r["value"]):
|
|
fact["result"] = true
|
|
return k
|
|
return -1
|
|
|
|
|
|
static func do_router(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
|
|
var log: Array = []
|
|
var why: Array = []
|
|
var k := route(t, ctx, log, why)
|
|
if k < 0:
|
|
var stop := Roller._stop(t, Roller.NO_CASE, {"kind": RollTable.KIND_ROUTER})
|
|
Roller._log(stop, log)
|
|
Roller._why(stop, why)
|
|
Roller._attach(f, stop, ctx)
|
|
return
|
|
var node := {"table": t, "index": k, "entry": t.entries[k], "children": [], "summary": "",
|
|
"kind": RollTable.KIND_ROUTER, "case": k}
|
|
Roller._log(node, log)
|
|
Roller._why(node, why)
|
|
Roller._attach(f, node, ctx)
|
|
await Roller._enter(node, f, ctx, stack)
|
|
|
|
|
|
# ---------- Checks ----------
|
|
|
|
## Rolls a check card's dice, modifier and target (docs/PLAIN.md §4.1):
|
|
## {"nat", "mod", "total", "target", "success", "faces" (the dice faces),
|
|
## "error" ("" when fine)}. An empty modifier is 0. Numbers are whole
|
|
## (floored).
|
|
static func check_roll(t: RollTable, ctx: RollContext) -> Dictionary:
|
|
var out := {"nat": 0, "mod": 0, "total": 0, "target": 0, "success": false, "faces": [], "error": ""}
|
|
var was: Variant = ctx.faces
|
|
ctx.faces = []
|
|
var r := Expr.evaluate(t.check_dice, ctx)
|
|
var faces: Array = ctx.faces
|
|
ctx.faces = was
|
|
if was != null:
|
|
(was as Array).append_array(faces)
|
|
out["faces"] = faces
|
|
if r["error"] != "":
|
|
out["error"] = "Check dice %s: %s" % [t.check_dice, r["error"]]
|
|
return out
|
|
if not Expr.is_number(r["value"]):
|
|
out["error"] = "Check dice %s gave \"%s\", not a number" % [t.check_dice, Expr.format_value(r["value"])]
|
|
return out
|
|
var nat := Expr.as_int(r, 0)
|
|
var mod := 0
|
|
if t.check_mod.strip_edges() != "":
|
|
var m := Expr.evaluate(t.check_mod, ctx)
|
|
if m["error"] != "" or not Expr.is_number(m["value"]):
|
|
out["error"] = "Check modifier %s: %s" % [t.check_mod, m["error"] if m["error"] != "" else "not a number"]
|
|
return out
|
|
mod = Expr.as_int(m, 0)
|
|
var g := Expr.evaluate(t.check_target, ctx)
|
|
if g["error"] != "" or not Expr.is_number(g["value"]):
|
|
out["error"] = "Check target %s: %s" % [t.check_target, g["error"] if g["error"] != "" else "not a number"]
|
|
return out
|
|
var target := Expr.as_int(g, 0)
|
|
var total := nat + mod
|
|
out["nat"] = nat
|
|
out["mod"] = mod
|
|
out["total"] = total
|
|
out["target"] = target
|
|
out["success"] = total <= target if t.check_cmp == "le" else total >= target
|
|
return out
|
|
|
|
|
|
static func do_check(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
|
|
var c := check_roll(t, ctx)
|
|
if str(c["error"]) != "":
|
|
var stop := Roller._stop(t, "Can't roll the check: %s" % c["error"], {"kind": RollTable.KIND_CHECK})
|
|
stop["effects"] = [{"text": str(c["error"]), "error": true}]
|
|
Roller._attach(f, stop, ctx)
|
|
return
|
|
ctx.chain_vars["nat"] = c["nat"]
|
|
ctx.chain_vars["total"] = c["total"]
|
|
ctx.chain_vars["effect"] = int(c["total"]) - int(c["target"])
|
|
var k := 0 if c["success"] else 1
|
|
var info := {"nat": c["nat"], "mod": c["mod"], "total": c["total"], "target": c["target"], "success": c["success"]}
|
|
var fact := {"type": "check", "dice": t.check_dice.strip_edges(), "mod_expr": t.check_mod.strip_edges(),
|
|
"target_expr": t.check_target.strip_edges(), "faces": c["faces"], "nat": c["nat"], "mod": c["mod"],
|
|
"total": c["total"], "target": c["target"], "cmp": t.check_cmp, "success": c["success"]}
|
|
if k >= t.entries.size():
|
|
var none := Roller._stop(t, "This check has no Failure result", {"kind": RollTable.KIND_CHECK, "check": info, "value": c["total"]})
|
|
Roller._why(none, [fact])
|
|
Roller._attach(f, none, ctx)
|
|
return
|
|
var node := {"table": t, "index": k, "entry": t.entries[k], "value": c["total"], "children": [], "summary": "",
|
|
"kind": RollTable.KIND_CHECK, "check": info, "why": [fact]}
|
|
Roller._attach(f, node, ctx)
|
|
await Roller._enter(node, f, ctx, stack)
|
|
|
|
|
|
# ---------- Loops ----------
|
|
|
|
static func _repeated(n: int) -> String:
|
|
return "Repeated 1 time" if n == 1 else "Repeated %d times" % n
|
|
|
|
|
|
static func start_loop(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
|
|
var header := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": _repeated(0),
|
|
"kind": RollTable.KIND_LOOP, "passes": 0}
|
|
Roller._attach(f, header, ctx)
|
|
var total := 0
|
|
if t.loop_mode == "times":
|
|
var r := Expr.evaluate(t.loop_expr, ctx)
|
|
if r["error"] != "":
|
|
header["effects"] = [{"text": "Repeat %s: %s" % [t.loop_expr, r["error"]], "error": true}]
|
|
else:
|
|
total = maxi(0, Expr.as_int(r, 0))
|
|
stack.append({"op": Roller.OP_LOOP, "node": header, "table": t, "i": 0, "total": total, "depth": f.get("depth", 0),
|
|
"save": f.get("save", ""), "had_i": ctx.chain_vars.has("i"), "prev_i": ctx.chain_vars.get("i")})
|
|
|
|
|
|
## 1 true, 0 false, -1 error (logged on the header).
|
|
static func _cond(t: RollTable, header: Dictionary, ctx: RollContext) -> int:
|
|
var r := Expr.evaluate(t.loop_expr, ctx)
|
|
if r["error"] != "":
|
|
if not header.has("effects"):
|
|
header["effects"] = []
|
|
(header["effects"] as Array).append({"text": "%s %s: %s" % [t.loop_mode.capitalize(), t.loop_expr, r["error"]], "error": true})
|
|
return -1
|
|
return 1 if Expr.truthy(r["value"]) else 0
|
|
|
|
|
|
static func do_loop(f: Dictionary, ctx: RollContext, stack: Array) -> void:
|
|
var t: RollTable = f["table"]
|
|
var header: Dictionary = f["node"]
|
|
var i := int(f["i"])
|
|
var go := false
|
|
match t.loop_mode:
|
|
"times":
|
|
go = i < int(f["total"])
|
|
"while":
|
|
go = _cond(t, header, ctx) == 1
|
|
"until":
|
|
go = i == 0 or _cond(t, header, ctx) == 0
|
|
if go:
|
|
if not Roller._take_action({"parent": header}, t, ctx):
|
|
return
|
|
i += 1
|
|
f["i"] = i
|
|
ctx.chain_vars["i"] = i
|
|
header["passes"] = i
|
|
header["summary"] = _repeated(i)
|
|
var pass_node := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "",
|
|
"kind": RollTable.KIND_LOOP, "pass": i, "value": i}
|
|
(header["children"] as Array).append(pass_node)
|
|
stack.append(f)
|
|
await Roller._enter(pass_node, {"depth": f["depth"]}, ctx, stack)
|
|
return
|
|
if f["had_i"]:
|
|
ctx.chain_vars["i"] = f["prev_i"]
|
|
else:
|
|
ctx.chain_vars.erase("i")
|
|
if str(f["save"]) != "":
|
|
ctx.save(str(f["save"]), i, t.id)
|
|
if t.entries.size() > 1:
|
|
var after := {"table": t, "index": 1, "entry": t.entries[1], "children": [], "summary": "",
|
|
"kind": RollTable.KIND_LOOP, "after": true}
|
|
(header["children"] as Array).append(after)
|
|
await Roller._enter(after, {"depth": f["depth"]}, ctx, stack)
|