Ranged cards: edit by Weights or Ranges, whole-row drag, auto-sort

A ranged card now stores that it is ranged, so an empty card can switch
between Plain and Ranged. Cards made ranged are edited by weight (die faces
per result; ranges follow the row order); a gap becomes an empty result.
Ranges mode keeps typed ranges, rows drag with their range, and auto-sort
(on by default) keeps rows in roll order. Old cards load as Ranges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
RobinFiredrake 2026-11-15 12:29:52 -06:00
parent 91c19980f7
commit f335faa5c5
13 changed files with 335 additions and 28 deletions

117
core/range_weights.gd Normal file
View file

@ -0,0 +1,117 @@
class_name RangeWeights
extends RefCounted
## How Build edits a ranged card (RollTable.range_edit):
## - Weights: each result says how many die faces it covers (TableEntry.weight);
## the ranges are laid out from it in row order (reflow). Dragging a row moves
## its share, and the ranges after it follow.
## - Ranges: each range is typed by hand, as printed books do. With auto_sort on,
## rows put themselves back in roll order after an edit or a drag.
## The ranges stay the stored truth either way, so rolling never looks at this.
const WEIGHTS := "weights"
const RANGES := "ranges"
## True when the card's ranges come from its weights.
static func uses_weights(t: RollTable) -> bool:
return t.is_ranged() and t.range_edit == WEIGHTS
## First value the weights lay out from: the dice's lowest roll, or, for a card
## whose totals clamp (a modifier or expression dice), where its first range starts.
static func start_value(t: RollTable) -> int:
if RollRange.clamps(t):
for e in t.entries:
if e.has_range:
return e.range_lo
return RollRange.natural(t).x
## Lays the ranges out from the weights, in row order. Weight 0 = no range.
static func reflow(t: RollTable) -> void:
var next := start_value(t)
for e in t.entries:
if e.weight <= 0:
e.has_range = false
continue
e.has_range = true
e.range_lo = next
e.range_hi = next + e.weight - 1
next = e.range_hi + 1
## Switches how the card is edited. Going to Weights reads each weight off its
## range and turns every gap between ranges into an empty result, so no roll
## changes. Going to Ranges keeps the ranges as they are.
static func set_mode(t: RollTable, mode: String) -> void:
if mode == t.range_edit:
return
t.range_edit = mode
if mode == WEIGHTS:
to_weights(t)
elif t.auto_sort:
sort_rows(t)
static func to_weights(t: RollTable) -> void:
sort_rows(t)
var out: Array[TableEntry] = []
var next := start_value(t)
for e in t.entries:
if not e.has_range:
e.weight = 0
out.append(e)
continue
if e.range_lo > next:
var gap := TableEntry.new(TowerBoard.new_id("e"), "")
gap.weight = e.range_lo - next
out.append(gap)
# Overlaps can't be kept as weights: the later row starts after the earlier one.
e.weight = maxi(1, e.range_hi - maxi(e.range_lo, next) + 1)
next = maxi(next, e.range_hi + 1)
out.append(e)
t.entries = out
reflow(t)
## Puts rows in roll order (by range start); rows without a range keep their
## order at the end. Returns true when anything moved.
static func sort_rows(t: RollTable) -> bool:
var before := t.entries.map(func(e: TableEntry) -> String: return e.id)
var ranged: Array[TableEntry] = []
var rest: Array[TableEntry] = []
for e in t.entries:
(ranged if e.has_range else rest).append(e)
ranged.sort_custom(func(a: TableEntry, b: TableEntry) -> bool: return a.range_lo < b.range_lo)
var sorted: Array[TableEntry] = []
sorted.append_array(ranged)
sorted.append_array(rest)
t.entries = sorted
return sorted.map(func(e: TableEntry) -> String: return e.id) != before
## After a weight, range or row-order edit: reflow (Weights) or auto-sort
## (Ranges). Returns true when auto-sort moved rows.
static func after_edit(t: RollTable) -> bool:
if not t.is_ranged():
return false
if t.range_edit == WEIGHTS:
reflow(t)
return false
return t.auto_sort and sort_rows(t)
## "Weights add up to 95 of 100: 5 short." when the weights don't cover the
## dice exactly; "" when they do, or when the card isn't edited by weight.
static func total_problem(t: RollTable) -> String:
if not uses_weights(t) or t.is_expr_dice():
return ""
var total := 0
for e in t.entries:
total += maxi(0, e.weight)
var nat := RollRange.natural(t)
var size := nat.y - nat.x + 1
if total == size or (total > size and RollRange.clamps(t)):
return ""
var off := "%d short" % (size - total) if total < size else "%d too many" % (total - size)
return "Weights add up to %d of %d: %s." % [total, size, off]

View file

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

View file

@ -280,6 +280,9 @@ static func problems(t: RollTable) -> String:
var back := backwards(t)
if back != "":
return "The range %s runs backwards: make its start no bigger than its end. The card can't be rolled until then." % back
var weights_note := RangeWeights.total_problem(t)
if weights_note != "":
return weights_note
var lo := min_value(t)
var hi := max_value(t)
if clamps(t):

View file

@ -71,6 +71,14 @@ var dice: String = DEFAULT_DICE
## Ranged tables: the modifier added to the dice, an expression ("@luck",
## "-@fatigue", "dm(@str)", "2"), or "" for none.
var dice_mod: String = ""
## Ranged even while no result has a range (an empty card switched to Ranged).
## Results with ranges make a card ranged either way (is_ranged).
var ranged: bool = false
## How Build edits the ranges: RangeWeights.WEIGHTS or RangeWeights.RANGES.
## Cards made before this setting existed load as Ranges, so nothing moves.
var range_edit: String = "ranges"
## Ranges mode: rows put themselves back in roll order after edits and drags.
var auto_sort: bool = true
## Card mode: entries are drawn without replacement until the deck is empty.
var card_mode: bool = false
## What happens when the deck runs out: "reshuffle" or "stop".
@ -236,6 +244,8 @@ func is_kind(k: String) -> bool:
func is_ranged() -> bool:
if ranged:
return true
for e in entries:
if e.has_range:
return true

View file

@ -31,6 +31,11 @@ static func to_dict(t: RollTable) -> Dictionary:
d["list_h"] = roundi(t.list_height)
if t.is_ranged():
d["dice"] = t.dice
d["ranged"] = true
if t.range_edit == RangeWeights.WEIGHTS:
d["range_edit"] = RangeWeights.WEIGHTS
if not t.auto_sort:
d["auto_sort"] = false
if t.has_mod():
d["dice_mod"] = t.dice_mod.strip_edges()
if t.card_mode:
@ -117,6 +122,9 @@ static func from_dict(d: Dictionary) -> RollTable:
elif int(d.get("die", 0)) > 1:
t.dice = "1d%d" % int(d["die"])
t.dice_mod = RollTable.expr_text(d.get("dice_mod", ""), "").strip_edges()
t.ranged = bool(d.get("ranged", false))
t.range_edit = RangeWeights.WEIGHTS if str(d.get("range_edit", "")) == RangeWeights.WEIGHTS else RangeWeights.RANGES
t.auto_sort = bool(d.get("auto_sort", true))
t.card_mode = bool(d.get("card_mode", false))
t.deck_empty = "stop" if str(d.get("deck_empty", "reshuffle")) == "stop" else "reshuffle"
t.deck_empty_text = str(d.get("deck_empty_text", ""))

View file

@ -42,17 +42,42 @@ func _test_plain() -> void:
_eq(_ids(main.data.get_table("monsters")), before, "undo puts the order back")
func _test_ranged() -> void:
var t := main.data.get_table("wilderness")
## Drags a ranged card's first row to the third row's place.
func _drag_first_down_two(t: RollTable) -> String:
var card := main.card_for(t.id)
var ranges := t.entries.map(func(e: TableEntry) -> Vector2i: return Vector2i(e.range_lo, e.range_hi))
var moved: String = t.entries[0].id
var h := _handle(card, moved)
var second := (card.rows[t.entries[2].id] as Control).get_global_rect()
h.track(second.get_center() + Vector2(0, 2))
h.finish()
return moved
func _test_ranged() -> void:
var t := main.data.get_table("wilderness")
_eq(t.range_edit, RangeWeights.RANGES, "a loaded card keeps typed ranges")
var first_range := Vector2i(t.entries[0].range_lo, t.entries[0].range_hi)
# Auto-sort (on by default) puts a Ranges card back in roll order.
var moved := _drag_first_down_two(t)
await _frames()
_eq(t.entries.find(t.find_entry(moved)), 2, "the result moved down two places")
_eq(t.entries.map(func(e: TableEntry) -> Vector2i: return Vector2i(e.range_lo, e.range_hi)), ranges,
"the ranges stay in place")
_eq(t.entries.find(t.find_entry(moved)), 0, "auto-sort puts the row back in roll order")
# Without auto-sort the whole row moves, range and all.
t.auto_sort = false
moved = _drag_first_down_two(t)
await _frames()
var e := t.find_entry(moved)
_eq(t.entries.find(e), 2, "the result moved down two places")
_eq(Vector2i(e.range_lo, e.range_hi), first_range, "its range moved with it")
_eq(t.range_problems(), "", "the ranges still cover the dice")
# Weights: the moved row's share follows it and the ranges are laid out again.
t.auto_sort = true
RangeWeights.set_mode(t, RangeWeights.WEIGHTS)
main.card_for(t.id).rebuild()
await _frames()
_eq(t.entries[0].range_lo, RollRange.natural(t).x, "Weights: the first row starts at the dice's lowest roll")
var size := e.weight
moved = _drag_first_down_two(t)
await _frames()
_eq(t.find_entry(moved).range_hi - t.find_entry(moved).range_lo + 1, t.find_entry(moved).weight, "Weights: the moved row keeps its share")
_eq(t.range_problems(), "", "Weights: the ranges still cover the dice")
_check(size > 0, "weights were read off the ranges")

View file

@ -0,0 +1,98 @@
extends TestBase
## Headless checks for ranged cards edited by weight or by range (RangeWeights):
## turning gaps into empty results, laying ranges out from weights, the total
## warning, auto-sort, the file format, and an empty card switching to Ranged.
## Run: godot --headless --path . -s res://tests/test_range_weights.gd
func _init() -> void:
_test_to_weights()
_test_total_warning()
_test_auto_sort()
_test_file_format()
_test_empty_card_ranged()
finish()
## The user's example: d100 with 1–5, 10–80, 81–87, 88–100 (a gap at 6–9).
func _workday() -> RollTable:
var t := RollTable.new("work", "Workday Job")
t.dice = "1d100"
for r: Array in [["Result 1", 1, 5], ["Bob", 10, 80], ["Joe", 81, 87], ["Kevin", 88, 100]]:
var e := TableEntry.new("e%d" % t.entries.size(), r[0])
e.has_range = true
e.range_lo = r[1]
e.range_hi = r[2]
t.entries.append(e)
return t
func _texts(t: RollTable) -> Array:
return t.entries.map(func(e: TableEntry) -> String: return e.text)
func _spans(t: RollTable) -> Array:
return t.entries.map(func(e: TableEntry) -> Vector2i: return Vector2i(e.range_lo, e.range_hi))
func _test_to_weights() -> void:
var t := _workday()
RangeWeights.set_mode(t, RangeWeights.WEIGHTS)
_eq(_texts(t), ["Result 1", "", "Bob", "Joe", "Kevin"], "the 6–9 gap becomes an empty result")
_eq(t.entries.map(func(e: TableEntry) -> int: return e.weight), [5, 4, 71, 7, 13], "weights are read off the ranges")
_eq(_spans(t)[1], Vector2i(6, 9), "no roll changes: the empty result covers 6–9")
_eq(t.range_problems(), "", "the weights cover the d100")
t.entries[2].weight = 70
RangeWeights.reflow(t)
_eq(_spans(t)[3], Vector2i(80, 86), "editing a weight moves the ranges after it")
func _test_total_warning() -> void:
var t := _workday()
RangeWeights.set_mode(t, RangeWeights.WEIGHTS)
t.entries[1].weight = 0
RangeWeights.reflow(t)
_eq(t.range_problems(), "Weights add up to 96 of 100: 4 short.", "a short total says so")
_check(not t.entries[1].has_range, "weight 0 gives no range")
t.entries[0].weight = 10
RangeWeights.reflow(t)
_eq(t.range_problems(), "Weights add up to 101 of 100: 1 too many.", "a long total says so")
func _test_auto_sort() -> void:
var t := _workday()
var bob := t.entries[1]
t.entries.remove_at(1)
t.entries.append(bob)
_check(RangeWeights.after_edit(t), "auto-sort reports that it moved rows")
_eq(_texts(t), ["Result 1", "Bob", "Joe", "Kevin"], "auto-sort puts the rows in roll order")
t.auto_sort = false
t.entries.remove_at(1)
t.entries.append(bob)
_check(not RangeWeights.after_edit(t), "with auto-sort off nothing moves")
_eq(_texts(t), ["Result 1", "Joe", "Kevin", "Bob"], "the dragged order stays")
func _test_file_format() -> void:
var t := _workday()
var d := t.to_dict()
_check(not d.has("range_edit"), "Ranges is the default in files, so old cards load unchanged")
RangeWeights.set_mode(t, RangeWeights.WEIGHTS)
t.auto_sort = false
d = t.to_dict()
var back := RollTable.from_dict(d)
_eq(back.range_edit, RangeWeights.WEIGHTS, "Weights is saved")
_check(not back.auto_sort, "auto-sort off is saved")
var empty := RollTable.new("empty", "Empty")
empty.ranged = true
_check(RollTable.from_dict(empty.to_dict()).is_ranged(), "an empty ranged card stays ranged after saving")
func _test_empty_card_ranged() -> void:
var t := RollTable.new("new", "New card")
var res := TableSettingsRules.apply_settings(t, {"ranged": true, "dice": "1d20"})
_check(res["ok"], "the switch is accepted")
_check(t.is_ranged(), "an empty card can switch to Ranged")
_eq(t.range_edit, RangeWeights.WEIGHTS, "a card made ranged is edited by weight")
TableSettingsRules.apply_settings(t, {"ranged": false})
_check(not t.is_ranged(), "and back to Plain")

View file

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

View file

@ -156,7 +156,13 @@ func add_entry(tid: String) -> void:
m.undo_redo._begin_edit()
var t := m.data.get_table(tid)
var e := TableEntry.new(TowerBoard.new_id("e"), "Result %d" % (t.entries.size() + 1))
if t.is_ranged():
if RangeWeights.uses_weights(t):
e.has_range = true
e.weight = 1
e.text = "New result"
t.entries.append(e)
RangeWeights.reflow(t)
elif t.is_ranged():
var hi := 0
for x in t.entries:
hi = maxi(hi, x.range_hi)
@ -165,7 +171,8 @@ func add_entry(tid: String) -> void:
e.range_lo = hi + 1 if t.has_mod() else clampi(hi + 1, t.min_value(), t.die_size())
e.range_hi = e.range_lo
e.text = "New range"
t.entries.append(e)
if not t.entries.has(e):
t.entries.append(e)
t.collapsed = false
m.card_for(tid).rebuild()
m.undo_redo._end_edit()

View file

@ -157,7 +157,7 @@ static func hbox(sep: int) -> HBoxContainer:
func _num_width(build: bool, ranged: bool) -> float:
var wide := table.die_size() >= 100
if build and ranged:
return 90.0
return 100.0 if RangeWeights.uses_weights(table) else 90.0
if ranged:
return 52.0 if wide else 40.0
return 24.0 if wide else 22.0

View file

@ -34,6 +34,8 @@ func text_edit(e: TableEntry, index: int, chosen: bool) -> LineEdit:
edit.tooltip_text = "%s: shown each pass ({i} is the pass number)" % loop_rows[0] if index == 0 else "%s: runs once when the repeat ends" % loop_rows[1]
elif table.kind == RollTable.KIND_ROUTER:
edit.placeholder_text = "Result text"
elif not chosen:
edit.placeholder_text = "(nothing)"
edit.text_changed.connect(func(s: String) -> void:
e.text = s
e.page = ""
@ -125,17 +127,13 @@ func move_entry(from: int, to: int) -> void:
var entries := card.table.entries
if from == to or from < 0 or from >= entries.size() or to < 0 or to >= entries.size():
return
var ranges: Array = []
for e in entries:
ranges.append([e.has_range, e.range_lo, e.range_hi])
# A row moves whole, with its range or weight; Weights then lay the ranges
# out again, and auto-sort may put a Ranges card back in roll order.
var moved := entries[from]
entries.remove_at(from)
entries.insert(to, moved)
if card.table.is_ranged():
for i in entries.size():
entries[i].has_range = ranges[i][0]
entries[i].range_lo = ranges[i][1]
entries[i].range_hi = ranges[i][2]
if RangeWeights.after_edit(card.table):
card.main.toast("Auto-sort put the rows back in roll order (turn it off in the card's settings)")
card.rebuild()
card.main.mark_dirty()
@ -156,28 +154,39 @@ func add_case() -> void:
## Weight on a plain table, shown as ×N. Also the number of copies in card mode.
func weight_edit(e: TableEntry) -> LineEdit:
## The weight box. `faces`: a Weights-mode ranged card, where the weight is
## how many die faces the result covers (shown plain, in a range-style box).
func weight_edit(e: TableEntry, faces: bool = false) -> LineEdit:
var edit := LineEdit.new()
edit.text = "×%d" % e.weight
edit.custom_minimum_size = Vector2(34, 0)
var shown := func(w: int) -> String: return str(w) if faces else "×%d" % w
edit.text = shown.call(e.weight)
edit.custom_minimum_size = Vector2(40 if faces else 34, 0)
edit.alignment = HORIZONTAL_ALIGNMENT_CENTER
edit.max_length = 4
edit.tooltip_text = "Weight: how likely this result is, relative to the others (0 = never)"
edit.tooltip_text = "Weight: how many die faces this result covers (0 = never). The ranges follow the row order." if faces \
else "Weight: how likely this result is, relative to the others (0 = never)"
edit.size_flags_vertical = Control.SIZE_SHRINK_CENTER
edit.add_theme_font_override("font", Style.display(true))
edit.add_theme_font_size_override("font_size", 14)
edit.add_theme_color_override("font_color", Style.MUTED)
edit.add_theme_font_size_override("font_size", 15 if faces else 14)
if faces:
edit.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 4, [2, 2, 2, 2]), 1, Style.RULE))
edit.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 4, [2, 2, 2, 2]), 1, Style.TRIM))
else:
edit.add_theme_color_override("font_color", Style.MUTED)
var commit := func() -> void:
var digits := ""
for ch in edit.text:
if ch >= "0" and ch <= "9":
digits += ch
var w := clampi(digits.to_int(), 0, 999) if digits != "" else e.weight
edit.text = "×%d" % w
var w := clampi(digits.to_int(), 0, 9999 if faces else 999) if digits != "" else e.weight
edit.text = shown.call(w)
if w != e.weight:
e.weight = w
card.update_deck()
card.main.mark_dirty()
if RangeWeights.uses_weights(card.table):
RangeWeights.reflow(card.table)
card.rebuild.call_deferred()
edit.text_submitted.connect(func(_t: String) -> void: commit.call())
edit.focus_exited.connect(commit)
return edit
@ -208,8 +217,11 @@ func range_edit(e: TableEntry, is_lo: bool) -> LineEdit:
else:
e.range_hi = v
edit.text = str(e.range_lo if is_lo else e.range_hi)
card.update_warning()
card.main.mark_dirty()
if RangeWeights.after_edit(table):
card.rebuild.call_deferred()
else:
card.update_warning()
edit.text_submitted.connect(func(_t: String) -> void: commit.call())
edit.focus_exited.connect(commit)
return edit
@ -227,7 +239,7 @@ func make_footer(ranged: bool) -> Control:
wrap.add_child(h)
# Loops, sheets, variables and number/text choices have fixed rows.
if table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and table.choice == "pick"):
var label := "+ Add range" if ranged else ("+ Add option" if table.kind == RollTable.KIND_CHOICE else "+ Add result")
var label := "+ Add range" if ranged and not RangeWeights.uses_weights(table) else ("+ Add option" if table.kind == RollTable.KIND_CHOICE else "+ Add result")
var add := footer_button(label, Style.INK)
add.pressed.connect(func() -> void: main.add_entry(table.id))
h.add_child(add)

View file

@ -90,7 +90,19 @@ func make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float)
if build and not fixed and not chosen and table.entries.size() > 1:
h.add_child(EntryHandle.new(card, e.id))
var num: Label = null
if build and ranged:
if build and RangeWeights.uses_weights(table):
# Weights: the box sets the share; the range it gives is shown beside it.
var r := TableCard.hbox(6)
r.custom_minimum_size = Vector2(numw, 0)
r.size_flags_vertical = Control.SIZE_SHRINK_CENTER
r.add_child(edit.weight_edit(e, true))
var span := Style.make_label(table.num_label(e, index) if e.has_range else "—", Style.display(true), 14, Style.MUTED)
span.custom_minimum_size = Vector2(52, 0)
span.mouse_filter = Control.MOUSE_FILTER_PASS
span.tooltip_text = "The range this weight gives, from the row order"
r.add_child(span)
h.add_child(r)
elif build and ranged:
var r := TableCard.hbox(2)
r.custom_minimum_size = Vector2(numw, 0)
r.size_flags_vertical = Control.SIZE_SHRINK_CENTER

View file

@ -137,6 +137,7 @@ static func _apply_kind(t: RollTable, s: Dictionary) -> void:
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Answer"))
t.entries[0].text = "Answer"
t.entries[0].has_range = false
t.ranged = false
t.card_mode = false
t.choice = c
t.prompt = str(s.get("prompt", t.prompt))
@ -293,8 +294,18 @@ static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary:
t.dice = dice
if not was_ranged:
assign_ranges(t)
# A card made ranged now is edited by weight (RangeWeights).
t.range_edit = RangeWeights.RANGES
RangeWeights.set_mode(t, RangeWeights.WEIGHTS)
elif was_ranged:
drop_ranges(t)
if ranged:
if s.has("auto_sort"):
t.auto_sort = bool(s["auto_sort"])
if s.has("range_edit"):
RangeWeights.set_mode(t, str(s["range_edit"]))
if was_ranged and old_dice != t.dice:
RangeWeights.after_edit(t)
_apply_kind(t, s)
var deck_reset := was_ranged != ranged or old_card != t.card_mode or (ranged and old_dice != t.dice)
return {"ok": true, "error": "", "deck_reset": deck_reset}
@ -304,6 +315,7 @@ static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary:
## value each while there is room). Entries of weight 0 get no range. Each
## entry keeps only its first pipe, since a range takes one pipe.
static func assign_ranges(t: RollTable) -> void:
t.ranged = true
var d := t.dice_obj()
var lo := d.min_value()
var hi := d.max_value()
@ -336,6 +348,7 @@ static func assign_ranges(t: RollTable) -> void:
static func drop_ranges(t: RollTable) -> void:
t.ranged = false
for e in t.entries:
e.has_range = false
e.range_lo = 1