From f575b58551cfccbb34728f01f7f2fa20fe6e0e2d Mon Sep 17 00:00:00 2001 From: RobinFiredrake Date: Tue, 1 Dec 2026 14:15:25 -0600 Subject: [PATCH] Decks roll like other cards; re-rolls keep their cards; a roll stopped at a question goes to Earlier Co-Authored-By: Claude Sonnet --- core/deck_state.gd | 50 ++--------------------- core/roll_cards.gd | 60 +++++++++++++++++++-------- docs/LOGIC.md | 2 +- tests/test_choice_dialog.gd | 19 +++++++++ tests/test_roll_features.gd | 81 +++++++++++++++++++++++++++++++++++++ ui/main_rolling.gd | 20 +++++++-- 6 files changed, 163 insertions(+), 69 deletions(-) diff --git a/core/deck_state.gd b/core/deck_state.gd index 7ae8dff..62cc777 100644 --- a/core/deck_state.gd +++ b/core/deck_state.gd @@ -57,53 +57,9 @@ func cards_left(table: RollTable) -> Vector2i: return Vector2i(left, total) -## Draws one card. Returns {"index": int, "value": int} or {} if nothing is left. -func draw(table: RollTable, rng: RandomNumberGenerator) -> Dictionary: - _prune(table) - var weights: Array[float] = [] - var sum := 0.0 - for e in table.entries: - var w := float(_remaining(table, e)) - if table.is_ranged(): - w *= 1.0 if table.clamps() else table.chance(e) - weights.append(w) - sum += w - if sum <= 0.0: - return {} - var pick := rng.randf() * sum - var index := -1 - for i in weights.size(): - if weights[i] <= 0.0: - continue - index = i - if pick < weights[i]: - break - pick -= weights[i] - var chosen := table.entries[index] - drawn[chosen.id] = int(drawn.get(chosen.id, 0)) + 1 - var value := index + 1 - if table.is_ranged(): - value = _value_in(table, chosen, rng) - return {"index": index, "value": value} - - -## A die value inside the entry's range, weighted by the dice distribution. -func _value_in(table: RollTable, e: TableEntry, rng: RandomNumberGenerator) -> int: - if table.clamps(): - return rng.randi_range(e.range_lo, e.range_hi) - var dist := table.dice_obj().distribution() - var vals: Array[int] = [] - var mass := 0.0 - for v in range(e.range_lo, e.range_hi + 1): - if dist.has(v): - vals.append(v) - mass += float(dist[v]) - var pick := rng.randf() * mass - for v in vals: - pick -= float(dist[v]) - if pick < 0.0: - return v - return vals[vals.size() - 1] +## Draws one copy of this result: it leaves the deck until a reshuffle. +func take(e: TableEntry) -> void: + drawn[e.id] = int(drawn.get(e.id, 0)) + 1 ## Forgets draws for entries that no longer exist. diff --git a/core/roll_cards.gd b/core/roll_cards.gd index fe45289..7def4f5 100644 --- a/core/roll_cards.gd +++ b/core/roll_cards.gd @@ -26,16 +26,27 @@ static func pick_for(t: RollTable, ctx: RollContext, f: Dictionary) -> Dictionar skip.append(e.id) if skip.is_empty(): return pick_node(t, ctx, dice) + var deck: DeckState = null + if t.card_mode: + deck = (ctx.get_meta("decks", {}) as Dictionary).get(t.id) + # Only what is left in the deck can come up; an empty deck reshuffles first. + var deck_full := deck == null or deck.cards_left(t).x <= 0 var left := false for e in t.entries: - if not skip.has(e.id) and t.can_come_up(e): + if not skip.has(e.id) and t.can_come_up(e) and (deck_full or deck.remaining(t, e) > 0): left = true if not left: return Roller._stop(t, ALL_REROLLED if skip.size() == thread_skip.size() else NONE_ALLOWED) var skipped: Array = [] + var reshuffled := false for n in MAX_REROLLS: - var node := pick_node(t, ctx, dice) + var node := pick_node(t, ctx, dice, false) + reshuffled = reshuffled or node.has("reshuffled") if node.has("stop") or not skip.has((node["entry"] as TableEntry).id): + if reshuffled and not node.has("stop"): + node["reshuffled"] = true + if t.card_mode and not node.has("stop"): + (ctx.get_meta("decks")[t.id] as DeckState).take(node["entry"]) if not skipped.is_empty(): Roller._why(node, [{"type": "reroll", "skipped": skipped}]) return node @@ -44,21 +55,21 @@ static func pick_for(t: RollTable, ctx: RollContext, f: Dictionary) -> Dictionar 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 … +## Rolls an entry. A card in Deck mode rolls exactly like one without it (its +## dice, modifier, limits and `dice`); a result that is already drawn is +## rolled again without drawing. The kept card is drawn when `draw` is true; +## pick_for passes false, since it may still roll the result again. 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 +static func pick_node(t: RollTable, ctx: RollContext, dice: String = "", draw: bool = true) -> Dictionary: + var deck: DeckState = null 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] + deck = 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: @@ -67,11 +78,28 @@ static func pick_node(t: RollTable, ctx: RollContext, dice: String = "") -> Dict 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 node := _roll_entry(t, ctx, dice) + if deck != null: + var tries := 1 + while not node.has("stop") and deck.remaining(t, node["entry"]) <= 0: + if tries >= MAX_REROLLS: + return Roller._stop(t, "No card left in the deck can come up with these dice") + node = _roll_entry(t, ctx, dice) + tries += 1 + if reshuffled: + node["reshuffled"] = true + if draw and not node.has("stop"): + deck.take(node["entry"]) + return node + + +## One roll of the card's own way (card mode ignored): ranged dice, or the weights. +static func _roll_entry(t: RollTable, ctx: RollContext, dice: String) -> Dictionary: + var rng := ctx.rng + var index: int + var value: int + var fact: Dictionary + if t.is_ranged(): var was: Variant = ctx.faces ctx.faces = [] var rv := RollRange.roll_value(t, ctx, dice) @@ -124,8 +152,6 @@ static func pick_node(t: RollTable, ctx: RollContext, dice: String = "") -> Dict 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. diff --git a/docs/LOGIC.md b/docs/LOGIC.md index 809589f..4478a65 100644 --- a/docs/LOGIC.md +++ b/docs/LOGIC.md @@ -247,7 +247,7 @@ reach (−3 to 24 on a d20). A ranged `roll` table models this with a **modifier - `nat` is the dice alone, `total` isn't set (as before), and the Why line names the modifier: "Rolled 20, +7 for Luck = 27, past the top of the table, so it counts as 24". - A modifier that fails stops the card ("Can't roll 1d20 + @luck +: the modifier …"). -- Card mode (a deck) ignores the modifier. +- Card mode (a deck) rolls the same way: the modifier, limits and a thread's own dice all apply. A result that is already drawn is rolled again; only the kept result leaves the deck (a result rolled again for Only if, a thread or No repeats goes back). - The modifier and the old "whole expression as the dice" form (`2d6 + dm(@end)`) both work. The modifier is the clearer one: the card knows its dice, so it can show chances, the natural range and plain wording. diff --git a/tests/test_choice_dialog.gd b/tests/test_choice_dialog.gd index 9a23447..d124100 100644 --- a/tests/test_choice_dialog.gd +++ b/tests/test_choice_dialog.gd @@ -19,6 +19,7 @@ func run() -> void: await _test_keyboard_focus() await _test_minimize() await _test_waiting_question() + await _test_replaced_question() await _test_cancel_from_pill() await _test_state_kept() @@ -227,6 +228,24 @@ func _test_waiting_question() -> void: await process_frame +## Starting a roll while another waits on a question moves the old roll to Earlier. +## Spec lines (rolling): "WHEN you start a roll while one animates or waits on a question → the old roll stops and moves to [[Earlier]]". +func _test_replaced_question() -> void: + var d := await _ask() + if d == null: + _check(false, "the question opens for the replaced-question test") + return + var before: int = main.history.size() + main.start_roll("t_loot") + await process_frame + await process_frame + _eq(main.history.size(), before + 1, "a roll stopped at a question goes to Earlier") + _eq(str(main.history[0].get("root", "")), "t_ask", "the stopped roll is the one that waited") + _check(not main.history[0].has("pending"), "the Earlier record is not marked pending") + main.rolling.cancel_choice() + await process_frame + + func _test_cancel_from_pill() -> void: var d := await _ask() if d == null: diff --git a/tests/test_roll_features.gd b/tests/test_roll_features.gd index ccade2b..7cf4378 100644 --- a/tests/test_roll_features.gd +++ b/tests/test_roll_features.gd @@ -13,6 +13,8 @@ func run() -> void: await _test_costs() await _test_card_costs() _test_limits() + _test_deck_dice_rules() + _test_deck_rerolls() finish() @@ -237,3 +239,82 @@ func _test_limits() -> void: _check(why.contains("raised to 7"), "Why says it was raised: " + why) var back := RollTable.from_dict(atmo.to_dict()) _check(back.roll_floor == "@atmo_min", "the floor is saved") + + +## A card in Deck mode on a board; `ranged` gives it six single-number results +## on a d6, else six plain results. Returns [board, table]. +func _deck(ranged: bool) -> Array: + var b := TowerBoard.new() + var t := RollTable.new("deck", "Deck") + t.card_mode = true + t.dice = "d6" + for i in 6: + var e := TableEntry.new("c%d" % (i + 1), "Card %d" % (i + 1)) + if ranged: + e.has_range = true + e.range_lo = i + 1 + e.range_hi = i + 1 + t.entries.append(e) + b.tables.append(t) + return [b, t] + + +func _draw(b: TowerBoard, t: RollTable, rng: RandomNumberGenerator, decks: Dictionary, f: Dictionary = {}) -> Dictionary: + return RollCards.pick_for(t, Roller.new_context(b, rng, {}, decks), f) + + +## A deck rolls like the same card without Deck mode: the table's modifier, +## "Never below" and a thread's own dice all apply, and a result that is +## already drawn is rolled again. +## Spec lines (deck-mode): "ALWAYS a deck rolls exactly like the same card without Deck mode, except that drawn results can't come up". +func _test_deck_dice_rules() -> void: + var rng := RandomNumberGenerator.new() + for seed_value in 20: + rng.seed = seed_value + var plain := _deck(false) + plain[1].dice_mod = "2" + var first := _draw(plain[0], plain[1], rng, {}) + _check(int(first["index"]) >= 2, "a plain deck's modifier moves the pick (seed %d)" % seed_value) + var ranged := _deck(true) + var board: TowerBoard = ranged[0] + var table: RollTable = ranged[1] + table.roll_floor = "5" + var decks := {} + rng.seed = 3 + var got := [] + for k in 2: + got.append((_draw(board, table, rng, decks)["entry"] as TableEntry).id) + got.sort() + _eq(got, ["c5", "c6"], "a deck's \"Never below\" keeps low results out") + _check(_draw(board, table, rng, decks).has("stop"), "once the results the dice can reach are drawn, the deck stops") + var thread := _deck(true) + var thread_decks := {} + var one := _draw(thread[0], thread[1], rng, thread_decks, {"dice": "1d1"}) + _eq((one["entry"] as TableEntry).id, "c1", "a thread's own dice pick the deck's result") + _check(_draw(thread[0], thread[1], rng, thread_decks, {"dice": "1d1"}).has("stop"), "an already drawn result is rolled again, not drawn twice") + var modded := _deck(true) + modded[1].dice_mod = "1" + var up := _draw(modded[0], modded[1], rng, {}) + _check(not up.has("stop") and int(up["value"]) >= 2, "a ranged deck adds its modifier to the roll") + + +## Only the result that is kept leaves the deck; results rolled again go back, +## and the "can anything come up" check counts only what is left. +## Spec lines (deck-mode): "IF a drawn result is rolled again → it goes back; only the kept result leaves the deck". +func _test_deck_rerolls() -> void: + var rng := RandomNumberGenerator.new() + for seed_value in 20: + rng.seed = seed_value + var deck := _deck(false) + var decks := {} + var node := _draw(deck[0], deck[1], rng, decks, {"reroll": ["c1", "c2", "c3"]}) + var state: DeckState = decks["deck"] + _eq(state.cards_left(deck[1]), Vector2i(5, 6), "one card leaves the deck, not the re-rolled ones (seed %d)" % seed_value) + _check(int(node["index"]) >= 3 and state.remaining(deck[1], node["entry"]) == 0, "only the kept result is drawn (seed %d)" % seed_value) + var left := _deck(false) + var left_decks := {} + for id in ["c2", "c3", "c4", "c5", "c6"]: + (left_decks.get_or_add("deck", DeckState.new()) as DeckState).take(left[1].find_entry(id)) + var stop := _draw(left[0], left[1], rng, left_decks, {"reroll": ["c1"]}) + _eq(stop.get("stop", ""), RollCards.ALL_REROLLED, "a thread that skips the last card left in the deck stops the roll") + _eq((left_decks["deck"] as DeckState).cards_left(left[1]), Vector2i(1, 6), "and nothing is drawn or reshuffled") diff --git a/ui/main_rolling.gd b/ui/main_rolling.gd index 113e238..5c40f97 100644 --- a/ui/main_rolling.gd +++ b/ui/main_rolling.gd @@ -38,7 +38,7 @@ func _init(p_main: Main) -> void: ## whole result at once; so does the "Skip animations" setting. Choice cards ## still ask (docs/LOGIC.md §8): the roll animates up to the question, waits, ## then animates the rest, as a pause does. Starting a roll while a question -## is open cancels the old roll. +## is open cancels the old roll and moves it to Earlier. func start_roll(tid: String, fast: bool = false) -> void: var t := m.data.get_table(tid) if t == null or t.kind == RollTable.KIND_VARIABLE: @@ -317,17 +317,29 @@ func _pulse(key: String, my: int) -> void: m.board.pipes.pulse_key = "" -## Moves the current roll to the Earlier list (it's already in the saved history). +## Moves the current roll to the Earlier list (it's already in the saved history, +## except a roll stopped at a question). func _archive_current() -> void: - # A roll still waiting for an answer is cancelled, not kept. - if m.current.is_empty() or m.current.get("archived", false) or m.current.get("pending", false): + if m.current.is_empty() or m.current.get("archived", false): + return + # A roll still working has nothing to keep, and a paused one is set aside + # (RollPauses). One waiting on a question keeps the steps up to it. + var at_question: bool = m.current.get("pending", false) and pending_choice() != null + if m.current.get("pending", false) and not at_question: return m.current["archived"] = true var rec := m.current.duplicate() + for key in ["pending", "prompted", "asking"]: + rec.erase(key) rec["steps"] = m.current["all"] m.history.push_front(rec) if m.history.size() > Main.HISTORY_SIZE: m.history.resize(Main.HISTORY_SIZE) + if at_question and m.state != null: + # A finished roll is saved when it ends (_store_roll); this one never will be. + m.state.add_history({"collection": m.data.id, "root": rec["root"], "root_name": rec["root_name"], + "time": rec["time"], "steps": rec["steps"], "chain_vars": {}}) + m.state.save() ## Opens the session (MainRollingSeed.seed_session).