TableTower/core/roll_cards.gd
RobinFiredrake a7fb931bb4 Rerolls show in the roll animation; MainRollingShow split out
A result that came up but was rolled again (a thread's roll again, Only
if) now flickers with a floating "rolled again" before the kept result
lights. main_rolling.gd hit 412 lines, so showing a roll at once moved to
MainRollingShow (delegators kept).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 14:25:21 -06:00

331 lines
13 KiB
GDScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.
## Most times a thread rolls again on the results it skips before giving up.
const MAX_REROLLS := 100
const ALL_REROLLED := "This thread rolls again on every result"
const NONE_ALLOWED := "Nothing on this card can come up right now: every result's Only if is false"
## pick_node() for the frame `f` that reached the card: its thread may roll
## with other dice (f.dice) and roll again on some results (f.reroll, result
## ids). A result whose "Only if" (show_if) is false right now is rolled
## again too. Skipped rolls go in a {"type": "reroll", "skipped": [{value,
## text}]} why fact on the kept node.
static func pick_for(t: RollTable, ctx: RollContext, f: Dictionary) -> Dictionary:
var dice := str(f.get("dice", ""))
var thread_skip: Array = f.get("reroll", [])
var skip: Array = thread_skip.duplicate()
if t.kind == RollTable.KIND_ROLL:
for e in t.entries:
if e.show_if.strip_edges() != "" and not skip.has(e.id) and not RollChoice.option_shown(e, ctx):
skip.append(e.id)
if skip.is_empty():
return pick_node(t, ctx, dice)
var left := false
for e in t.entries:
if not skip.has(e.id) and t.can_come_up(e):
left = true
if not left:
return Roller._stop(t, ALL_REROLLED if skip.size() == thread_skip.size() else NONE_ALLOWED)
var skipped: Array = []
for n in MAX_REROLLS:
var node := pick_node(t, ctx, dice)
if node.has("stop") or not skip.has((node["entry"] as TableEntry).id):
if not skipped.is_empty():
Roller._why(node, [{"type": "reroll", "skipped": skipped}])
return node
skipped.append({"value": node["value"], "text": Formatter.strip_tags((node["entry"] as TableEntry).text).strip_edges(),
"entry_id": (node["entry"] as TableEntry).id})
return Roller._stop(t, ALL_REROLLED)
## Rolls an entry the normal way (card mode, ranges or weights). Returns a node
## with no children yet, or a stop node. `dice` (a thread's "roll with …
## instead") replaces a ranged card's own dice; past the ends then counts as
## the end result.
static func pick_node(t: RollTable, ctx: RollContext, dice: String = "") -> 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":
# Waits for Shuffle: the card gives its empty result and the chain ends here.
return Roller._stop(t, t.empty_text(), {"deck_empty": true})
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 := RollRange.roll_value(t, ctx, dice)
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" % [RollRange.join(dice, t.dice_mod) if dice != "" else t.roll_text(), rv["error"]])
value = int(rv["value"])
fact = {"type": "roll", "pick": "dice", "dice": RollRange.join(dice, t.dice_mod) if dice != "" else t.roll_text(), "faces": faces, "total": value}
if rv.has("limited"):
fact["limited"] = rv["limited"]
fact["limit_expr"] = rv["limit_expr"]
fact["raw"] = rv["raw"]
# The Why line names the modifier ("+3 for Luck") when it's all of the change.
if dice == "" and t.has_mod() and not t.is_expr_dice() and t.dice_obj().bonus == 0:
fact["mod_expr"] = t.dice_mod.strip_edges()
if not faces.is_empty():
var nat := 0
for x: int in faces:
nat += x
fact["nat"] = nat
fact["mod"] = int(fact.get("raw", value)) - nat
index = RollRange.index_for(t, value, dice != "")
if t.clamps() or dice != "":
var span := RollRange.span(t)
if value < span.x or value > span.y:
fact["counts_as"] = clampi(value, span.x, span.y)
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}
# A plain table's modifier moves the pick down (+) or up (−) the list by
# that many rows; the first and last rows catch anything past them.
if t.has_mod():
var shift := RollRange.modifier(t.dice_mod, ctx)
if shift["error"] != "":
return Roller._stop(t, "Can't work out the modifier %s: %s" % [t.dice_mod.strip_edges(), shift["error"]])
var moved := clampi(index + int(shift["value"]), 0, t.entries.size() - 1)
fact["mod"] = int(shift["value"])
fact["mod_expr"] = t.dice_mod.strip_edges()
fact["from"] = value
index = moved
value = index + 1
fact["total"] = value
var node := {"table": t, "index": index, "value": value, "entry": t.entries[index], "children": [],
"summary": "", "why": [fact]}
if reshuffled:
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 m := RollRange.modifier(t.check_mod, ctx)
if m["error"] != "":
out["error"] = "Check modifier %s: %s" % [t.check_mod, m["error"]]
return out
var mod: int = m["value"]
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)