Compare commits

...

14 commits

Author SHA1 Message Date
f71a118d00 Docs: experimental lives in the main folder, not a worktree
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:51:20 -06:00
cc36be692e Merge reroll-and-deck-rows: partly drawn tint shows on plain rows
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:42:35 -06:00
13b8834564 Partly drawn tint: a colour layer behind the row
The row's own background is see-through on a plain row, so tinting it
showed nothing. A ColorRect behind the contents now carries the tint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:42:08 -06:00
e060fda21f Merge reroll-and-deck-rows: reroll undoes old values; new partly drawn tint
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:13:14 -06:00
2d3f5e9e3d Reroll this undoes the old result's values; partly drawn tint from a turned accent
- RollJournal: each roll logs the values it saves or erases; a reroll undoes
  the old branch's writes before rolling again (a number a later step changed
  keeps that later change).
- Style.turned_accent: the accent with its hue turned (OK HSL). Partly drawn
  deck rows use it turned 200 degrees, so they don't look like a lit row.
- Tests in test_roller and test_fast_roll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:13:14 -06:00
9a2afedaa0 Merge reroll-and-deck-rows: deck rows show copies left; Reroll this
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:34:08 -06:00
7d7b181b71 Deck rows show copies left; Reroll this on tray steps
- A deck row with no copies left is greyed out; one partly drawn gets an
  accent tint (Play and Build) and, in Play, shows <left> / <weight>.
- Each step of the current result has a Reroll this button: that card and
  the cards after it roll again in place. Earlier keeps no copy; the old
  branch's deck draws go back.
- Tests in test_small_ui and test_fast_roll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:33:49 -06:00
577922d15d CLAUDE.md: full test run only at the dev gate
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:21:26 -06:00
cffaa8f3e3 Tests: old deck and Earlier tests follow the new behaviour
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:17:40 -06:00
9b68da43d8 Deck: plain decks weigh results by copies left; test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:16:23 -06:00
f575b58551 Decks roll like other cards; re-rolls keep their cards; a roll stopped at a question goes to Earlier
Co-Authored-By: Claude Sonnet <noreply@anthropic.com>
2026-12-01 14:15:25 -06:00
4d317bceb2 Docs: Coderstanding viewer is the hosted page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:42:49 -06:00
31bce49f4d Coderstanding app renamed to tabletarot
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:38:07 -06:00
0365eb657b Release sweep script (suites, smoke, soak, hidden-screen windows); agents write spec tests; experimental push rule; shared Coderstanding data
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:19:52 -06:00
30 changed files with 788 additions and 105 deletions

View file

@ -7,7 +7,8 @@ How to work on it: `docs/DESIGN.md` §5. Module map: `docs/ARCHITECTURE.md`.
- Only the user changes `BUDGET_SECS`. If the tests can't reasonably fit, ask them, with timings.
- Don't get around it: no looping over suites, no several filtered runs to cover a full run,
no background or repeated runs.
- While working, run the suites for the area you changed, by filter. Do one full run at the end.
- While working, run the suites for the area you changed, by filter. The full run happens once,
at the dev gate (major-project rule, Robin 2026-12-01); never when work goes into `experimental`.
- `NOT RUN` means not tested. Say which suites were not run; never report them as passing.
- A new test must fit. Prefer adding to an existing suite; a new app suite costs about half a second to start.
No real waiting: the runner uses simulated time (`--fixed-fps 60`).
@ -21,8 +22,9 @@ TableTarot is a **major** project (Robin, 2026-12-01). Rules: `~/AI/Rules/coding
- **Into `experimental`: no gate.** The agent tests only its own code, then merges.
- **Dev gate** (`experimental` → `dev`): the user tries it and says OK, then one full
`tools/run_tests.sh` run plus the spec checks.
- **Release sweep** (`dev` → `main`): `tools/run_tests.sh --sweep` (every suite, 5× the budget)
plus the spec health report.
- Pushing `experimental`, `dev` or `main` needs the user's OK. Own work branches: push freely.
- **Specs are required** (Coderstanding app `tabletower`). Plan new behaviour as a spec Draft
branch first; only the user approves specs. Check: `coderstanding specs tabletower --lines`.
- **Release sweep** (`dev` → `main`): `tools/release_sweep.sh` (exhaustive, 5× the budget: every
suite, a smoke run, a soak run, real-window runs on a hidden screen) plus the spec health report.
- Merging into and pushing `experimental`: no need to ask. Pushing `dev` or `main` needs the
user's OK. Own work branches: push freely.
- **Specs are required** (Coderstanding app `tabletarot`). Plan new behaviour as a spec Draft
branch first; only the user approves specs. Check: `coderstanding specs tabletarot --lines`.

View file

@ -57,53 +57,18 @@ 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}
## 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
## 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]
## Puts one drawn copy of this result back (its roll was replaced).
func put_back(entry_id: String) -> void:
var count := int(drawn.get(entry_id, 0)) - 1
if count > 0:
drawn[entry_id] = count
else:
drawn.erase(entry_id)
## Forgets draws for entries that no longer exist.

View file

@ -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,29 @@ 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, deck)
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, deck)
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: ranged dice, or the weights (a deck's plain
## table weighs each result by its copies left).
static func _roll_entry(t: RollTable, ctx: RollContext, dice: String, deck: DeckState = null) -> 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)
@ -104,7 +133,7 @@ static func pick_node(t: RollTable, ctx: RollContext, dice: String = "") -> Dict
if index < 0:
return Roller._stop(t, "No result for %s" % t.fmt(value), {"value": value})
else:
index = pick_weighted(t, rng)
index = pick_weighted(t, rng, deck)
if index < 0:
return Roller._stop(t, "No result can come up")
value = index + 1
@ -124,8 +153,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.
@ -137,18 +164,26 @@ static func pick_node(t: RollTable, ctx: RollContext, dice: String = "") -> Dict
## 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()
## In Deck mode (`deck` given) each result counts once per copy still in the deck.
static func pick_weighted(t: RollTable, rng: RandomNumberGenerator, deck: DeckState = null) -> int:
var total := 0
for entry in t.entries:
total += _weight_now(t, entry, deck)
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)
pick -= _weight_now(t, t.entries[i], deck)
if pick < 0:
return i
return -1
## A result's weight for this pick: its copies left in the deck, or its weight.
static func _weight_now(t: RollTable, entry: TableEntry, deck: DeckState) -> int:
return deck.remaining(t, entry) if deck != null else maxi(0, entry.weight)
# ---------- Routers ----------
## The index of the first router case whose condition is true (an empty

View file

@ -46,6 +46,9 @@ var persistent_vars: Dictionary = {}
## True once save() has written a persistent variable in this roll, so the caller
## knows local state needs saving.
var persistent_changed: bool = false
## Every value this roll saved or erased, in order (RollJournal), so a reroll
## can undo part of it.
var journal: Array = []
## Depth of the text currently being expanded. References in that text are
## rolled at this depth. The roller sets it (depth + 1 for an entry's text).
var depth: int = 0
@ -111,9 +114,11 @@ func save(name: String, value: Variant, source_id: String = "") -> void:
var steps := scale_steps(n)
if not steps.is_empty():
value = Scales.store(steps, value)
RollJournal.record(journal, "@" + n, value, persistent_vars, chain_vars)
persistent_vars[n] = {"value": value, "source": source_id}
persistent_changed = true
elif n != "":
RollJournal.record(journal, n, value, persistent_vars, chain_vars)
chain_vars[n] = value
@ -157,9 +162,13 @@ func get_value(name: String) -> Variant:
func erase(name: String) -> void:
var n: String = name.strip_edges()
if n.begins_with("@"):
if persistent_vars.has(n.substr(1)):
RollJournal.record(journal, n, null, persistent_vars, chain_vars)
if persistent_vars.erase(n.substr(1)):
persistent_changed = true
else:
if chain_vars.has(n):
RollJournal.record(journal, n, null, persistent_vars, chain_vars)
chain_vars.erase(n)

95
core/roll_journal.gd Normal file
View file

@ -0,0 +1,95 @@
class_name RollJournal
extends RefCounted
## The values one roll changed, in the order it changed them, so part of the
## roll can be undone ("Reroll this": the old result never happened).
##
## Each write is {"key": "@name" or a chain name, "had": bool, "before":
## value, "before_source": table id, "after": value}. Every result node keeps
## "journal_at", the number of writes made before it started; a node's branch
## runs in one piece, so its writes sit between its own journal_at and the
## next branch's.
## Notes one write, before it happens. `persistent` and `chain` are the
## RollContext's dictionaries; `key` starts with "@" for a persistent value.
static func record(journal: Array, key: String, after: Variant, persistent: Dictionary, chain: Dictionary) -> void:
var write := {"key": key, "had": false, "before": null, "after": after}
if key.begins_with("@"):
var old: Variant = persistent.get(key.substr(1))
if old is Dictionary:
write["had"] = true
write["before"] = (old as Dictionary).get("value")
write["before_source"] = str((old as Dictionary).get("source", ""))
elif chain.has(key):
write["had"] = true
write["before"] = chain[key]
journal.append(write)
## Undoes writes [from, to). A value no later write touched goes back to what
## it was before the first of them. A number a later write changed again keeps
## that later change: only the undone writes' net change comes off it. Anything
## else a later write changed is left alone. Returns true if a persistent
## value changed.
static func undo(journal: Array, from: int, to: int, persistent: Dictionary, chain: Dictionary) -> bool:
var first := {}
var last := {}
for i in range(from, to):
var write: Dictionary = journal[i]
var key := str(write["key"])
if not first.has(key):
first[key] = write
last[key] = write
var later := {}
for i in range(to, journal.size()):
later[str((journal[i] as Dictionary)["key"])] = true
var persistent_changed := false
for key: String in first:
var start: Dictionary = first[key]
if not later.has(key):
_put(key, start["had"], start["before"], str(start.get("before_source", "")), persistent, chain)
else:
var before: Variant = start["before"] if start["had"] else 0
var after: Variant = (last[key] as Dictionary)["after"]
var now: Variant = _value_of(key, persistent, chain)
if not (_is_number(before) and _is_number(after) and _is_number(now)):
continue
var source := str(start.get("before_source", ""))
_put(key, true, Expr.normalize(float(now) - (float(after) - float(before))), source, persistent, chain)
persistent_changed = persistent_changed or key.begins_with("@")
return persistent_changed
## Replaces writes [from, to) with `fresh` (a reroll's own writes) and moves
## the journal_at of every step from `after_index` on to match.
static func splice(journal: Array, from: int, to: int, fresh: Array, steps: Array, after_index: int) -> Array:
var out: Array = journal.slice(0, from) + fresh + journal.slice(to)
var shift := fresh.size() - (to - from)
for i in range(after_index, steps.size()):
var step: Dictionary = steps[i]
if step.has("journal_at"):
step["journal_at"] = int(step["journal_at"]) + shift
return out
static func _put(key: String, had: bool, value: Variant, source: String, persistent: Dictionary, chain: Dictionary) -> void:
if key.begins_with("@"):
if had:
persistent[key.substr(1)] = {"value": value, "source": source}
else:
persistent.erase(key.substr(1))
elif had:
chain[key] = value
else:
chain.erase(key)
static func _value_of(key: String, persistent: Dictionary, chain: Dictionary) -> Variant:
if key.begins_with("@"):
var entry: Variant = persistent.get(key.substr(1))
return (entry as Dictionary).get("value") if entry is Dictionary else null
return chain.get(key)
static func _is_number(value: Variant) -> bool:
return value is int or value is float

1
core/roll_journal.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://clu2xrmhtfgim

View file

@ -16,6 +16,9 @@ static func stop(table: RollTable, why: String, extra: Dictionary = {}) -> Dicti
## Hangs `node` under the frame's parent, with the frame's save name and card
## inputs. A top-level node also becomes ctx.root.
static func attach(frame: Dictionary, node: Dictionary, ctx: RollContext) -> void:
# Where this node's writes start (RollJournal): from the frame's start, so
# a paid cost counts as the node's own.
node["journal_at"] = int(frame.get("journal_at", ctx.journal.size()))
if str(frame.get("save", "")) != "":
node["save_as"] = frame["save"]
if frame.has("inputs"):

View file

@ -38,7 +38,7 @@ static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
step["spread"] = n["spread"]
if n.has("effects"):
step["effects"] = (n["effects"] as Array).duplicate(true)
for k in ["answer", "passes", "pass", "after", "picked", "only_option", "random", "limit", "cancelled", "deck_empty", "dropped", "kept", "combined", "stopped_before", "case", "option", "check", "inputs", "columns", "card_thread"]:
for k in ["answer", "passes", "pass", "after", "picked", "only_option", "random", "limit", "cancelled", "deck_empty", "dropped", "kept", "combined", "stopped_before", "case", "option", "check", "inputs", "columns", "card_thread", "journal_at"]:
if n.has(k):
step[k] = n[k]
if n.has("why"):

View file

@ -232,6 +232,7 @@ static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack:
return
if not _take_action(f, t, ctx):
return
f["journal_at"] = ctx.journal.size()
RollPipes.bind_inputs(t, f, ctx, stack)
if not await RollCosts.card_gate(board, t, f, ctx):
return

View file

@ -93,6 +93,20 @@ func add_history(record: Dictionary) -> void:
_dirty = true
## Swaps the record with the same collection and time for this one (a
## rerolled step changes the current roll in place). Adds it if none matches.
func replace_history(record: Dictionary) -> void:
var list: Array = _section_list("history")
for i in list.size():
var old: Variant = list[i]
if old is Dictionary and str(old.get("collection", "")) == str(record.get("collection", "")) \
and float(old.get("time", -1.0)) == float(record.get("time", -2.0)):
list[i] = record.duplicate(true)
_dirty = true
return
add_history(record)
## All records, or only those whose "collection" is cid when cid isn't empty.
func get_history(cid: String = "") -> Array[Dictionary]:
var out: Array[Dictionary] = []

View file

@ -227,7 +227,9 @@ Each original file keeps one-line delegators, so callers are unchanged.
- **Ledger:** `core/ledger_members.gd` (entries on the card: clean, adopt older spreads, sync with
saved values), `ui/ledger_edits.gd` (add/rename/start/remove with undo), `ui/ledger_card_rows.gd`
(Build-mode fields on the card).
- **Rolling:** `ui/main_rolling_show.gd` (show a roll at once), `RollCosts.card_gate` (card costs),
- **Rolling:** `ui/main_rolling_show.gd` (show a roll at once), `ui/main_rolling_reroll.gd`
("Reroll this" on a tray step: that card and its branch roll again in place, with
`core/roll_journal.gd` undoing the values the old branch changed; 2026-12-01), `RollCosts.card_gate` (card costs),
`RollPauses` pop-up, `SpreadLinks` (`core/spread_links.gd`, [[Spread::Card]]) with
`ui/spread_loader.gd` and `ui/spread_link_dialog.gd`.
- **Interface:** `ui/delete_key.gd`, `ui/sound_panel.gd`, `ui/format_menu.gd` (right-click Format),

View file

@ -78,6 +78,8 @@ undo 200 steps, formula depth 8) and the review list at the end of `docs/SHEETS.
- Drag handles reorder a card's results in Build (ranged cards keep ranges in place). Hand-tested.
- Thread nodes under a card stacked above theirs are hidden. Hand-tested.
- Deck mode: a drawn result fades only after the roll animation reveals it (fast rolls: at once).
- Deck mode rows (2026-12-01): none left = greyed out; some drawn = accent tint, and in Play
mode "<left> / <weight>" in place of the number. Tray steps have "↻ Reroll this".
- Group marks (the user's pick, "option C"): a member card's top-right corner, and the group's
border, take the group's colour (Colour ▸ on the group menu); uncoloured groups use the theme
token GROUP (default gold, same as the highlight; watch for confusion).
@ -281,7 +283,8 @@ that works on any theme (solid background, stronger text, thicker borders, no ef
Six Godot workers (`tests/run_suites.gd`) share the suites, longest first; what doesn't fit is
listed as NOT RUN (exit code 2). A full run takes ~12 s on an idle machine (2026-11-25). One
line per suite; a failing suite prints 8 lines; a compile error shared by many suites prints
once. A suite is a Node with `run()`, ending in `finish()`. It extends `TestBase`
once. Release sweep: `tools/release_sweep.sh` (75 s; ~22 s on 2026-12-01).
A suite is a Node with `run()`, ending in `finish()`. It extends `TestBase`
(`tests/testbase.gd`, no UI: `require_sample()`, `_check`, `_eq`, `_frames`, `_wipe`) or
`AppTestBase` (`tests/app_testbase.gd`: `main`, `start_main()`; pass false to start on an
empty spread). The suites' demo spread has tables of 12 rows at most. Suites share a process,
@ -304,19 +307,23 @@ that works on any theme (solid background, stronger text, thicker borders, no ef
scripts, avoid apostrophes inside single-quoted replacement strings.
- **Git:** origin `git@forgejo.smhub.duckdns.org:RobinFiredrake/TableTower.git`. Major project
(2026-12-01): feature branch → `experimental` → `dev` → `main`, with a dev gate and a release
sweep (`CLAUDE.md`). Worktree for `experimental`: `~/Repos/Worktrees/TableTower/experimental`.
sweep (`CLAUDE.md`). `experimental` is checked out in the main folder, where the user
tests (2026-12-01): merge feature branches there, and never check it out in a second worktree
(the other copy's files fall behind).
Co-Authored-By line on commits.
- **Agents:** only for large, separate jobs. Worktree briefs start with `git reset --hard <branch>`,
own specific files, keep public APIs as delegators, don't touch tests. The user's computer has
own specific files, keep public APIs as delegators. They write tests from the spec lines they
touch, link them to the lines, and run only their own test file (major-project rule, 2026-12-01). The user's computer has
been crashing: an interrupted agent's work stays in `.claude/worktrees/`; resume it with
SendMessage ("don't reset"), then cherry-pick its commit and `git worktree remove -f -f`.
- **Token savings:** read only this page at the start; read the other docs on demand; keep tool
output short (the test runner already does); avoid viewing full-size screenshots (crop/resize).
- **Coderstanding** (structure scanner, tours) is installed: `coderstanding` on PATH (venv
`~/.local/share/coderstanding/venv`), app `tabletower`, data and tours in
`~/.local/share/coderstanding/tabletower`, viewer http://127.0.0.1:8517/. Tours teach the
`~/.local/share/coderstanding/venv`), app `tabletarot`, data and tours in
`~/.local/share/coderstanding/tabletarot`, shared with Digit: the data home is the private repo
`digit/coderstanding-data`; run its `./sync.sh` after changing specs, tours or scans. Viewer: https://code.smhub.duckdns.org (hosted page; it talks to the local helper on 127.0.0.1:8517). Tours teach the
user (new to coding): plain words, explain basics. Specs are required (major project):
`coderstanding specs tabletower --lines`. Update: pull
`coderstanding specs tabletarot --lines`. Update: pull
https://forgejo.smhub.duckdns.org/digit/coderstanding and `pip install` it into that venv.
After a Fedora Python upgrade the venv breaks (`No module named 'coderstanding'`): rebuild it
with `python3 -m venv` and reinstall (done for 3.15 on 2026-12-01, v0.4.0).

View file

@ -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.

View file

@ -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:

View file

@ -42,9 +42,56 @@ func run() -> void:
await _test_deck_waits()
await _test_batch_history()
_test_reroll_mark()
await _test_reroll_this()
finish()
## Reroll this: a step rolls again with its branch, in place. The steps
## before it stay, Earlier keeps no copy, and a deck's old draw goes back.
func _test_reroll_this() -> void:
main.start_roll("wilderness", true)
var before: Array = main.current["all"]
var history := main.history.size()
var last := before.size() - 1
_check(main.tray.reroll_buttons.has(last), "a step of the current result has Reroll this")
await main.rolling.reroll.reroll(last)
var after: Array = main.current["all"]
for i in last:
_check(is_same(after[i], before[i]), "the steps before it are kept (step %d)" % i)
_eq(str(after[last]["table_id"]), str(before[last]["table_id"]), "the same card rolls again")
_eq(main.history.size(), history, "Earlier keeps no copy of the old result")
_check(main.current.get("done", false), "the rerolled result is finished")
before = after
await main.rolling.reroll.reroll(0)
_check(not is_same(main.current["all"][0], before[0]), "the first step and the cards after it roll again")
_eq(str(main.current["root"]), "wilderness", "it is still the same roll")
# The old result never happened: its effect is undone before the new one.
var t := main.data.get_table("wilderness")
var own_effects: Array[String] = []
for e in t.entries:
own_effects.append(e.effects)
e.effects = "@reroll_luck -= 1"
main.persistent_vars["reroll_luck"] = {"value": 5, "source": ""}
main.start_roll(t.id, true)
_eq(int(main.persistent_vars["reroll_luck"]["value"]), 4, "the roll's effect happens once")
await main.rolling.reroll.reroll(0)
_eq(int(main.persistent_vars["reroll_luck"]["value"]), 4, "a reroll undoes the old effect first")
for i in t.entries.size():
t.entries[i].effects = own_effects[i]
main.persistent_vars.erase("reroll_luck")
t.card_mode = true
main.reshuffle_table(t.id)
main.start_roll(t.id, true)
var total := main.cards_left(t.id).y
_eq(main.cards_left(t.id).x, total - 1, "the roll draws one card")
await main.rolling.reroll.reroll(0)
_eq(main.cards_left(t.id).x, total - 1, "the old card goes back; only the new one is drawn")
t.card_mode = false
main.reshuffle_table(t.id)
## "Roll again" shows: the skipped result flickers with a floating note.
func _test_reroll_mark() -> void:
var card := main.card_for("names")

View file

@ -248,7 +248,7 @@ func _test_replace() -> void:
_check(second != null and second != first, "the new roll opens its own pop-up")
_check(not is_instance_valid(first) or first.is_queued_for_deletion(), "the old pop-up goes away")
_check(not main.current.has("halted"), "the old roll doesn't overwrite the new one")
_eq(main.history.size(), history, "the replaced (unanswered) roll isn't added to Earlier")
_eq(main.history.size(), history + 1, "the replaced (unanswered) roll moves to Earlier (Robin, 2026-12-01)")
if second == null:
return
second._text.text = "Cy"

View file

@ -217,8 +217,9 @@ func _test_cards() -> void:
# Edits.
t.deck_empty = "reshuffle"
var d3 := DeckState.new()
for i in 4:
d3.draw(t, r)
for entry in t.entries:
for copy in d3.copies_of(t, entry):
d3.take(entry)
_check(d3.cards_left(t) == Vector2i(0, 4), "fully drawn deck")
t.entries[0].weight = 3
_check(d3.cards_left(t) == Vector2i(2, 6), "raising a weight adds copies")
@ -226,8 +227,8 @@ func _test_cards() -> void:
_check(d3.cards_left(t) == Vector2i(3, 7), "new entries start undrawn")
t.entries.remove_at(1)
_check(d3.cards_left(t) == Vector2i(3, 5), "deleted entries drop out")
var first := d3.draw(t, r)
_check(first.has("index"), "can still draw after edits")
d3.take(t.entries[0])
_check(d3.cards_left(t) == Vector2i(2, 5), "can still draw after edits")
t.entries[0].weight = 1
_check(d3.cards_left(t).x == 1 and d3.cards_left(t).y == 3, "lowering a weight removes copies (%s)" % str(d3.cards_left(t)))

View file

@ -13,6 +13,9 @@ func run() -> void:
await _test_costs()
await _test_card_costs()
_test_limits()
_test_deck_dice_rules()
_test_deck_rerolls()
_test_deck_copies_left()
finish()
@ -237,3 +240,104 @@ 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")
## Spec deck-mode: "a plain deck holds one copy of a result per point of weight".
## A result with copies drawn comes up less often, not at its full weight.
func _test_deck_copies_left() -> void:
var table := RollTable.new("deck", "Deck")
table.card_mode = true
var three_copies := TableEntry.new("three", "Three copies")
three_copies.weight = 3
var one_copy := TableEntry.new("one", "One copy")
table.entries.append(three_copies)
table.entries.append(one_copy)
var deck := DeckState.new()
deck.take(three_copies)
deck.take(three_copies)
var rng := RandomNumberGenerator.new()
rng.seed = 7
var three_count := 0
for i in 2000:
three_count += int(RollCards.pick_weighted(table, rng, deck) == 0)
var share := three_count / 2000.0
_check(share > 0.4 and share < 0.6, "1 copy left each: an even chance, not 3 to 1 (got %.2f)" % share)

View file

@ -81,4 +81,27 @@ func run() -> void:
dangling = true
_check(not dangling and copy.get_table("loot") == null, "removing a table removes threads into it")
_test_journal_undo()
finish()
## RollJournal: undoing part of a roll puts values back. A number a later
## write changed again keeps that later change; a value first set by the undone
## part is erased.
func _test_journal_undo() -> void:
var persistent := {"luck": {"value": 5, "source": "a"}}
var ctx := RollContext.new(persistent)
ctx.save("@luck", 4) # 0: undone
ctx.save("@gold", 10) # 1: undone, new value
ctx.save("place", "cave") # 2: undone, chain value
ctx.save("@luck", 2) # 3: a later write (-2)
RollJournal.undo(ctx.journal, 0, 3, persistent, ctx.chain_vars)
_eq(int(persistent["luck"]["value"]), 3, "a later change stays; only the undone -1 comes off")
_check(not persistent.has("gold"), "a value the undone part made is gone")
_check(not ctx.chain_vars.has("place"), "a chain value the undone part made is gone")
var fresh := {"luck": {"value": 5, "source": "a"}}
var ctx2 := RollContext.new(fresh)
ctx2.save("@luck", 1)
ctx2.erase("@luck")
RollJournal.undo(ctx2.journal, 0, 2, fresh, ctx2.chain_vars)
_eq(int(fresh["luck"]["value"]), 5, "a value set then erased comes back as it was")

View file

@ -84,11 +84,53 @@ func _test_chip_and_export() -> void:
_check(subs.size() == 1 and (subs[0] as PopupMenu).item_count == IoMenu.EXPORTS.size() - 1, "diagram formats sit under Export as a diagram")
## Deck mode: a row with some copies drawn is tinted (Play and Build) and, in
## Play, shows "<left> / <weight>"; with none left it is greyed out.
func _test_partly_drawn(t: RollTable) -> void:
var first := t.entries[0]
var weight := first.weight
first.weight = 2
main.reshuffle_table(t.id)
var card := main.card_for(t.id)
card.rebuild()
await _frames()
var number: Label = card.rows_ui.parts[first.id]["num"]
var plain := number.text
(main.decks.get_or_add(t.id, DeckState.new()) as DeckState).take(first)
card.update_deck()
var row: Control = card.rows[first.id]
var layer := TableCardSkin.partly_drawn_layer(row)
_check(layer != null and layer.visible and layer.color == TableCardSkin.partly_drawn_tint() and layer.get_index() == 0, "a partly drawn row is tinted")
await _frames()
_check(layer.size.x > 0.0 and layer.size.y > 0.0, "the tint covers the row")
_eq(number.text, "1 / 2", "a partly drawn row shows its copies left")
main.set_mode(Main.Mode.BUILD)
await _frames()
card = main.card_for(t.id)
var build_layer := TableCardSkin.partly_drawn_layer(card.rows[first.id])
_check(build_layer != null and build_layer.visible, "it is tinted in Build mode too")
main.set_mode(Main.Mode.PLAY)
await _frames()
card = main.card_for(t.id)
(main.decks[t.id] as DeckState).take(first)
card.update_deck()
row = card.rows[first.id]
number = card.rows_ui.parts[first.id]["num"]
var gone_layer := TableCardSkin.partly_drawn_layer(row)
_check(row.modulate == TableCardSkin.DRAWN_LOOK and (gone_layer == null or not gone_layer.visible), "with no copies left the row is greyed out")
_eq(number.text, plain, "it shows its own number again")
first.weight = weight
main.reshuffle_table(t.id)
card.rebuild()
await _frames()
## Deck mode: drawn results fade, an empty deck that waits for Shuffle gives
## its Empty result, and Shuffle all puts everything back.
func _test_deck_mode() -> void:
var t := main.data.get_table("party_roles")
_check(t != null and t.card_mode, "the sample's Party Roles is a deck")
await _test_partly_drawn(t)
t.deck_empty = "stop"
t.deck_empty_text = "No roles left"
for i in t.entries.size():

78
tools/release_sweep.sh Executable file
View file

@ -0,0 +1,78 @@
#!/usr/bin/env bash
# The release sweep: run before `dev` goes into `main`. Exhaustive, unlike the dev gate.
#
# Runs, in one shared time limit of 5x the suite budget (BUDGET_SECS in run_tests.sh):
# 1. every test suite (run_tests.sh --sweep)
# 2. a headless smoke run of the app with the sample spread
# 3. a soak run: the example board rolled many times, every choice answered at random
# 4. real-window runs (desktop and phone view) on a hidden virtual screen, with screenshots
# A step fails on its own failure or on a SCRIPT ERROR. Steps that don't fit the time are NOT RUN.
# Step 4 is NOT RUN while SteamVR or a Steam game runs (GPU runs then can crash the PC).
#
# Usage: tools/release_sweep.sh
# Exit codes: 0 all passed, 1 a step failed, 2 over the time limit (nothing failed).
set -u
cd "$(dirname "$0")/.." || exit 1
GODOT="${GODOT:-$HOME/apps/Godot_v4.7.2-stable_linux.x86_64}"
SWEEP_MULTIPLIER=5
budget_secs=$(grep -oP '^readonly BUDGET_SECS=\K[0-9]+' tools/run_tests.sh)
limit_secs=$(( budget_secs * SWEEP_MULTIPLIER ))
SHOTS="${SWEEP_SHOTS:-/tmp/tabletarot-sweep}"
mkdir -p "$SHOTS"
start_ms=$(date +%s%3N)
left_secs() { echo $(( limit_secs - ($(date +%s%3N) - start_ms) / 1000 )); }
failed=()
not_run=()
LOG="$(mktemp)"
trap 'rm -f "$LOG"' EXIT
# run_step NAME COMMAND...: runs at low priority in the time that is left.
run_step() {
local name="$1"; shift
local left; left=$(left_secs)
if (( left < 2 )); then not_run+=("$name"); echo "NOT RUN $name (no time left)"; return; fi
nice -n 10 timeout -s KILL "$left" "$@" >"$LOG" 2>&1
local code=$?
if (( code == 137 )); then not_run+=("$name"); echo "NOT RUN $name (stopped at the time limit)"
elif (( code != 0 )) || grep -q "SCRIPT ERROR" "$LOG"; then
failed+=("$name"); echo "FAIL $name"; grep -E "FAIL|SCRIPT ERROR|ERROR" "$LOG" | head -8
else echo "ok $name"; fi
}
# 1. Suites: run_tests.sh prints its own report.
left=$(left_secs)
timeout -s KILL "$left" tools/run_tests.sh --sweep | grep -vE "^ok "
case ${PIPESTATUS[0]} in
0) ;;
2|137) not_run+=("suites") ;;
*) failed+=("suites") ;;
esac
# 2. Smoke run.
run_step "smoke" "$GODOT" --headless --audio-driver Dummy --path . --quit-after 120 -- --sample
# 3. Soak run: exit code 1 means a roll hit an error or the action limit.
run_step "soak" "$GODOT" --headless --audio-driver Dummy --path . -s res://tools/simulate_board.gd -- \
--board=examples/logic_demo.json --start=start --runs=500 --quiet
# 4. Real windows on a hidden screen (never on the user's desktop).
if pgrep -x vrserver >/dev/null || pgrep -f "SteamLaunch" >/dev/null; then
not_run+=("windows"); echo "NOT RUN windows (SteamVR or a game is running)"
else
socket="tabletarot-sweep-$$"
kwin_wayland --virtual --no-lockscreen --socket "$socket" --width 1600 --height 1000 >/dev/null 2>&1 &
kwin_pid=$!
for _ in $(seq 50); do [[ -S "$XDG_RUNTIME_DIR/$socket" ]] && break; sleep 0.1; done
window_run=(env WAYLAND_DISPLAY="$socket" "$GODOT" --display-driver wayland --audio-driver Dummy --path . --)
run_step "window desktop" "${window_run[@]}" --sample --screenshot="$SHOTS/desktop.png"
run_step "window phone" "${window_run[@]}" --sample --mobile --screenshot="$SHOTS/phone.png"
kill "$kwin_pid" 2>/dev/null
echo "Screenshots: $SHOTS"
fi
took="$(( ($(date +%s%3N) - start_ms) / 1000 ))s of ${limit_secs}s"
(( ${#not_run[@]} )) && echo "NOT RUN: ${not_run[*]}"
if (( ${#failed[@]} )); then echo "RELEASE SWEEP FAILED: ${failed[*]} ($took)"; exit 1; fi
if (( ${#not_run[@]} )); then echo "RELEASE SWEEP OVER TIME ($took)"; exit 2; fi
echo "RELEASE SWEEP PASSED ($took)"

View file

@ -22,6 +22,8 @@ var deck_reveal: DeckReveal
var _seed: MainRollingSeed
var _copy: MainRollingCopy
var _show: MainRollingShow
## "Reroll this" on a step in the result tray.
var reroll: MainRollingReroll
func _init(p_main: Main) -> void:
@ -31,6 +33,7 @@ func _init(p_main: Main) -> void:
_seed = MainRollingSeed.new(p_main)
_copy = MainRollingCopy.new(p_main)
_show = MainRollingShow.new(p_main)
reroll = MainRollingReroll.new(p_main)
## Rolls a table and plays the result down its pipes. A fast roll (Shift held
@ -38,7 +41,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:
@ -90,7 +93,7 @@ func start_roll(tid: String, fast: bool = false) -> void:
m.lit_texts.clear()
m.lit_columns.clear()
m.current = {"collection": m.data.id, "root": tid, "root_name": t.name, "time": m.current.get("time", Time.get_unix_time_from_system()),
"steps": [], "all": Roller.flatten(tree, []), "done": false, "chain_vars": ctx.chain_vars.duplicate()}
"steps": [], "all": Roller.flatten(tree, []), "done": false, "chain_vars": ctx.chain_vars.duplicate(), "journal": ctx.journal}
if ctx.halted != "":
m.current["halted"] = ctx.halted
m.local_state._store_roll(ctx)
@ -317,17 +320,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).

129
ui/main_rolling_reroll.gd Normal file
View file

@ -0,0 +1,129 @@
class_name MainRollingReroll
extends RefCounted
## "Reroll this" in the result tray: one step's card rolls again, and so do
## the cards after it along its threads. The new steps take the old ones'
## place in the current result; Earlier keeps no copy. The old result never
## happened: the values its branch changed are undone (RollJournal) and its
## deck draws go back, before the new roll. The reroll shows at once.
## Steps that can't be rerolled on their own: text rolls inside a result,
## runs dropped from or added into a total, a choice's answer, and the
## "Cancelled" / "Stopped after …" ends.
const FIXED_KEYS := ["inline", "dropped", "combined", "answer", "spread", "cancelled", "limit"]
## How the old step was reached; the new step keeps it, so its thread lights.
const LINK_KEYS := ["pass", "after", "card_thread"]
var m: Main
func _init(p_main: Main) -> void:
m = p_main
## True when step `index` of the finished current result can be rerolled.
func can_reroll(index: int) -> bool:
if m.current.is_empty() or not m.current.get("done", false):
return false
var steps: Array = m.current.get("all", [])
if index < 0 or index >= steps.size():
return false
var step: Dictionary = steps[index]
for key: String in FIXED_KEYS:
var value: Variant = step.get(key)
if value != null and not (value is bool and value == false):
return false
var table := m.data.get_table(str(step.get("table_id", "")))
return table != null and table.kind != RollTable.KIND_VARIABLE
## Index just past the last step under steps[index] (its whole branch).
static func branch_end(steps: Array, index: int) -> int:
var depth := int((steps[index] as Dictionary).get("depth", 0))
var end := index + 1
while end < steps.size() and int((steps[end] as Dictionary).get("depth", 0)) > depth:
end += 1
return end
## Rolls step `index` of the current result again, with its branch.
func reroll(index: int) -> void:
if not can_reroll(index):
return
var current := m.current
var steps: Array = current["all"]
var step: Dictionary = steps[index]
var end := branch_end(steps, index)
_put_back_draws(steps.slice(index, end))
if m.sound:
m.sound.play("roll")
var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, m.decks)
ctx.chain_vars = (current.get("chain_vars", {}) as Dictionary).duplicate(true)
var journal: Array = current.get("journal", [])
var span := _journal_span(steps, index, end, journal)
if span.x >= 0:
ctx.persistent_changed = RollJournal.undo(journal, span.x, span.y, m.persistent_vars, ctx.chain_vars)
ctx.prompt = _ask
m.sheet_links.before_roll(Formatter.strip_tags(str(current.get("root_name", ""))))
var depth := int(step.get("depth", 0))
var tree: Dictionary = await Roller.roll_async(m.data, str(step["table_id"]), ctx, depth)
if not is_same(current, m.current):
return # another roll started while this one asked a question
var fresh := Roller.flatten(tree, [], depth)
if not fresh.is_empty():
for key: String in LINK_KEYS:
if step.has(key):
(fresh[0] as Dictionary)[key] = step[key]
var all: Array = steps.slice(0, index) + fresh + steps.slice(end)
if span.x >= 0:
for st: Dictionary in fresh:
if st.has("journal_at"):
st["journal_at"] = int(st["journal_at"]) + span.x
current["journal"] = RollJournal.splice(journal, span.x, span.y, ctx.journal, all, index + fresh.size())
current["all"] = all
current["steps"] = all
current["chain_vars"] = ctx.chain_vars.duplicate()
current["fast"] = true
_show(all)
m.local_state.replace_current_roll(ctx)
## The old branch's writes in the journal, as Vector2i(from, to); x is -1 for
## a roll saved before journals were kept (its values can't be undone).
static func _journal_span(steps: Array, index: int, end: int, journal: Array) -> Vector2i:
var from := int((steps[index] as Dictionary).get("journal_at", -1))
var to := journal.size()
if end < steps.size():
to = int((steps[end] as Dictionary).get("journal_at", -1))
if from < 0 or to < from or to > journal.size():
return Vector2i(-1, -1)
return Vector2i(from, to)
## Deck mode: every card the old branch drew goes back into its deck.
func _put_back_draws(old_steps: Array) -> void:
for st: Dictionary in old_steps:
if st.get("stop", false) or not st.has("entry_id"):
continue
var deck: DeckState = m.decks.get(str(st.get("table_id", "")))
if deck:
deck.put_back(str(st["entry_id"]))
## Questions in the rerolled branch ask as usual; a paused thread goes on,
## since you asked for this branch.
func _ask(req: Dictionary) -> Variant:
if str(req.get("kind", "")) == "pause":
return true
return await m.prompt_hook.call(req)
func _show(all: Array) -> void:
m.lit_entries.clear()
m.lit_pipes.clear()
m.lit_texts.clear()
m.lit_columns.clear()
m.rolling._light_steps(all)
m._refresh_lit()
m.rolling._reveal_steps(all)
m.refresh_live()
m.tray.render()

View file

@ -0,0 +1 @@
uid://dgy1y1xvj0vpm

View file

@ -53,7 +53,7 @@ func load_local_state() -> void:
## After a roll: saves the decks, any changed persistent variables and the
## history record.
func _store_roll(ctx: RollContext) -> void:
func _store_roll(ctx: RollContext, replace: bool = false) -> void:
# Values the roll changed go back into the sheets on the spread first.
m.sheet_links.after_roll()
if m.state == null:
@ -61,11 +61,22 @@ func _store_roll(ctx: RollContext) -> void:
_store_decks()
if ctx.persistent_changed:
_store_variables()
m.state.add_history({"collection": m.data.id, "root": m.current["root"], "root_name": m.current["root_name"],
"time": m.current["time"], "steps": m.current["all"], "chain_vars": m.current.get("chain_vars", {})})
var record := {"collection": m.data.id, "root": m.current["root"], "root_name": m.current["root_name"],
"time": m.current["time"], "steps": m.current["all"], "chain_vars": m.current.get("chain_vars", {}),
"journal": m.current.get("journal", [])}
if replace:
m.state.replace_history(record)
else:
m.state.add_history(record)
m.state.save()
## After "Reroll this": saves like _store_roll, but the current roll's history
## record is changed in place, not added again.
func replace_current_roll(ctx: RollContext) -> void:
_store_roll(ctx, true)
func _store_decks() -> void:
if m.state == null:
return

View file

@ -58,6 +58,8 @@ var _scroll_to_end := false
var _why: WhyPopover
## The "Why this?" buttons of the chips shown, by step index (tests).
var why_buttons: Dictionary = {}
## The "Reroll this" buttons of the chips shown, by step index (tests).
var reroll_buttons: Dictionary = {}
var _why_flag_done := false
## A long chain shows only its last steps; the rest sit behind a toggle.
@ -197,6 +199,7 @@ func render() -> void:
_flow.remove_child(c)
c.queue_free()
why_buttons.clear()
reroll_buttons.clear()
if _why != null:
_why.close()
_empty.visible = current.is_empty()

View file

@ -127,6 +127,14 @@ static func caps() -> Font:
# ---------- Styleboxes ----------
## margins: [left, top, right, bottom]
## The accent with its hue turned `degrees` around the colour wheel, keeping
## how light and how strong it is (perceptual OK HSL). Colours made this way
## follow whatever accent the theme picks, yet never look like the accent.
static func turned_accent(degrees: float) -> Color:
var turned := fposmod(ACCENT.ok_hsl_h + degrees / 360.0, 1.0)
return Color.from_ok_hsl(turned, ACCENT.ok_hsl_s, ACCENT.ok_hsl_l, ACCENT.a)
static func box(bg: Color, radius: int = 0, margins: Array = [0, 0, 0, 0]) -> StyleBoxFlat:
var s := StyleBoxFlat.new()
s.bg_color = bg

View file

@ -162,6 +162,8 @@ func _num_width(build: bool, ranged: bool) -> float:
return 100.0 if RangeWeights.uses_weights(table) else 90.0
if ranged:
return 52.0 if wide else 40.0
if table.card_mode and not build:
return 50.0 # room for a partly drawn deck row's "<left> / <weight>"
return 24.0 if wide else 22.0

View file

@ -2,6 +2,9 @@ class_name TableCardSkin
extends RefCounted
## The card shell look: frame colour, drop/warning panels and scrollbars.
## A deck row with no copies left: greyed out.
const DRAWN_LOOK := Color(0.7, 0.7, 0.7, 0.45)
var card: TableCard
@ -81,8 +84,9 @@ func skin_scrollbar(bar: VScrollBar) -> void:
bar.add_theme_stylebox_override("grabber_pressed", grab_hi)
## Deck mode: results already drawn (none left in the deck) show faded until
## the deck is shuffled.
## Deck mode: a result with no copies left is greyed out until the deck is
## shuffled; one with some copies drawn is tinted in the accent colour and, in
## Play mode, shows "<left> / <weight>" in place of its number.
func dim_drawn() -> void:
if not card.table.card_mode:
return
@ -91,10 +95,61 @@ func dim_drawn() -> void:
var row: Control = card.rows.get(e.id)
if row == null or not is_instance_valid(row):
continue
var held := card.main.rolling.deck_reveal.held(card.table.id, e.id)
var gone := deck != null and deck.remaining(card.table, e) + held <= 0
row.modulate.a = 0.38 if gone else 1.0
var copies := DeckState.copies_of(card.table, e)
var left := copies
if deck != null:
var held := card.main.rolling.deck_reveal.held(card.table.id, e.id)
left = mini(copies, deck.remaining(card.table, e) + held)
var gone := left <= 0
var partly := not gone and left < copies
row.modulate = DRAWN_LOOK if gone else Color.WHITE
_show_partly_drawn(row, partly)
row.tooltip_text = "Already drawn: Shuffle the deck to put it back" if gone else ""
_show_copies_left(e, left, copies, partly)
## How far the partly drawn tint's hue is turned from the accent, so it isn't
## mistaken for a lit row (pale accent).
const PARTLY_DRAWN_TURN := 200.0
## The tint on a row with some of its copies drawn (laid over the row, so it
## shows on a plain row, a striped one and a lit one alike).
static func partly_drawn_tint() -> Color:
return Color(Style.turned_accent(PARTLY_DRAWN_TURN), 0.45)
## A row's partly drawn tint: a colour layer behind its contents, made on
## first use. Returns the layer, or null when the row has none.
static func partly_drawn_layer(row: Control) -> ColorRect:
return row.get_node_or_null("PartlyDrawnTint") as ColorRect
func _show_partly_drawn(row: Control, partly: bool) -> void:
var layer := partly_drawn_layer(row)
if layer == null:
if not partly:
return
layer = ColorRect.new()
layer.name = "PartlyDrawnTint"
layer.mouse_filter = Control.MOUSE_FILTER_IGNORE
row.add_child(layer)
row.move_child(layer, 0) # first child: drawn behind the row's contents
layer.color = partly_drawn_tint()
layer.visible = partly
## Play mode: a partly drawn row's number becomes "<left> / <weight>".
func _show_copies_left(e: TableEntry, left: int, copies: int, partly: bool) -> void:
var part: Dictionary = card.rows_ui.parts.get(e.id, {})
var num: Label = part.get("num")
if num == null or not is_instance_valid(num):
return
if not num.has_meta("row_number"):
num.set_meta("row_number", [num.text, num.tooltip_text])
var own: Array = num.get_meta("row_number")
num.text = "%d / %d" % [left, copies] if partly else str(own[0])
num.tooltip_text = "%d of %d copies left in the deck" % [left, copies] if partly else str(own[1])
func build_styles() -> void:

View file

@ -66,11 +66,22 @@ static func chip(tray: ResultTray, step: Dictionary, last: bool, steps: Array =
var fx: Array = step.get("effects", [])
if not fx.is_empty():
v.add_child(_effect_lines(TrayText.effect_lines_for(step, main.data, plain)))
var pills := HBoxContainer.new()
pills.add_theme_constant_override("separation", 6)
if has_why:
var wb := _why_button()
var wb := _pill_button("Why this?", "What decided this step")
wb.pressed.connect(func() -> void: tray.open_why(index, wb))
tray.why_buttons[index] = wb
v.add_child(wb)
pills.add_child(wb)
if index >= 0 and main.rolling.reroll.can_reroll(index):
var rb := _pill_button("↻ Reroll this", "Roll this card again, and the cards after it")
rb.pressed.connect(func() -> void: main.rolling.reroll.reroll(index))
tray.reroll_buttons[index] = rb
pills.add_child(rb)
if pills.get_child_count() > 0:
v.add_child(pills)
else:
pills.free()
if has_details or has_why:
p.mouse_entered.connect(func() -> void:
if not tray.why_popover().visible:
@ -78,11 +89,11 @@ static func chip(tray: ResultTray, step: Dictionary, last: bool, steps: Array =
return p
## The small "Why this?" pill under a chip.
static func _why_button() -> Button:
## A small pill button under a chip ("Why this?", "Reroll this").
static func _pill_button(text: String, tip: String) -> Button:
var b := Button.new()
b.text = "Why this?"
b.tooltip_text = "What decided this step"
b.text = text
b.tooltip_text = tip
b.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN
b.focus_mode = Control.FOCUS_NONE
var n := Style.bordered(Style.box(Color.WHITE, 10, [9, 1, 9, 2]), 1, Style.RULE)