Combine repeated rolls: add together, keep highest/lowest, or let me choose
A thread that rolls its card more than once gets a 'then' choice (TableEntry.pipe_combine, JSON "combine"): keep every roll (as before), add them together, keep the highest or lowest, or let the player choose (the choice pop-up). The repeats hold their own threads until the combine step (Roller.OP_COMBINE, RollCombine) keeps one, which then follows its threads; save-as keeps the total or the kept result. Set-aside rolls show faded in the tray. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
193794a9e0
commit
1ca38f35b6
10 changed files with 272 additions and 4 deletions
95
core/roll_combine.gd
Normal file
95
core/roll_combine.gd
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
class_name RollCombine
|
||||
extends RefCounted
|
||||
## Repeated rolls, combined. A thread that rolls its card more than once can
|
||||
## keep every roll ("all", the default), add them together ("sum"), keep the
|
||||
## highest or lowest ("max", "min"), or let the player choose one ("choose").
|
||||
## When combining, the repeated rolls don't follow their own threads; the kept
|
||||
## one does, once the combine step has run (Roller.OP_COMBINE). A roll's number
|
||||
## is its result text when that is a number, else the die total.
|
||||
|
||||
const MODES := ["all", "sum", "max", "min", "choose"]
|
||||
const LABELS := ["Keep every roll", "Add them together", "Keep the highest", "Keep the lowest", "Let me choose"]
|
||||
|
||||
|
||||
static func value_of(n: Dictionary) -> float:
|
||||
var t := Formatter.strip_tags(str(n.get("summary", ""))).strip_edges()
|
||||
if t.is_valid_float():
|
||||
return t.to_float()
|
||||
return float(n.get("value", 0))
|
||||
|
||||
|
||||
## Runs the combine frame `f` {node, to, mode, start, save}: returns the node
|
||||
## whose threads should now run, or {} for none (a total, or nothing rolled).
|
||||
static func run(f: Dictionary, ctx: RollContext) -> Dictionary:
|
||||
var node: Dictionary = f["node"]
|
||||
var kids: Array = []
|
||||
var all_kids: Array = node["children"]
|
||||
for i in range(int(f["start"]), all_kids.size()):
|
||||
var k: Dictionary = all_kids[i]
|
||||
var t: RollTable = k.get("table")
|
||||
if t and t.id == str(f["to"]) and not k.get("inline", false) and not k.has("stop"):
|
||||
kids.append(k)
|
||||
if kids.is_empty():
|
||||
return {}
|
||||
var mode := str(f["mode"])
|
||||
var keep: Dictionary = {}
|
||||
match mode:
|
||||
"sum":
|
||||
var total := 0.0
|
||||
var parts := PackedStringArray()
|
||||
for k: Dictionary in kids:
|
||||
total += value_of(k)
|
||||
parts.append(_fmt(value_of(k)))
|
||||
k["dropped"] = true
|
||||
var t: RollTable = kids[0]["table"]
|
||||
var sum := {"table": t, "children": [], "summary": _fmt(total), "combined": "sum",
|
||||
"why": [{"type": "combine", "mode": "sum", "parts": parts, "total": total}]}
|
||||
all_kids.append(sum)
|
||||
_save(f, ctx, total, t)
|
||||
return {}
|
||||
"max", "min":
|
||||
keep = kids[0]
|
||||
for k: Dictionary in kids:
|
||||
if (mode == "max" and value_of(k) > value_of(keep)) or (mode == "min" and value_of(k) < value_of(keep)):
|
||||
keep = k
|
||||
"choose":
|
||||
keep = await _ask(kids, ctx)
|
||||
if keep.is_empty():
|
||||
ctx.halted = Roller.CANCELLED
|
||||
return {}
|
||||
_:
|
||||
return {}
|
||||
for k: Dictionary in kids:
|
||||
if not is_same(k, keep):
|
||||
k["dropped"] = true
|
||||
keep["kept"] = mode
|
||||
_save(f, ctx, Formatter.to_export_bbcode(str(keep.get("summary", ""))), keep["table"])
|
||||
return keep
|
||||
|
||||
|
||||
## Asks which roll to keep, with the same pop-up as a choice card.
|
||||
static func _ask(kids: Array, ctx: RollContext) -> Dictionary:
|
||||
var t: RollTable = kids[0]["table"]
|
||||
var options: Array = []
|
||||
for i in kids.size():
|
||||
options.append({"index": i, "entry": int(kids[i].get("index", 0)), "text": str(kids[i].get("summary", "")),
|
||||
"details": "", "weight": 1})
|
||||
var req := {"table_id": t.id, "kind": "pick", "title": t.name, "prompt": "Keep which roll?",
|
||||
"options": options, "min": 0, "max": 0, "default": -1, "log": [], "hidden": 0, "why": [], "combine": true}
|
||||
var reply: Variant = await RollChoice.ask(ctx, req)
|
||||
if reply == null:
|
||||
return {}
|
||||
var i := int(reply)
|
||||
if i < 0 or i >= kids.size():
|
||||
i = ctx.rng.randi_range(0, kids.size() - 1)
|
||||
return kids[i]
|
||||
|
||||
|
||||
static func _save(f: Dictionary, ctx: RollContext, v: Variant, t: RollTable) -> void:
|
||||
var save := str(f.get("save", ""))
|
||||
if save != "":
|
||||
ctx.save(save, v, t.id)
|
||||
|
||||
|
||||
static func _fmt(x: float) -> String:
|
||||
return str(int(x)) if is_equal_approx(x, roundf(x)) else str(snappedf(x, 0.01))
|
||||
1
core/roll_combine.gd.uid
Normal file
1
core/roll_combine.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://by3putyoyufm1
|
||||
|
|
@ -36,7 +36,7 @@ static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
|
|||
step["kind"] = n["kind"]
|
||||
if n.has("effects"):
|
||||
step["effects"] = (n["effects"] as Array).duplicate(true)
|
||||
for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled", "deck_empty", "case", "option", "check", "inputs"]:
|
||||
for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled", "deck_empty", "dropped", "kept", "combined", "case", "option", "check", "inputs"]:
|
||||
if n.has(k):
|
||||
step[k] = n[k]
|
||||
if n.has("why"):
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ const CANCELLED := "Cancelled"
|
|||
const NO_CASE := "No case matched"
|
||||
const NO_OPTIONS := "No options available"
|
||||
|
||||
enum { OP_ROLL, OP_PIPE, OP_LOOP, OP_RESTORE }
|
||||
enum { OP_ROLL, OP_PIPE, OP_LOOP, OP_RESTORE, OP_COMBINE }
|
||||
|
||||
|
||||
## A RollContext wired to this board: it resolves [[names]] against the board's
|
||||
|
|
@ -194,6 +194,10 @@ static func _chain(board: TowerBoard, table_id: String, depth: int, ctx: RollCon
|
|||
await RollCards.do_loop(f, ctx, stack)
|
||||
OP_RESTORE:
|
||||
RollPipes.restore(f, ctx)
|
||||
OP_COMBINE:
|
||||
var keep: Dictionary = await RollCombine.run(f, ctx)
|
||||
if not keep.is_empty():
|
||||
_queue_pipes(keep, ctx, stack, int(f["depth"]))
|
||||
# A halted roll leaves frames behind: put back any card inputs they hid.
|
||||
while not stack.is_empty():
|
||||
var rest: Dictionary = stack.pop_back()
|
||||
|
|
@ -316,6 +320,17 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr
|
|||
ctx.save(t.save_as, Formatter.strip_tags(str(node["summary"])).strip_edges(), t.id)
|
||||
if e.pipes.is_empty():
|
||||
return
|
||||
# A roll that is being combined with others (RollCombine) waits: only the
|
||||
# one that's kept follows its threads.
|
||||
if f.get("no_follow", false):
|
||||
return
|
||||
_queue_pipes(node, ctx, stack, depth)
|
||||
|
||||
|
||||
## Snapshots a result's threads (RollPipes.pipe_plan) and queues the ones
|
||||
## that run, last first so they run in order.
|
||||
static func _queue_pipes(node: Dictionary, ctx: RollContext, stack: Array, depth: int) -> void:
|
||||
var e: TableEntry = node["entry"]
|
||||
var log: Array = []
|
||||
var why: Array = []
|
||||
var plan := RollPipes.pipe_plan(e, ctx, log, why)
|
||||
|
|
@ -329,6 +344,13 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr
|
|||
var fr := {"op": OP_PIPE, "node": node, "entry": e, "to": p, "left": int(item["count"]), "save": e.save_for(p), "depth": depth}
|
||||
if item.has("with"):
|
||||
fr["with"] = item["with"]
|
||||
var mode := e.combine_for(p)
|
||||
if mode != "all" and int(item["count"]) > 1:
|
||||
# Runs after every repeat: combines them (RollCombine).
|
||||
stack.append({"op": OP_COMBINE, "node": node, "to": p, "mode": mode, "save": fr["save"],
|
||||
"start": (node["children"] as Array).size(), "depth": depth})
|
||||
fr["no_follow"] = true
|
||||
fr["save"] = ""
|
||||
stack.append(fr)
|
||||
|
||||
|
||||
|
|
@ -362,6 +384,8 @@ static func _do_pipe(board: TowerBoard, f: Dictionary, ctx: RollContext, stack:
|
|||
var fr := {"op": OP_ROLL, "id": f["to"], "parent": f["node"], "save": f["save"], "depth": f["depth"]}
|
||||
if f.has("with"):
|
||||
fr["with"] = f["with"]
|
||||
if f.get("no_follow", false):
|
||||
fr["no_follow"] = true
|
||||
stack.append(fr)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -39,6 +39,9 @@ var pipe_color: Dictionary = {}
|
|||
## The Book page this result is linked to ("" = none). Its text and details
|
||||
## follow the page (TowerBoard.sync_page).
|
||||
var page: String = ""
|
||||
## target table id -> how repeated rolls combine: "sum", "max", "min" or
|
||||
## "choose" (RollCombine). Missing = keep every roll.
|
||||
var pipe_combine: Dictionary = {}
|
||||
## Router cards: this case's condition. "" is the Otherwise case (always
|
||||
## matches). Ignored on other kinds.
|
||||
var when: String = ""
|
||||
|
|
@ -198,6 +201,11 @@ func add_pipe(target: String, count: Variant = 1, save_as: String = "") -> void:
|
|||
set_pipe_save(target, save_as)
|
||||
|
||||
|
||||
## How a thread's repeated rolls combine (RollCombine.MODES).
|
||||
func combine_for(target: String) -> String:
|
||||
return str(pipe_combine.get(target, "all"))
|
||||
|
||||
|
||||
## Removes a pipe along with its options.
|
||||
func remove_pipe(target: String) -> void:
|
||||
pipes.erase(target)
|
||||
|
|
@ -207,6 +215,7 @@ func remove_pipe(target: String) -> void:
|
|||
pipe_otherwise.erase(target)
|
||||
pipe_with.erase(target)
|
||||
pipe_color.erase(target)
|
||||
pipe_combine.erase(target)
|
||||
|
||||
|
||||
func to_dict() -> Dictionary:
|
||||
|
|
@ -231,7 +240,8 @@ func to_dict() -> Dictionary:
|
|||
var other := is_otherwise(p)
|
||||
var wv: Variant = pipe_with.get(p)
|
||||
var col := str(pipe_color.get(p, ""))
|
||||
if expr == "" and n == 1 and s == "" and w == "" and not other and wv == null and col == "":
|
||||
var comb := combine_for(p)
|
||||
if expr == "" and n == 1 and s == "" and w == "" and not other and wv == null and col == "" and comb == "all":
|
||||
list.append(p)
|
||||
else:
|
||||
var po := {"table": p}
|
||||
|
|
@ -249,6 +259,8 @@ func to_dict() -> Dictionary:
|
|||
po["with"] = (wv as Dictionary).duplicate()
|
||||
if col != "":
|
||||
po["color"] = col
|
||||
if comb != "all":
|
||||
po["combine"] = comb
|
||||
list.append(po)
|
||||
d["pipes"] = list
|
||||
if has_range:
|
||||
|
|
@ -278,6 +290,8 @@ static func from_dict(d: Dictionary) -> TableEntry:
|
|||
e.set_pipe_with(target, p["with"])
|
||||
if str(p.get("color", "")) != "":
|
||||
e.pipe_color[target] = str(p["color"])
|
||||
if RollCombine.MODES.has(str(p.get("combine", "all"))) and str(p.get("combine", "all")) != "all":
|
||||
e.pipe_combine[target] = str(p["combine"])
|
||||
elif str(p) != "":
|
||||
e.add_pipe(str(p))
|
||||
var r: Variant = d.get("range")
|
||||
|
|
|
|||
99
tests/test_roll_features.gd
Normal file
99
tests/test_roll_features.gd
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
extends SceneTree
|
||||
## Roll features in the engine: combining a thread's repeated rolls (add,
|
||||
## highest, lowest, choose), saving the combined value, and only the kept roll
|
||||
## following its threads.
|
||||
## Run: godot --headless --path . -s res://tests/test_roll_features.gd
|
||||
|
||||
var _failures := 0
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
_test_combine()
|
||||
await _test_choose()
|
||||
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
|
||||
quit(1 if _failures else 0)
|
||||
|
||||
|
||||
## Start → Gold ×3; Gold's results are numbers, and each pipes on to Note.
|
||||
func _board(mode: String) -> TowerBoard:
|
||||
var b := TowerBoard.new()
|
||||
var start := RollTable.new("start", "Start")
|
||||
var e := TableEntry.new("e1", "Treasure")
|
||||
e.add_pipe("gold", 3, "loot")
|
||||
if mode != "all":
|
||||
e.pipe_combine["gold"] = mode
|
||||
start.entries.append(e)
|
||||
var gold := RollTable.new("gold", "Gold")
|
||||
for i in 6:
|
||||
var g := TableEntry.new("g%d" % i, str((i + 1) * 10))
|
||||
g.add_pipe("note")
|
||||
gold.entries.append(g)
|
||||
var note := RollTable.new("note", "Note")
|
||||
note.entries.append(TableEntry.new("n1", "Noted"))
|
||||
for t in [start, gold, note]:
|
||||
b.tables.append(t)
|
||||
return b
|
||||
|
||||
|
||||
func _kids(tree: Dictionary, tid: String) -> Array:
|
||||
return (tree["children"] as Array).filter(func(k: Dictionary) -> bool: return (k["table"] as RollTable).id == tid)
|
||||
|
||||
|
||||
func _test_combine() -> void:
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = 7
|
||||
var tree := Roller.roll(_board("all"), "start", rng)
|
||||
_check(_kids(tree, "gold").size() == 3, "keep every roll: three Gold results")
|
||||
_check((_kids(tree, "gold")[0]["children"] as Array).size() == 1, "and each follows its own thread")
|
||||
|
||||
var b := _board("sum")
|
||||
var ctx := Roller.new_context(b, rng)
|
||||
tree = Roller.roll(b, "start", rng, 0, {}, ctx)
|
||||
var golds := _kids(tree, "gold")
|
||||
var total := 0
|
||||
for k: Dictionary in golds:
|
||||
if not k.has("combined"):
|
||||
total += int(str(k["summary"]))
|
||||
_check(k.get("dropped", false) and (k["children"] as Array).is_empty(), "added rolls don't follow their threads")
|
||||
var sum: Dictionary = golds[golds.size() - 1]
|
||||
_check(sum.get("combined") == "sum" and int(str(sum["summary"])) == total, "add together: a total of %d" % total)
|
||||
_check(int(ctx.lookup("loot")) == total, "save as keeps the total")
|
||||
|
||||
b = _board("max")
|
||||
tree = Roller.roll(b, "start", rng)
|
||||
golds = _kids(tree, "gold")
|
||||
var best: Dictionary = {}
|
||||
for k: Dictionary in golds:
|
||||
if not k.get("dropped", false):
|
||||
best = k
|
||||
var top := 0
|
||||
for k: Dictionary in golds:
|
||||
top = maxi(top, int(str(k["summary"])))
|
||||
_check(best.get("kept") == "max" and int(str(best["summary"])) == top, "keep the highest keeps %d" % top)
|
||||
_check((best["children"] as Array).size() == 1, "the kept roll follows its thread")
|
||||
var flat := Roller.flatten(tree, [])
|
||||
_check(flat.any(func(s: Dictionary) -> bool: return s.get("dropped", false)), "set-aside rolls are marked in the steps")
|
||||
|
||||
var back := TableEntry.from_dict(b.get_table("start").entries[0].to_dict())
|
||||
_check(back.combine_for("gold") == "max", "the combine mode is saved")
|
||||
|
||||
|
||||
func _test_choose() -> void:
|
||||
var b := _board("choose")
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = 3
|
||||
var ctx := Roller.new_context(b, rng)
|
||||
var asked: Array = []
|
||||
ctx.prompt = func(req: Dictionary) -> Variant:
|
||||
asked.append(req)
|
||||
return 1
|
||||
var tree: Dictionary = await Roller.roll_async(b, "start", ctx)
|
||||
var golds := _kids(tree, "gold")
|
||||
_check(asked.size() == 1 and (asked[0]["options"] as Array).size() == 3, "let me choose asks once, with the three rolls")
|
||||
_check(golds[1].get("kept") == "choose" and golds[0].get("dropped", false), "the picked roll is kept")
|
||||
|
||||
|
||||
func _check(ok: bool, what: String) -> void:
|
||||
if not ok:
|
||||
_failures += 1
|
||||
print("FAIL ", what)
|
||||
1
tests/test_roll_features.gd.uid
Normal file
1
tests/test_roll_features.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bg7ass7t6g5tu
|
||||
|
|
@ -322,6 +322,17 @@ func set_pipe_count(to: String, s: String) -> void:
|
|||
wrote(selected_table())
|
||||
|
||||
|
||||
func set_pipe_combine(to: String, mode: String) -> void:
|
||||
var e := _pipe_entry()
|
||||
if e == null or e.combine_for(to) == mode:
|
||||
return
|
||||
if mode == "all":
|
||||
e.pipe_combine.erase(to)
|
||||
else:
|
||||
e.pipe_combine[to] = mode
|
||||
wrote(selected_table())
|
||||
|
||||
|
||||
func set_pipe_save(to: String, s: String) -> void:
|
||||
var e := _pipe_entry()
|
||||
if e == null or _save_error(s) != "" or s.strip_edges() == e.save_for(to):
|
||||
|
|
@ -664,7 +675,16 @@ func _pipe_box(t: RollTable, e: TableEntry, to: String) -> Control:
|
|||
set_pipe_count(to, s)
|
||||
)
|
||||
cr.add_child(count)
|
||||
cr.add_child(InspectorKit.word("times"))
|
||||
cr.add_child(InspectorKit.word("times, then"))
|
||||
var then := OptionButton.new()
|
||||
ModalCard.style_popup(then.get_popup())
|
||||
for i in RollCombine.LABELS.size():
|
||||
then.add_item(RollCombine.LABELS[i], i)
|
||||
then.select(maxi(0, RollCombine.MODES.find(e.combine_for(to))))
|
||||
then.tooltip_text = "What to do with the rolls when there's more than one (rerolls, best of two, totals…)"
|
||||
then.item_selected.connect(func(i: int) -> void: set_pipe_combine(to, RollCombine.MODES[i]))
|
||||
cr.add_child(then)
|
||||
parts["combine"] = then
|
||||
var sr := InspectorKit.hbox(6)
|
||||
sr.add_child(InspectorKit.word("Saves as"))
|
||||
var save := InspectorKit.line(e.save_for(to), "nothing (or a name)")
|
||||
|
|
|
|||
|
|
@ -23,6 +23,9 @@ static func chip(tray: ResultTray, step: Dictionary, last: bool, steps: Array =
|
|||
if inline:
|
||||
sb.bg_color = sb.bg_color.darkened(0.04)
|
||||
p.add_theme_stylebox_override("panel", sb)
|
||||
if step.get("dropped", false):
|
||||
# A repeated roll that wasn't kept (or went into a total).
|
||||
p.modulate.a = 0.5
|
||||
p.size_flags_vertical = Control.SIZE_SHRINK_CENTER
|
||||
p.mouse_filter = Control.MOUSE_FILTER_PASS
|
||||
var v := VBoxContainer.new()
|
||||
|
|
|
|||
|
|
@ -66,6 +66,17 @@ static func caption_for(step: Dictionary, board: TowerBoard = null, plain: bool
|
|||
caption += " · rolled %s on %s" % [num, dl]
|
||||
if step.get("reshuffled", false):
|
||||
caption += " · deck reshuffled"
|
||||
match str(step.get("combined", step.get("kept", ""))):
|
||||
"sum":
|
||||
caption += " · total"
|
||||
"max":
|
||||
caption += " · kept, the highest"
|
||||
"min":
|
||||
caption += " · kept, the lowest"
|
||||
"choose":
|
||||
caption += " · kept, your choice"
|
||||
if step.get("dropped", false):
|
||||
caption += " · set aside"
|
||||
if str(step.get("save_as", "")) != "":
|
||||
if plain:
|
||||
caption += " · saved as %s" % Describe.label(str(step["save_as"]), board)
|
||||
|
|
|
|||
Loading…
Reference in a new issue