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>
260 lines
10 KiB
GDScript
260 lines
10 KiB
GDScript
class_name RollChoice
|
|
extends RefCounted
|
|
## Choice cards for the Roller: the prompt request, show_if and dynamic
|
|
## options (options_from / options_where), asking the player, and running the
|
|
## answer.
|
|
|
|
|
|
## The prompt request for a choice card (docs/LOGIC.md §8):
|
|
## {table_id, kind ("pick" | "number" | "text"), title, prompt (BBCode,
|
|
## rendered), options: [{index, entry, text, details, weight, ...}], min, max,
|
|
## default, log (error lines from show_if and options_where), hidden (how many
|
|
## fixed options show_if hid)}.
|
|
## A pick's options are its fixed options whose show_if holds (index = entry
|
|
## = the entry's index), then, on a dynamic card (options_from), one option
|
|
## per candidate variable or list item (index = entries.size() + j, entry =
|
|
## 0, the Chosen entry, plus "dynamic": true, "option", "label", "value" and
|
|
## "value_text"). The reply is an option's index, or -1 for Random.
|
|
static func request_for(t: RollTable, ctx: RollContext) -> Dictionary:
|
|
var options: Array = []
|
|
var log: Array = []
|
|
var why: Array = []
|
|
var hidden := 0
|
|
var chosen_hidden := false
|
|
if t.choice == "pick":
|
|
var ranged := t.is_ranged()
|
|
for k in range(t.fixed_start(), t.entries.size()):
|
|
var e := t.entries[k]
|
|
if not option_shown(e, ctx, log):
|
|
hidden += 1
|
|
continue
|
|
options.append({"index": k, "entry": k, "text": TextExpander.render(e.text, ctx), "details": e.details,
|
|
"weight": e.span() if ranged else maxi(0, e.weight)})
|
|
if t.is_dynamic() and not t.entries.is_empty() and not option_shown(t.entries[0], ctx, log):
|
|
chosen_hidden = true
|
|
elif t.is_dynamic() and not t.entries.is_empty():
|
|
var chosen := t.entries[0]
|
|
var cands := dynamic_options(t, ctx, log, why)
|
|
for j in cands.size():
|
|
var c: Dictionary = cands[j]
|
|
var vt := Expr.format_value(c["value"]) if str(c["kind"]) == "prefix" else ""
|
|
var label := str(c["label"])
|
|
var shown := label if vt == "" else "%s %s" % [label, vt]
|
|
options.append({"index": t.entries.size() + j, "entry": 0, "text": Formatter.escape_literal(shown),
|
|
"details": chosen.details, "weight": maxi(0, chosen.weight), "dynamic": true,
|
|
"option": c["option"], "label": label, "value": c["value"], "value_text": vt})
|
|
var lo := Expr.eval_int(t.min_expr, ctx, 0)
|
|
var hi := maxi(lo, Expr.eval_int(t.max_expr, ctx, 99))
|
|
var def: Variant = -1
|
|
if t.choice == "number":
|
|
def = lo
|
|
elif t.choice == "text":
|
|
def = ""
|
|
if hidden > 0 or chosen_hidden:
|
|
why.push_front({"type": "show_if", "hidden": hidden, "chosen_hidden": chosen_hidden})
|
|
return {"table_id": t.id, "kind": t.choice, "title": t.name, "prompt": TextExpander.render(t.prompt, ctx),
|
|
"options": options, "min": lo, "max": hi, "default": def, "log": log, "hidden": hidden, "why": why}
|
|
|
|
|
|
## Whether a pick option is offered now: its show_if is empty or true. An
|
|
## error counts as false and adds a line to `log`.
|
|
static func option_shown(e: TableEntry, ctx: RollContext, log: Array = []) -> bool:
|
|
var w := e.show_if.strip_edges()
|
|
if w == "":
|
|
return true
|
|
var r := Expr.evaluate(w, ctx)
|
|
if r["error"] != "":
|
|
log.append({"text": "Show only if %s: %s" % [w, r["error"]], "error": true})
|
|
return false
|
|
return Expr.truthy(r["value"])
|
|
|
|
|
|
## The candidates of a dynamic pick card (options_from, filtered by
|
|
## options_where), in order: Array of {kind ("prefix" | "list"), option (the
|
|
## variable name without "@", or the list item), label, value}. A prefix
|
|
## gives one per set variable, sorted by label ("Pilot"); a list gives one
|
|
## per item, in list order (label and value are the item). A filter error
|
|
## counts as false and adds one line to `log`. With a filter, `why` gets
|
|
## {"type": "options_where", "from", "expr", "kept", "total"}.
|
|
static func dynamic_options(t: RollTable, ctx: RollContext, log: Array = [], why: Array = []) -> Array:
|
|
var out: Array = []
|
|
var src := RollTable.parse_options_from(t.options_from)
|
|
if str(src["error"]) != "":
|
|
log.append({"text": "Options from %s: %s" % [t.options_from.strip_edges(), src["error"]], "error": true})
|
|
return out
|
|
var name := str(src["name"])
|
|
var cands: Array = []
|
|
match str(src["kind"]):
|
|
"prefix":
|
|
for v in ctx.list_vars(name):
|
|
cands.append({"kind": "prefix", "option": v["name"], "label": v["label"], "value": v["value"]})
|
|
"list":
|
|
var cur: Variant = ctx.get_value("@" + name)
|
|
for item in Expr.list_items(cur if cur != null else ""):
|
|
cands.append({"kind": "list", "option": item, "label": item, "value": item})
|
|
var where := t.options_where.strip_edges()
|
|
if where == "":
|
|
return cands
|
|
var saved := {}
|
|
for k in OPTION_VARS:
|
|
if ctx.chain_vars.has(k):
|
|
saved[k] = ctx.chain_vars[k]
|
|
var failed := false
|
|
for c: Dictionary in cands:
|
|
_bind_option(ctx, c)
|
|
var r := Expr.evaluate(where, ctx)
|
|
if r["error"] != "":
|
|
if not failed:
|
|
failed = true
|
|
log.append({"text": "Only where %s: %s" % [where, r["error"]], "error": true})
|
|
elif Expr.truthy(r["value"]):
|
|
out.append(c)
|
|
for k in OPTION_VARS:
|
|
if saved.has(k):
|
|
ctx.chain_vars[k] = saved[k]
|
|
else:
|
|
ctx.chain_vars.erase(k)
|
|
why.append({"type": "options_where", "from": t.options_from.strip_edges(), "expr": where, "kept": out.size(), "total": cands.size()})
|
|
return out
|
|
|
|
|
|
## How many options a pick card offers right now (show_if and options_from
|
|
## included); for the card's live count.
|
|
static func available_count(t: RollTable, ctx: RollContext) -> int:
|
|
return (request_for(t, ctx)["options"] as Array).size()
|
|
|
|
|
|
## The chain variables a dynamic option sets.
|
|
const OPTION_VARS: Array[String] = ["option", "option_label", "option_value"]
|
|
## The default text of a dynamic card's Chosen entry: the result then reads as
|
|
## the picked option's label.
|
|
const CHOSEN := "Chosen"
|
|
|
|
|
|
static func _bind_option(ctx: RollContext, c: Dictionary) -> void:
|
|
ctx.chain_vars["option"] = c["option"]
|
|
ctx.chain_vars["option_label"] = c["label"]
|
|
ctx.chain_vars["option_value"] = Expr.normalize(c["value"])
|
|
|
|
|
|
## The headless answer to a request: Random for a pick, min for a number, ""
|
|
## for text.
|
|
static func default_reply(req: Dictionary) -> Variant:
|
|
match str(req.get("kind", "pick")):
|
|
"number":
|
|
return int(req.get("min", 0))
|
|
"text":
|
|
return ""
|
|
return -1
|
|
|
|
|
|
## Asks the player through ctx.prompt, or gives the headless answer.
|
|
static func ask(ctx: RollContext, req: Dictionary) -> Variant:
|
|
if ctx.no_prompt or not ctx.prompt.is_valid():
|
|
return default_reply(req)
|
|
return await ctx.prompt.call(req)
|
|
|
|
|
|
static func run(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
|
|
var req := request_for(t, ctx)
|
|
var opts: Array = req["options"]
|
|
if t.choice == "pick" and opts.is_empty():
|
|
var none := Roller._stop(t, Roller.NO_OPTIONS, {"kind": RollTable.KIND_CHOICE})
|
|
Roller._log(none, req["log"])
|
|
Roller._why(none, req["why"])
|
|
Roller._attach(f, none, ctx)
|
|
return
|
|
var reply: Variant = await ask(ctx, req)
|
|
if reply == null:
|
|
Roller._attach(f, Roller._stop(t, Roller.CANCELLED, {"kind": RollTable.KIND_CHOICE, "cancelled": true}), ctx)
|
|
ctx.halted = Roller.CANCELLED
|
|
return
|
|
match t.choice:
|
|
"number":
|
|
var v := int(req["min"])
|
|
if reply is int or reply is float:
|
|
v = int(reply)
|
|
elif reply is String and (reply as String).strip_edges().is_valid_int():
|
|
v = (reply as String).strip_edges().to_int()
|
|
v = clampi(v, int(req["min"]), int(req["max"]))
|
|
await _answered(t, f, ctx, stack, v, str(v))
|
|
"text":
|
|
var s := str(reply)
|
|
await _answered(t, f, ctx, stack, s, Formatter.close_open_tags(s))
|
|
_:
|
|
var idx := int(reply) if (reply is int or reply is float) else -1
|
|
var opt: Dictionary = {}
|
|
for o: Dictionary in opts:
|
|
if int(o["index"]) == idx:
|
|
opt = o
|
|
break
|
|
var node: Dictionary
|
|
if not opt.is_empty():
|
|
node = _option_node(t, opt, ctx)
|
|
node["picked"] = true
|
|
elif not t.is_dynamic() and int(req["hidden"]) == 0:
|
|
# A plain fixed list: Random rolls the card the usual way
|
|
# (weights, ranges, card mode).
|
|
node = RollCards.pick_node(t, ctx)
|
|
node.erase("nat")
|
|
node["random"] = true
|
|
else:
|
|
var k := _pick_option(opts, ctx.rng)
|
|
if k < 0:
|
|
node = Roller._stop(t, "No result can come up")
|
|
else:
|
|
node = _option_node(t, opts[k], ctx)
|
|
node["random"] = true
|
|
node["kind"] = RollTable.KIND_CHOICE
|
|
Roller._log(node, req["log"])
|
|
Roller._why(node, req["why"])
|
|
Roller._attach(f, node, ctx)
|
|
if node.has("stop"):
|
|
return
|
|
await Roller._enter(node, f, ctx, stack)
|
|
|
|
|
|
## The node for a pick option from a request: a fixed entry (a card-mode deck
|
|
## counts the draw), or the Chosen entry for a dynamic option, which binds
|
|
## option, option_label and option_value first.
|
|
static func _option_node(t: RollTable, o: Dictionary, ctx: RollContext) -> Dictionary:
|
|
var ei := int(o.get("entry", o["index"]))
|
|
var node := {"table": t, "index": ei, "entry": t.entries[ei], "children": [], "summary": ""}
|
|
if o.get("dynamic", false):
|
|
_bind_option(ctx, {"option": o["option"], "label": o["label"], "value": o["value"]})
|
|
node["option"] = str(o["label"])
|
|
elif 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]
|
|
var eid := t.entries[ei].id
|
|
deck.drawn[eid] = int(deck.drawn.get(eid, 0)) + 1
|
|
return node
|
|
|
|
|
|
## Random among a request's options by their "weight" (each dynamic option
|
|
## weighs as much as the Chosen entry; fixed ones their own weight, or span
|
|
## on a ranged card). Position in `opts`, or -1 when every weight is 0.
|
|
static func _pick_option(opts: Array, rng: RandomNumberGenerator) -> int:
|
|
var total := 0
|
|
for o: Dictionary in opts:
|
|
total += maxi(0, int(o.get("weight", 1)))
|
|
if total <= 0:
|
|
return -1
|
|
var pick := rng.randi_range(0, total - 1)
|
|
for k in opts.size():
|
|
pick -= maxi(0, int((opts[k] as Dictionary).get("weight", 1)))
|
|
if pick < 0:
|
|
return k
|
|
return -1
|
|
|
|
|
|
static func _answered(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array, value: Variant, summary: String) -> void:
|
|
ctx.chain_vars["answer"] = value
|
|
if t.save_as != "":
|
|
ctx.save(t.save_as, value, t.id)
|
|
var node := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": summary,
|
|
"kind": RollTable.KIND_CHOICE, "answer": value}
|
|
Roller._attach(f, node, ctx)
|
|
await Roller._enter(node, f, ctx, stack, false)
|