From 33913889da1518a0cb62555cc83f059852e43e22 Mon Sep 17 00:00:00 2001 From: RobinFiredrake Date: Mon, 9 Nov 2026 10:01:10 -0600 Subject: [PATCH] Roll modifiers and resizable tray/inspector - Ranged roll tables take a modifier (dice_mod, e.g. @luck). Ranges may run past the dice (-3 to 24 on a d20); totals past the ends use the end result. - Range and chance code moved from RollTable into RollRange; chances follow the modifier's current value; plain wording and Why lines name it. - ModifierEditor builds modifiers in plain words for roll and check cards; the inspector's roll section is now InspectorRoll. - The Earlier tab scrolls; the tray and inspector resize with drag handles (PanelSplitter), sizes kept in local settings. - Demo Room check uses 2d6 + Luck with a luck-only vault; new test_modifier suite; docs updated. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 + core/board_tester.gd | 2 + core/builder.gd | 2 + core/deck_state.gd | 4 +- core/describe.gd | 61 ++++++-- core/roll_cards.gd | 25 ++-- core/roll_range.gd | 280 ++++++++++++++++++++++++++++++++++++ core/roll_range.gd.uid | 1 + core/roll_table.gd | 177 ++++++----------------- core/roll_tree.gd | 2 +- docs/DESIGN.md | 40 +++++- docs/LOGIC.md | 36 ++++- docs/PLAIN.md | 4 +- examples/logic_demo.json | 8 +- io/json_io.gd | 4 +- tests/test_inspector.gd | 27 ++-- tests/test_logic_ui.gd | 7 +- tests/test_modifier.gd | 193 +++++++++++++++++++++++++ tests/test_modifier.gd.uid | 1 + tests/test_navigation.gd | 62 +++++++- ui/details_popup.gd | 4 +- ui/earlier_rolls.gd | 13 +- ui/inspector.gd | 24 +++- ui/inspector_card.gd | 118 +-------------- ui/inspector_roll.gd | 83 +++++++++++ ui/inspector_roll.gd.uid | 1 + ui/main.gd | 11 ++ ui/main_editing.gd | 3 +- ui/modifier_editor.gd | 181 +++++++++++++++++++++++ ui/modifier_editor.gd.uid | 1 + ui/panel_splitter.gd | 114 +++++++++++++++ ui/panel_splitter.gd.uid | 1 + ui/result_tray.gd | 41 ++++-- ui/rules_view.gd | 13 +- ui/table_card.gd | 1 + ui/table_card_editing.gd | 12 +- ui/table_card_header.gd | 12 +- ui/table_card_rows.gd | 40 +++++- ui/table_preview.gd | 14 +- ui/table_settings_dialog.gd | 47 +++++- ui/table_settings_rules.gd | 17 ++- ui/variables_panel.gd | 6 +- 42 files changed, 1350 insertions(+), 349 deletions(-) create mode 100644 core/roll_range.gd create mode 100644 core/roll_range.gd.uid create mode 100644 tests/test_modifier.gd create mode 100644 tests/test_modifier.gd.uid create mode 100644 ui/inspector_roll.gd create mode 100644 ui/inspector_roll.gd.uid create mode 100644 ui/modifier_editor.gd create mode 100644 ui/modifier_editor.gd.uid create mode 100644 ui/panel_splitter.gd create mode 100644 ui/panel_splitter.gd.uid diff --git a/README.md b/README.md index fd95ce1..b70a243 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,12 @@ godot --path . **Board ▾** menu imports and exports TableTower JSON, JSON Canvas, Mermaid, DOT and GraphML. - **Ranged tables** (like *Wilderness Travel*) roll a d100 where each range's size sets its chance. Each range takes one pipe; laying a new one replaces the old. +- **Modifiers:** a ranged table can add a modifier to its roll, such as "roll 1d20 and add your + Luck". In Build mode, pick **Modifier: Add ▾ Luck ▾** in the inspector. Ranges may go past the + dice (−3 to 24 on a d20), and a total past the lowest or highest result counts as that result. + The card's chances follow Luck's current value. +- **Resizing:** drag the top edge of the result tray or the left edge of the inspector. + Double-click the edge to go back to the default size. - **Collapsing:** the arrow beside a table's name collapses it. A collapsed table still shows its last result. **Collapse all / Expand all** in the top bar does every table at once. - **Groups:** in Build mode, Ctrl- or Shift-click card headers (or Ctrl-drag on the felt) to diff --git a/core/board_tester.gd b/core/board_tester.gd index b5e7fdc..b91a9c9 100644 --- a/core/board_tester.gd +++ b/core/board_tester.gd @@ -270,6 +270,8 @@ static func static_checks(b: TowerBoard) -> Array[Dictionary]: add.call("expression", t, eid, "%s \"%s\": %s" % [what, src, err]) if t.is_expr_dice(): expr.call("Dice", t.dice) + if t.is_ranged(): + expr.call("Modifier", t.dice_mod) if t.is_ranged(): var rp := t.range_problems() if rp != "": diff --git a/core/builder.gd b/core/builder.gd index 8fcae62..251541e 100644 --- a/core/builder.gd +++ b/core/builder.gd @@ -433,6 +433,8 @@ static func known_values(board: TowerBoard) -> Array[Dictionary]: chain["nat"] = true if t.is_expr_dice(): reads.append([t.dice, t.id]) + if t.has_mod(): + reads.append([t.dice_mod, t.id]) for inp: Dictionary in t.inputs: add.call(str(inp.get("name", "")), _kind_of_expr(str(inp.get("default", ""))), "input", t.id) for e in t.entries: diff --git a/core/deck_state.gd b/core/deck_state.gd index 563a8ab..07b5d70 100644 --- a/core/deck_state.gd +++ b/core/deck_state.gd @@ -60,7 +60,7 @@ func draw(table: RollTable, rng: RandomNumberGenerator) -> Dictionary: for e in table.entries: var w := float(_remaining(table, e)) if table.is_ranged(): - w *= 1.0 if table.is_expr_dice() else table.chance(e) + w *= 1.0 if table.clamps() else table.chance(e) weights.append(w) sum += w if sum <= 0.0: @@ -84,7 +84,7 @@ func draw(table: RollTable, rng: RandomNumberGenerator) -> Dictionary: ## 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.is_expr_dice(): + if table.clamps(): return rng.randi_range(e.range_lo, e.range_hi) var dist := table.dice_obj().distribution() var vals: Array[int] = [] diff --git a/core/describe.gd b/core/describe.gd index 04c099b..0889dd1 100644 --- a/core/describe.gd +++ b/core/describe.gd @@ -428,14 +428,8 @@ static func check(table: RollTable, board: TowerBoard) -> String: if table == null or table.kind != RollTable.KIND_CHECK: return "" var L := _labels(board) - var roll := _expr(table.check_dice, L) + var roll := _with_mod(table.check_dice, table.check_mod, L) var mod := table.check_mod.strip_edges() - if mod != "": - var mt := Builder.tokens(mod) - if not mt.is_empty() and mt[0]["s"] == "-": - roll += " %s %s" % [MINUS, _expr(mod.substr(1), L)] - else: - roll += " + " + _expr(mod, L) var target := _expr(table.check_target, L) var num := Expr.is_number(table.check_target.strip_edges()) var need := "" @@ -446,6 +440,27 @@ static func check(table: RollTable, board: TowerBoard) -> String: return _short("Roll %s, need %s" % [roll, need], "Roll %s %s vs %s" % [table.check_dice, mod, table.check_target]) +## A ranged roll table's roll: "Roll d20 + Luck", "Roll 2D − Fatigue", +## "Roll d100". "" for other cards. +static func roll(table: RollTable, board: TowerBoard) -> String: + if table == null or table.kind != RollTable.KIND_ROLL or not table.is_ranged(): + return "" + return "Roll " + _with_mod(table.dice, table.dice_mod, _labels(board)) + + +## Dice plus a modifier in words: "2D + Strength modifier", "d20 − Fatigue". +static func _with_mod(dice_src: String, mod_src: String, L: Dictionary) -> String: + var out := _expr(dice_src, L) + var mod := mod_src.strip_edges() + if mod != "": + var mt := Builder.tokens(mod) + if not mt.is_empty() and mt[0]["s"] == "-": + out += " %s %s" % [MINUS, _expr(mod.substr(1), L)] + else: + out += " + " + _expr(mod, L) + return out + + # ---------------------------------------------------------------- why ## One trace fact (Roller node/step "why") as a sentence. Plain mode uses @@ -459,7 +474,7 @@ static func why(fact: Dictionary, board: TowerBoard, plain: bool = true) -> Stri var s := "" match str(fact.get("type", "")): "roll": - s = _why_roll(fact, plain) + s = _why_roll(fact, L, plain) "check": s = _why_check(fact, L, plain) "when": @@ -540,6 +555,11 @@ static func _nonzero(v: Variant) -> bool: return Expr.is_number(n) and n != 0 +## "+2", "−1", "+0". +static func signed_number(n: int) -> String: + return _signed(n) + + static func _signed(v: Variant) -> String: var n: Variant = Expr.to_value(v) if not Expr.is_number(n): @@ -547,7 +567,10 @@ static func _signed(v: Variant) -> String: return ("+" + Expr.format_value(n)) if n >= 0 else (MINUS + Expr.format_value(-n)) -static func _why_roll(f: Dictionary, plain: bool) -> String: +## A roll fact as a sentence: "Rolled 17, +3 for Luck = 20". A total past +## the table's ends adds "past the top of the table, so it counts as 24" +## (fact key counts_as). +static func _why_roll(f: Dictionary, L: Dictionary, plain: bool) -> String: var total := Expr.format_value(f.get("total")) match str(f.get("pick", "dice")): "weighted": @@ -555,16 +578,26 @@ static func _why_roll(f: Dictionary, plain: bool) -> String: "card": return "Drew card %s" % total if plain else "draw: card %s" % total var faces := _faces(f.get("faces")) + var past := f.has("counts_as") + var ends := Expr.format_value(f.get("counts_as")) if not plain: var t := "roll %s: %s" % [f.get("dice", ""), faces if faces != "" else total] if f.has("mod") and _nonzero(f["mod"]): t += " %s = %s" % [_signed(f["mod"]).replace(MINUS, "-"), total] + if past: + t += " (past the end: %s)" % ends return t - if faces == "": - return "Worked out %s" % total - var s := "Rolled " + faces - if f.has("mod") and _nonzero(f["mod"]): - s += ", %s = %s" % [_signed(f["mod"]), total] + var s := "Worked out %s" % total + if faces != "": + s = "Rolled " + faces + if f.has("mod") and _nonzero(f["mod"]): + var why_mod := "" + if str(f.get("mod_expr", "")) != "": + why_mod = " for " + _expr(str(f["mod_expr"]).trim_prefix("-"), L) + s += ", %s%s = %s" % [_signed(f["mod"]), why_mod, total] + if past: + var top: bool = float(Expr.to_value(f.get("counts_as"))) < float(Expr.to_value(f.get("total"))) + s += ", past the %s of the table, so it counts as %s" % ["top" if top else "bottom", ends] return s diff --git a/core/roll_cards.gd b/core/roll_cards.gd index 444ee09..41cbf54 100644 --- a/core/roll_cards.gd +++ b/core/roll_cards.gd @@ -38,16 +38,23 @@ static func pick_node(t: RollTable, ctx: RollContext) -> Dictionary: if was != null: (was as Array).append_array(faces) if rv["error"] != "": - return Roller._stop(t, "Can't roll %s: %s" % [t.dice, rv["error"]]) + return Roller._stop(t, "Can't roll %s: %s" % [t.roll_text(), rv["error"]]) value = int(rv["value"]) - fact = {"type": "roll", "pick": "dice", "dice": t.dice.strip_edges(), "faces": faces, "total": value} + fact = {"type": "roll", "pick": "dice", "dice": t.roll_text(), "faces": faces, "total": value} + # The Why line names the modifier ("+3 for Luck") when it's all of the change. + if t.has_mod() and not t.is_expr_dice() and t.dice_obj().bonus == 0: + fact["mod_expr"] = t.dice_mod.strip_edges() if not faces.is_empty(): var nat := 0 for x: int in faces: nat += x fact["nat"] = nat fact["mod"] = value - nat - index = t.entry_index_clamped(value) if t.is_expr_dice() else t.entry_index_for(value) + index = t.entry_index_clamped(value) + if t.clamps(): + var span := RollRange.span(t) + if value < span.x or value > span.y: + fact["counts_as"] = clampi(value, span.x, span.y) if index < 0: return Roller._stop(t, "No result for %s" % t.fmt(value), {"value": value}) else: @@ -149,13 +156,11 @@ static func check_roll(t: RollTable, ctx: RollContext) -> Dictionary: out["error"] = "Check dice %s gave \"%s\", not a number" % [t.check_dice, Expr.format_value(r["value"])] return out var nat := Expr.as_int(r, 0) - var mod := 0 - if t.check_mod.strip_edges() != "": - var m := Expr.evaluate(t.check_mod, ctx) - if m["error"] != "" or not Expr.is_number(m["value"]): - out["error"] = "Check modifier %s: %s" % [t.check_mod, m["error"] if m["error"] != "" else "not a number"] - return out - mod = Expr.as_int(m, 0) + var m := RollRange.modifier(t.check_mod, ctx) + if m["error"] != "": + out["error"] = "Check modifier %s: %s" % [t.check_mod, m["error"]] + return out + var mod: int = m["value"] var g := Expr.evaluate(t.check_target, ctx) if g["error"] != "" or not Expr.is_number(g["value"]): out["error"] = "Check target %s: %s" % [t.check_target, g["error"] if g["error"] != "" else "not a number"] diff --git a/core/roll_range.gd b/core/roll_range.gd new file mode 100644 index 0000000..ec567c0 --- /dev/null +++ b/core/roll_range.gd @@ -0,0 +1,280 @@ +class_name RollRange +extends RefCounted +## The numbers side of a ranged roll table (RollTable delegates here): its +## span, number labels, chances, range problems and the roll modifier. +## +## A ranged table rolls `dice` and then adds its modifier (`dice_mod`, an +## expression such as "@luck", "-@fatigue" or "dm(@str)"). The dice alone +## give the natural range (1–20 for 1d20). Results may sit past it (-3, 24): +## only a modifier reaches them. A table with a modifier, or with a whole +## expression as its dice, uses the nearest result for totals past its ends: +## a total below the lowest range or above the highest one counts as that end +## result ("clamps"). + + +## True when totals past the ends count as the end results: a ranged table +## with a modifier or with an expression for its dice. +static func clamps(t: RollTable) -> bool: + return t.is_ranged() and (t.is_expr_dice() or t.has_mod()) + + +## Vector2i(lowest, highest) range values over the ranged results. +static func span(t: RollTable) -> Vector2i: + var lo := 0 + var hi := 0 + var first := true + for e in t.entries: + if not e.has_range: + continue + if first: + lo = e.range_lo + hi = e.range_hi + first = false + else: + lo = mini(lo, e.range_lo) + hi = maxi(hi, e.range_hi) + return Vector2i(lo, hi) + + +## Vector2i(lowest, highest) the dice alone can roll. Expression dice have +## no known natural range, so it's the ranges' span. +static func natural(t: RollTable) -> Vector2i: + if t.is_expr_dice(): + return span(t) + var d := t.dice_obj() + return Vector2i(d.min_value(), d.max_value()) + + +## Lowest value the card shows or rolls: 1 on plain tables, the ranges' span +## for expression dice, the dice and the ranges together with a modifier. +static func min_value(t: RollTable) -> int: + if not t.is_ranged(): + return 1 + if t.is_expr_dice(): + return span(t).x + if t.has_mod(): + return mini(span(t).x, natural(t).x) + return t.dice_obj().min_value() + + +## Highest value (see min_value). Plain tables: the result count. +static func max_value(t: RollTable) -> int: + if not t.is_ranged(): + return t.entries.size() + if t.is_expr_dice(): + return span(t).y + if t.has_mod(): + return maxi(span(t).y, natural(t).y) + return t.dice_obj().max_value() + + +## True when the dice alone (no modifier) can land on the result. +static func natural_reach(t: RollTable, e: TableEntry) -> bool: + if not e.has_range: + return false + return t.is_expr_dice() or chance(t, e, 0) > 0.0 + + +# ---------- Labels ---------- + +## Formats a value the way printed tables do: plain d100 values are two +## digits and 100 is written "00". +static func fmt(t: RollTable, value: int) -> String: + var two_digit := (t.dice_obj().is_d100() and not clamps(t)) if t.is_ranged() else t.entries.size() == 100 + if two_digit: + return "00" if value == 100 else "%02d" % value + return str(value) + + +## The number column: "3", "01–30", and "≤6" / "24+" on the end results of +## a table that uses the nearest result past its ends. +static func num_label(t: RollTable, e: TableEntry, index: int) -> String: + if not e.has_range: + return fmt(t, index + 1) + if clamps(t): + var s := span(t) + var ranged := 0 + for x in t.entries: + if x.has_range: + ranged += 1 + if ranged > 1: + if e.range_lo == s.x: + return "≤%s" % fmt(t, e.range_hi) + if e.range_hi == s.y: + return "%s+" % fmt(t, e.range_lo) + if e.range_lo == e.range_hi: + return fmt(t, e.range_lo) + return "%s–%s" % [fmt(t, e.range_lo), fmt(t, e.range_hi)] + + +# ---------- Chances ---------- + +## Chance (0–1) that a roll lands on the result, with the modifier at `mod` +## (ignored when the table has none). 0 for expression dice, whose chances +## can't be known. +static func chance(t: RollTable, e: TableEntry, mod: int = 0) -> float: + if not t.is_ranged(): + var total := t.total_weight() + return float(maxi(0, e.weight)) / float(total) if total > 0 else 0.0 + if not e.has_range or t.is_expr_dice(): + return 0.0 + var d := t.dice_obj() + if not t.has_mod(): + return d.probability_between(e.range_lo, e.range_hi) + var s := span(t) + var p := 0.0 + var dist := d.distribution() + for v: int in dist: + var x := clampi(v + mod, s.x, s.y) + if x >= e.range_lo and x <= e.range_hi: + p += float(dist[v]) + return p + + +## True when the result can come up at all (with some modifier, on a table +## that has one). +static func can_come_up(t: RollTable, e: TableEntry) -> bool: + if t.is_ranged(): + return e.has_range and (clamps(t) or chance(t, e) > 0.0) + return e.weight > 0 + + +# ---------- The modifier ---------- + +## "1d20 + @luck", "2d6 - 1", or the dice alone when there's no modifier. +static func join(dice: String, mod: String) -> String: + var d := dice.strip_edges() + var m := mod.strip_edges() + if m == "": + return d + if m.begins_with("-"): + return "%s - %s" % [d, m.substr(1).strip_edges()] + return "%s + %s" % [d, m] + + +## Works out a modifier expression: {"value": int, "error": String}. "" +## gives 0. Shared by roll tables and check cards. +static func modifier(src: String, ctx: RollContext) -> Dictionary: + if src.strip_edges() == "": + return {"value": 0, "error": ""} + var m := Expr.evaluate(src, ctx) + if m["error"] != "": + return {"value": 0, "error": m["error"]} + if not Expr.is_number(m["value"]): + return {"value": 0, "error": "gave \"%s\", not a number" % Expr.format_value(m["value"])} + return {"value": Expr.as_int(m, 0), "error": ""} + + +## The modifier's value right now, for showing chances outside a roll: +## {"known": bool, "value": int}. Card inputs read as their defaults. It's +## unknown when it rolls dice, reads a roll value that isn't set, or fails. +static func live_mod(t: RollTable, ctx: RollContext) -> Dictionary: + var src := t.dice_mod.strip_edges() + if src == "": + return {"known": true, "value": 0} + for inp: Dictionary in t.inputs: + var nm := str(inp.get("name", "")) + if nm != "" and ctx.get_value(nm) == null: + var dv := modifier(str(inp.get("default", "")), ctx) + ctx.save(nm, dv["value"]) + for nm: String in Expr.names_in(src): + if not nm.begins_with("@") and ctx.get_value(nm) == null: + return {"known": false, "value": 0} + var was: Variant = ctx.faces + ctx.faces = [] + var r := modifier(src, ctx) + var rolled := not (ctx.faces as Array).is_empty() + ctx.faces = was + if r["error"] != "" or rolled: + return {"known": false, "value": 0} + return {"known": true, "value": r["value"]} + + +## Rolls the dice and adds the modifier. Returns {"value": int, "error": +## String}; dice faces go to ctx.faces when it's collecting them. +static func roll_value(t: RollTable, ctx: RollContext) -> Dictionary: + var total := 0 + if not t.is_expr_dice(): + var d := t.dice_obj() + if ctx.faces != null: + total = d.bonus + for k in d.count: + var face := ctx.rng.randi_range(1, d.sides) + (ctx.faces as Array).append(face) + total += face + if not d.valid: + total = 0 + else: + total = d.roll(ctx.rng) + else: + var r := Expr.evaluate(t.dice, ctx) + if r["error"] != "": + return {"value": 0, "error": r["error"]} + total = Expr.as_int(r, 0) + var m := modifier(t.dice_mod, ctx) + if m["error"] != "": + return {"value": 0, "error": "the modifier %s %s" % [t.dice_mod.strip_edges(), m["error"]]} + return {"value": total + int(m["value"]), "error": ""} + + +## The result index for a rolled total: past the ends counts as the end +## result on a table that clamps; otherwise -1 when no range holds it. +static func index_for(t: RollTable, value: int) -> int: + if clamps(t): + var s := span(t) + value = clampi(value, s.x, s.y) + for i in t.entries.size(): + var e := t.entries[i] + if e.has_range and value >= e.range_lo and value <= e.range_hi: + return i + return -1 + + +# ---------- Problems ---------- + +## Gaps, overlaps and (on a table that doesn't clamp) results the dice can't +## reach, or "" when clean. +static func problems(t: RollTable) -> String: + if not t.is_ranged(): + return "" + var lo := min_value(t) + var hi := max_value(t) + if clamps(t): + var s := span(t) + lo = s.x + hi = s.y + if hi - lo > 100000: + return "The ranges span too many values to check." + var hits := PackedInt32Array() + hits.resize(maxi(0, hi - lo + 1)) + var outside := PackedStringArray() + for e in t.entries: + if not e.has_range: + continue + for v in range(maxi(lo, e.range_lo), mini(hi, e.range_hi) + 1): + hits[v - lo] += 1 + if e.range_lo < lo or e.range_hi > hi: + outside.append("%s–%s" % [fmt(t, e.range_lo), fmt(t, e.range_hi)]) + var gaps := _runs(t, hits, lo, hi, func(h: int) -> bool: return h == 0) + var overlaps := _runs(t, hits, lo, hi, func(h: int) -> bool: return h > 1) + var parts := PackedStringArray() + if gaps != "": + parts.append("No result for %s." % gaps) + if overlaps != "": + parts.append("%s matches more than one result." % overlaps) + if not outside.is_empty(): + parts.append("%s is outside %s–%s. Give the roll a modifier to reach it." % [", ".join(outside), fmt(t, lo), fmt(t, hi)]) + return " ".join(parts) + + +static func _runs(t: RollTable, hits: PackedInt32Array, lo: int, n: int, test: Callable) -> String: + var out := PackedStringArray() + var start := -1 + for v in range(lo, n + 2): + var on: bool = v <= n and test.call(hits[v - lo]) + if on and start < 0: + start = v + elif not on and start >= 0: + out.append(fmt(t, start) if start == v - 1 else "%s–%s" % [fmt(t, start), fmt(t, v - 1)]) + start = -1 + return ", ".join(out) diff --git a/core/roll_range.gd.uid b/core/roll_range.gd.uid new file mode 100644 index 0000000..7a9f9c2 --- /dev/null +++ b/core/roll_range.gd.uid @@ -0,0 +1 @@ +uid://c2o57l6vdqpob diff --git a/core/roll_table.gd b/core/roll_table.gd index df67e3e..78ef5f9 100644 --- a/core/roll_table.gd +++ b/core/roll_table.gd @@ -11,10 +11,12 @@ extends RefCounted ## (a router's cases are its entries, each with an entry-level `when`). Use create() ## for a well-formed card of each kind. ## -## Ranged tables also accept a full expression in `dice` ("2d6 + dm(@end)", -## "@terms"). Anything that isn't plain dice is evaluated with Expr; values -## past the lowest or highest range clamp to that range, and chances aren't -## known (chance() is 0, has_chances() false). +## Ranged tables may add a modifier to the roll (`dice_mod`, e.g. "@luck"), +## and also accept a full expression in `dice` ("2d6 + dm(@end)", "@terms"). +## With either, a total past the lowest or highest range counts as that end +## result. Chances are known for a modifier (given its value) but not for an +## expression (chance() is 0, has_chances() false). The numbers live in +## RollRange. const DEFAULT_DICE := "1d100" @@ -50,6 +52,9 @@ var tags: Array[String] = [] ## Dice expression for ranged tables, e.g. "1d100", "2d6", "1d8+2", or any ## expression such as "2d6 + dm(@end)". 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 = "" ## 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". @@ -286,22 +291,24 @@ func dice_obj() -> Dice: return _dice_cache -## Rolls the ranged table's dice. Returns {"value": int, "error": String}. +## The roll modifier, if any (see RollRange): true when dice_mod is set. +func has_mod() -> bool: + return dice_mod.strip_edges() != "" + + +## The whole roll as text: "1d20 + @luck", or the dice alone. +func roll_text() -> String: + return RollRange.join(dice, dice_mod) + + +## True when totals past the ends count as the end results (RollRange.clamps). +func clamps() -> bool: + return RollRange.clamps(self) + + +## Rolls the dice and adds the modifier. Returns {"value": int, "error": String}. func roll_value(ctx: RollContext) -> Dictionary: - if not is_expr_dice(): - if ctx.faces != null: - var d := dice_obj() - var total := d.bonus - for k in d.count: - var face := ctx.rng.randi_range(1, d.sides) - (ctx.faces as Array).append(face) - total += face - return {"value": total if d.valid else 0, "error": ""} - return {"value": dice_obj().roll(ctx.rng), "error": ""} - var r := Expr.evaluate(dice, ctx) - if r["error"] != "": - return {"value": 0, "error": r["error"]} - return {"value": Expr.as_int(r, 0), "error": ""} + return RollRange.roll_value(self, ctx) ## Label for the dice: "d100", "2d6", "1d8+2". Plain tables label by entry @@ -314,42 +321,14 @@ func dice_label() -> String: return "d%d" % die_size() -## Lowest value that can be rolled (1 on plain tables). For expression dice, -## the lowest range start. +## Lowest value that can be shown or rolled (RollRange.min_value). func min_value() -> int: - if not is_ranged(): - return 1 - if is_expr_dice(): - return _range_span().x - return dice_obj().min_value() + return RollRange.min_value(self) -## Highest value that can be rolled. Plain tables: the entry count. For -## expression dice, the highest range end. +## Highest value (RollRange.max_value). Plain tables: the entry count. func die_size() -> int: - if is_ranged(): - if is_expr_dice(): - return _range_span().y - return dice_obj().max_value() - return entries.size() - - -## Vector2i(lowest range start, highest range end) over ranged entries. -func _range_span() -> Vector2i: - var lo := 0 - var hi := 0 - var first := true - for e in entries: - if not e.has_range: - continue - if first: - lo = e.range_lo - hi = e.range_hi - first = false - else: - lo = mini(lo, e.range_lo) - hi = maxi(hi, e.range_hi) - return Vector2i(lo, hi) + return RollRange.max_value(self) func total_weight() -> int: @@ -359,32 +338,12 @@ func total_weight() -> int: return w -## Formats a die value the way printed tables do: d100 values are two digits -## and 100 is written "00". func fmt(value: int) -> String: - var two_digit := (dice_obj().is_d100() and not is_expr_dice()) if is_ranged() else entries.size() == 100 - if two_digit: - return "00" if value == 100 else "%02d" % value - return str(value) + return RollRange.fmt(self, value) func num_label(e: TableEntry, index: int) -> String: - if not e.has_range: - return fmt(index + 1) - if is_expr_dice(): - var span := _range_span() - var ranged := 0 - for x in entries: - if x.has_range: - ranged += 1 - if ranged > 1: - if e.range_lo == span.x: - return "≤%s" % fmt(e.range_hi) - if e.range_hi == span.y: - return "%s+" % fmt(e.range_lo) - if e.range_lo == e.range_hi: - return fmt(e.range_lo) - return "%s–%s" % [fmt(e.range_lo), fmt(e.range_hi)] + return RollRange.num_label(self, e, index) ## False when chances can't be known (expression dice). @@ -392,24 +351,17 @@ func has_chances() -> bool: return not is_expr_dice() -## Chance (0–1) that a roll lands on this entry. 0 for expression dice, whose -## chances can't be known (see has_chances()). -func chance(e: TableEntry) -> float: - if is_ranged(): - if not e.has_range or is_expr_dice(): - return 0.0 - return dice_obj().probability_between(e.range_lo, e.range_hi) - var total := total_weight() - return float(maxi(0, e.weight)) / float(total) if total > 0 else 0.0 +## Chance (0–1) that a roll lands on this entry, with the modifier at `mod`. +func chance(e: TableEntry, mod: int = 0) -> float: + return RollRange.chance(self, e, mod) ## True when the entry can come up at all. func can_come_up(e: TableEntry) -> bool: - if is_ranged(): - return e.has_range and (is_expr_dice() or chance(e) > 0.0) - return e.weight > 0 + return RollRange.can_come_up(self, e) +## The entry whose range holds `value` exactly, or -1. func entry_index_for(value: int) -> int: for i in entries.size(): var e := entries[i] @@ -418,11 +370,10 @@ func entry_index_for(value: int) -> int: return -1 -## Like entry_index_for(), but a value below the lowest range or above the -## highest one lands on that end range (expression dice). +## The entry a rolled total picks: past the ends counts as the end result on +## a table that clamps (RollRange.index_for). func entry_index_clamped(value: int) -> int: - var span := _range_span() - return entry_index_for(clampi(value, span.x, span.y)) + return RollRange.index_for(self, value) func find_entry(eid: String) -> TableEntry: @@ -432,50 +383,9 @@ func find_entry(eid: String) -> TableEntry: return null -## Describes gaps, overlaps and out-of-span ranges in a ranged table, or "" when clean. -## Expression dice have no fixed span, so only gaps between ranges and -## overlaps are reported. +## Gaps, overlaps and out-of-reach ranges, or "" when clean (RollRange.problems). func range_problems() -> String: - if not is_ranged(): - return "" - var lo := min_value() - var hi := die_size() - if hi - lo > 100000: - return "The ranges span too many values to check." - var hits := PackedInt32Array() - hits.resize(maxi(0, hi - lo + 1)) - var outside := PackedStringArray() - for e in entries: - if not e.has_range: - continue - for v in range(maxi(lo, e.range_lo), mini(hi, e.range_hi) + 1): - hits[v - lo] += 1 - if e.range_lo < lo or e.range_hi > hi: - outside.append("%s–%s" % [fmt(e.range_lo), fmt(e.range_hi)]) - var gaps := _runs(hits, lo, hi, func(h: int) -> bool: return h == 0) - var overlaps := _runs(hits, lo, hi, func(h: int) -> bool: return h > 1) - var parts := PackedStringArray() - if gaps != "": - parts.append("No result for %s." % gaps) - if overlaps != "": - parts.append("%s matches more than one result." % overlaps) - if not outside.is_empty(): - parts.append("%s is outside %s–%s." % [", ".join(outside), fmt(lo), fmt(hi)]) - return " ".join(parts) - - -func _runs(hits: PackedInt32Array, lo: int, n: int, test: Callable) -> String: - var out := PackedStringArray() - var start := -1 - for v in range(lo, n + 2): - var on: bool = v <= n and test.call(hits[v - lo]) - if on and start < 0: - start = v - elif not on and start >= 0: - out.append(fmt(start) if start == v - 1 else "%s–%s" % [fmt(start), fmt(v - 1)]) - start = -1 - return ", ".join(out) - + return RollRange.problems(self) ## A variable card's starting value: {"value", "error"}. An empty `initial` ## gives 0 for numbers and "" otherwise. For text and list variables, plain @@ -513,6 +423,8 @@ func to_dict() -> Dictionary: d["tags"] = tags.duplicate() if is_ranged(): d["dice"] = dice + if has_mod(): + d["dice_mod"] = dice_mod.strip_edges() if card_mode: d["card_mode"] = true if deck_empty != "reshuffle": @@ -577,6 +489,7 @@ static func from_dict(d: Dictionary) -> RollTable: t.dice = str(d["dice"]) elif int(d.get("die", 0)) > 1: t.dice = "1d%d" % int(d["die"]) + t.dice_mod = expr_text(d.get("dice_mod", ""), "").strip_edges() t.card_mode = bool(d.get("card_mode", false)) t.deck_empty = "stop" if str(d.get("deck_empty", "reshuffle")) == "stop" else "reshuffle" var k := str(d.get("kind", KIND_ROLL)) diff --git a/core/roll_tree.gd b/core/roll_tree.gd index b5b718b..ffb6bf8 100644 --- a/core/roll_tree.gd +++ b/core/roll_tree.gd @@ -18,7 +18,7 @@ static func step_of(n: Dictionary, depth: int = 0) -> Dictionary: "table_id": t.id, "num": t.fmt(n["value"]) if n.has("value") else "", "die": t.die_size(), - "dice": t.dice_label(), + "dice": t.roll_text() if t.has_mod() else t.dice_label(), "text": str(n.get("summary", n.get("stop", ""))), "depth": depth, } diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 49b83cc..e983b69 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1,6 +1,6 @@ # TableTower — Design and Status -**Engine:** Godot 4.7.2 (GDScript) · **Started:** 2026-11-08 · **Last updated:** 2026-11-09 (file splits, duplicate-code and terminology passes; see §10) +**Engine:** Godot 4.7.2 (GDScript) · **Started:** 2026-11-08 · **Last updated:** 2026-11-09 (roll modifiers, resizable tray and inspector; see §10) This is the starting point for anyone picking the project up, including a new Claude session. It records what TableTower is, how it's built, how to work on it, where things @@ -21,6 +21,9 @@ stand, and what's next. - **Needed from the user:** that exact username, plus an API token (repository read/write and user read, passed as `FORGEJO_TOKEN`), or they do it in the web UI themselves. - Don't go looking for stored credentials. +- **Hands-on playtest of roll modifiers and the resizable panels** (branch `roll-modifier`): + build a 1d20 + Luck table from −3 to 24 in the inspector, watch the chances move as Luck changes, + drag the tray and inspector edges. Only headless tests and screenshots have checked them. - **Hands-on playtest** of the split/renamed build. The user had a first look after the file splits ("looking fine so far"), but the terminology pass hasn't been tried by hand. - **Stale worktree.** `.claude/worktrees/agent-aa27e470dd86ce971` (branch `split-table-card`) @@ -58,12 +61,18 @@ character, can run as one chain. - **Play / Build modes.** Collapse a card or **Collapse all**. Pan, zoom (8%–150%), **Fit** and a minimap (**Map**). - **Table types.** Weighted plain tables, ranged dice tables (`1d100`, `2d6`, any expression such as `2d6 + dm(@str)`), and card mode (a deck with no repeats, with Reshuffle). +- **Roll modifiers** (`dice_mod`, LOGIC.md §3c). A ranged table adds a modifier such as `@luck` to + its dice. Ranges may run past the dice (−3 to 24 on a d20); totals past the ends use the end + result. The card shows chances for the modifier's value now, and Why says "+3 for Luck". - **Pipe options.** A count (a number or an expression), "save as", **Only if** conditions, and **Otherwise**. A result's conditions and counts are evaluated once, as a snapshot, before any pipe runs. - **Text in results.** `[[Table]]` inline references, `{@var}` / `{hero}` values, and BBCode formatting. - **The result tray** shows the chain as chips with effect lines, a sheet headline, Earlier rolls, a Variables tab, Copy (text, BBCode, with details) and **Why this?** on each step. +- **Resizable panels.** Drag the tray's top edge or the inspector's left edge (double-click for the + default). The sizes are kept in local settings (`tray_height`, `inspector_width`). Every part of + the tray scrolls inside it. **Logic cards** (`docs/LOGIC.md`) - **Choice:** "Which option" (pick, with Random), "How many" (a number) or "Open @@ -81,6 +90,7 @@ character, can run as one chain. **Building** (Build mode) - **The inspector,** docked right. It edits the selected card, result or pipe: - effects as rows ("[Subtract] [1] from [Luck]") + - a roll or check modifier as "[Add ▾] [Luck ▾]" (ModifierEditor) - conditions as rows ("[Luck] [is at least] [2]", with and/or) - pipe inputs, Otherwise, count and saves-as - kind-specific card fields @@ -109,6 +119,8 @@ character, can run as one chain. core/ engine, no UI, testable headless tower_board.gd a collection (tables, groups), JSON, format v2 + migration roll_table.gd a card: kind, dice, entries, logic fields, factories (RollTable.create) + roll_range.gd a ranged card's numbers: span, natural range, labels, chances, the roll + modifier (shared with check cards), range problems table_entry.gd a result: text, weight, range, effects, pipes (+count/save/when/otherwise/with), show_if, when roller.gd coroutine roller with an explicit stack (_chain loop, roll/pipe steps, apply_starting_values) plus delegators to its parts: @@ -137,12 +149,14 @@ ui/ main.gd: the app shell (shared fields, _ready, cards, collapse, inpu table_card.gd + table_card_{header,rows,editing,value,text}.gd result_tray.gd + tray_chips, tray_text, earlier_rolls table_settings_dialog.gd + table_settings_rules (validation/apply), settings_kind_fields + inspector_card (card fields) + inspector_roll (roll dice and modifier); + modifier_editor (the plain modifier builder); panel_splitter (drag handles) and: board_view, card_layer, pipe_layer, port_layer, group_layer, group_card, minimap, why_popover, choice_dialog, table_preview, details_popup, inspector*, value_picker, rules_view, search_panel, board_search, board_layout, edit_history, test_board_dialog, template_*, io_menu, collection_switcher, variables_panel, modal_card, rich_text, style tools/ simulate_board.gd (headless simulator CLI), test_window.sh (background test windows) -tests/ test_*.gd: 25 headless suites +tests/ test_*.gd: 26 headless suites templates/ built-in templates · examples/logic_demo.json (original demo board) · assets/fonts (OFL) ``` @@ -157,8 +171,8 @@ templates/ built-in templates · examples/logic_demo.json (original demo board) `Style.field_colors`, `TableCard.vbox/hbox`, `InspectorKit.*` (fields, `focused_tag`/`refocus`, `as_text_link`), `Main.file_dialog`/`export_dialog`, `JsonIO.entry_line`/`finish_import`. - **Keep files small.** Aim for under ~400 lines; split by area into helper objects as above. - Next candidates, all 540–700 lines: - - core: describe, roll_table, expr + Next candidates, all 530–730 lines: + - core: describe (731, the largest now), roll_table, expr - ui: choice_dialog, inspector_card, inspector, main, edit_history - io: json_io @@ -223,6 +237,14 @@ templates/ built-in templates · examples/logic_demo.json (original demo board) - Collapse/expand isn't undoable. Collection members aren't undoable. - Rules are stored as text, and the plain layer sits on top of it, so old boards open unchanged. - Traveller-derived content stays out of the repo (§8). +- **Roll modifiers (2026-11-09).** A separate `dice_mod` field, not just an expression in `dice`, + so the card knows its dice: it can show chances, the natural range and plain words. Totals past + the ends always use the end result; there's no separate "nothing happens" setting, because an end + result that says so does the same job. The Check card's modifier picker became the shared + ModifierEditor, which also adds a value as it is (`@luck`) and doesn't only use `dm()`. +- **Panel resizing** uses a small drag handle (`PanelSplitter`) rather than Godot's + `SplitContainer`. The tray used to size itself to its content and the inspector collapses to a + strip, and a handle that sets the panel's size fits both without changing the layout. - **Terminology (2026-11-09).** UI text uses these words; code and JSON keys keep their old names. - **Card:** anything on the felt. "Roll table" means only the `roll` kind. - **Result**, never "entry" or "row" (code: `TableEntry`, `entries`). @@ -250,6 +272,8 @@ templates/ built-in templates · examples/logic_demo.json (original demo board) Pipes into a collapsed group can't be clicked. - Groups aren't kept in the Canvas and GraphML exports. Logic keys survive only in TableTower JSON. - `{= }` dice in live sheet and variable displays re-roll when the display refreshes. +- The simulator and Test board list results that only a modifier reaches as "never chosen" when + the modifier stays small in the runs (the demo's luck-only vault, for example). - **Not yet looked into: Coderstanding warnings.** - Signals emitted but never connected: `ModalCard.closed`, `SearchPanel.closed`. - A possible wrong handler in `ModalCard.segmented` (`pressed` → `on_change`; probably a @@ -346,3 +370,11 @@ templates/ built-in templates · examples/logic_demo.json (original demo board) - The built-in skill check is now a real Check card (`builtin:skill-check`). - "result" and "change" replace "entry", "row" and "effect" in UI text. - Pipes are deleted, not removed; `reset` reads "Reset". + +**2026-11-09: roll modifiers and resizable panels** (branch `roll-modifier`) +11. Roll modifiers: `dice_mod` on ranged roll tables, results past the dice, the end results + taking totals past the ends, live chances, plain wording and Why lines. The range and chance + code moved from roll_table.gd into `RollRange`. The shared ModifierEditor serves roll and check + cards. The demo's Room check uses 2d6 + Luck and has a vault only luck reaches. +12. Resizable tray (top edge) and inspector (left edge). The Earlier tab scrolls, and the tray no + longer grows with long Earlier rolls, sheets or chains. diff --git a/docs/LOGIC.md b/docs/LOGIC.md index 7d5ffe1..3816caf 100644 --- a/docs/LOGIC.md +++ b/docs/LOGIC.md @@ -223,6 +223,34 @@ the dice faces without any modifier (`2d6 + dm(@str)` and `2d6+3` both give the expression with no dice at all (`@terms`) leaves `nat` as it was. A pick card's Random never sets it. +### Roll modifiers (results past the dice) + +Many printed tables say "roll 1d20 and add your Luck", and list results the dice alone can't +reach (−3 to 24 on a d20). A ranged `roll` table models this with a **modifier** (`dice_mod`): + +- The card rolls `dice`, then adds the modifier, an expression such as `@luck`, `-@fatigue`, + `dm(@str)`, `2` or a card input (`bonus`). An empty modifier is none. +- **Ranges may go past the dice.** The dice alone give the *natural range* (1–20). Results outside + it (−3, 24) are only reached with a modifier; the card's number tooltip says so. +- **Totals past the ends use the nearest result.** A total below the lowest range or above the + highest one counts as that end result, and the card labels the ends `≤-3` and `24+`. For a + "nothing happens" past the ends, give the end results that text. +- **Chances follow the modifier's value now.** The card shows each result's chance with the + modifier as it is now (board values, and card inputs at their defaults), and updates after every + roll. A modifier that rolls dice or reads an unset roll value shows no chances. Hover previews, + which don't know the values, show none either. +- `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. +- 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. + +The inspector builds a modifier in plain words: **No modifier**, **Add** [value ▾], +**Subtract** [value ▾], **Add the modifier of** [value ▾] (`dm()`), **Add the number** [n] or +**Custom…** (any expression). Check cards use the same builder for `check_mod`. + ## 3d. Card inputs (pipe parameters) Any card (not a variable card) may declare `inputs: [{name, label, default}]`, and a pipe object @@ -278,8 +306,9 @@ evaluated with Godot's `Expression`, after a small rewrite. either are rolled. The inline `a if c else b` form is refused, because Godot's Expression returns the wrong branch for it. -Ranged `roll` tables keep plain dice (`2d6`) and also accept any expression, such as -`2d6 + dm(@end)` or `@terms`. Values beyond the lowest or highest range clamp to that range, +Ranged `roll` tables keep plain dice (`2d6`), may add a modifier (§3c, "Roll modifiers"), and +also accept any expression, such as `2d6 + dm(@end)` or `@terms`. Values beyond the lowest or +highest range clamp to that range, so a check table only needs "2–6 fail" and "7–12 pass". The card labels the ends `≤6` and `7+` when the expression has modifiers. @@ -382,6 +411,7 @@ Table keys: - `options_from`, `options_where` (pick choices with options from variables, §2a) - `loop`, `loop_expr` (loop cards) - `var_name`, `var_type` (`number`, `text`, `list` or `collection`), `initial` (variable cards) +- `dice_mod` (ranged roll tables: the roll modifier, an expression; left out when empty) - `check_dice`, `check_mod`, `check_cmp` (`ge` or `le`), `check_target` (check cards; Strings, left out at their defaults `2d6`, `""`, `ge`, `8`) - `inputs`: `[{"name": "tier", "label": "Tier", "default": "1"}]` (any card; `label` and @@ -406,7 +436,7 @@ so history keeps them. The key is left out when a node has no facts. Each fact h | `type` | On | Keys | |---|---|---| | `input` | the card's node, first | `name`, `value`, `from` (`"pipe"` or `"default"`) | -| `roll` | rolled nodes (roll tables, a pick's plain Random) | `pick` (`"dice"`, `"weighted"`, `"card"`), `dice`, `total`; dice rolls also `faces` (Array), and when there were dice `nat` and `mod` | +| `roll` | rolled nodes (roll tables, a pick's plain Random) | `pick` (`"dice"`, `"weighted"`, `"card"`), `dice`, `total`; dice rolls also `faces` (Array), and when there were dice `nat` and `mod`; `mod_expr` (the modifier, when it's all of `mod`) and `counts_as` (the end value a total past the ends counts as) | | `check` | check nodes | `dice`, `mod_expr`, `target_expr`, `faces`, `nat`, `mod`, `total`, `target`, `cmp`, `success` | | `case` | router nodes, one per case tried | `index`, `expr` (`""` for Otherwise), `values`, `result`, `error`? | | `show_if` | pick nodes when options were hidden | `hidden` (fixed options hidden), `chosen_hidden` | diff --git a/docs/PLAIN.md b/docs/PLAIN.md index a8eae06..d88b056 100644 --- a/docs/PLAIN.md +++ b/docs/PLAIN.md @@ -22,6 +22,7 @@ Pure functions that turn stored rules into short phrases. They use value labels | `options(table, board) -> String` | dynamic pick source | "your Skills, level 1 or more" | | `pipe(entry, target_id, board) -> String` | a pipe's label | "Tier 3 · only if Luck is 2 or more", "otherwise", "×2 · saves Weapon" | | `check(table, board) -> String` | a Check card | "Roll 2d6 + Strength modifier, need 8 or more" | +| `roll(table, board) -> String` | a ranged roll table | `1d20` with modifier `@luck` → "Roll d20 + Luck"; `-@fatigue` → "Roll d20 − Fatigue" | | `why(fact, board, plain := true) -> String` | one trace fact (§5) | "Skipped Tier 3 because Luck was 1 (needs 2 or more)" | Comparisons read as "is", "is not", "is at least", "is at most", "is more than" and "is less @@ -131,7 +132,8 @@ details. Where it settles something the spec left open, or differs: `[op] [amount] [to/from] [value ▾]`). - **Then go to:** one box per pipe with inputs, **Only if** (condition builder rows of `[value ▾] [comparison ▾] [amount]`, plus and/or), **Otherwise**, count and save as. - - **Cards:** kind-specific fields (check dice, modifier picker and target; collection members; + - **Cards:** kind-specific fields (a roll table's dice and modifier, with a live "Roll d20 + + Luck" sentence; check dice, modifier and target; collection members; declared inputs; options source as "from [collection ▾] where [condition]"; and so on). - A value picker lists `known_values` with search and "+ New value…". - "Edit as text" on any builder switches it to the text field, and back when it parses. diff --git a/examples/logic_demo.json b/examples/logic_demo.json index 9dc4914..84ebaca 100644 --- a/examples/logic_demo.json +++ b/examples/logic_demo.json @@ -106,12 +106,14 @@ "name": "Room check", "x": 1000, "y": 40, - "dice": "2d6 + @luck", - "details": "2d6 plus Luck. Low rolls hurt, high rolls pay.", + "dice": "2d6", + "dice_mod": "@luck", + "details": "2d6 plus Luck. Low rolls hurt, high rolls pay, and only luck finds the vault.", "entries": [ { "id": "e1", "text": "A trap snaps shut", "effects": "@hp -= 2", "range": [2, 6] }, { "id": "e2", "text": "Dust and echoes", "range": [7, 9] }, - { "id": "e3", "text": "A glinting cache", "effects": "@gold += 2d6\n@loot += if(1d6 <= 3, \"gem\", if(1d6 <= 3, \"silver idol\", \"old map\"))", "range": [10, 12] } + { "id": "e3", "text": "A glinting cache", "effects": "@gold += 2d6\n@loot += if(1d6 <= 3, \"gem\", if(1d6 <= 3, \"silver idol\", \"old map\"))", "range": [10, 12] }, + { "id": "e4", "text": "A hidden vault, found by luck", "effects": "@gold += 3d6", "range": [13, 13] } ] }, { diff --git a/io/json_io.gd b/io/json_io.gd index 2107969..20d3ecd 100644 --- a/io/json_io.gd +++ b/io/json_io.gd @@ -7,7 +7,7 @@ extends RefCounted ## Canonical collection form: ## {"format_version": 2, "id", "name", "tables": [table, ...], ["groups": [group, ...]]} ## group: id, name, x, y, w, h, [collapsed], [details], members (table ids) -## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode], +## table: id, name, x, y, [collapsed], [details], [tags], [dice], [dice_mod], [card_mode], ## [deck_empty], [kind], [choice], [prompt], [save_as], [options_from], ## [options_where], [min], [max], ## [loop], [loop_expr], [var_name], [var_type], [initial], @@ -325,7 +325,7 @@ static func _canon_table(td: Dictionary) -> Dictionary: var kind := str(td.get("kind", "roll")) if RollTable.KINDS.has(kind) and kind != "roll": t["kind"] = kind - var defaults := {"choice": "pick", "prompt": "", "save_as": "", "options_from": "", "options_where": "", "min": "0", "max": "99", + var defaults := {"dice_mod": "", "choice": "pick", "prompt": "", "save_as": "", "options_from": "", "options_where": "", "min": "0", "max": "99", "loop": "times", "loop_expr": "", "var_name": "", "var_type": "number", "initial": "", "check_dice": RollTable.CHECK_DEFAULT_DICE, "check_mod": "", "check_cmp": "ge", "check_target": RollTable.CHECK_DEFAULT_TARGET} for key: String in defaults: diff --git a/tests/test_inspector.gd b/tests/test_inspector.gd index 36459e4..96a9c0b 100644 --- a/tests/test_inspector.gd +++ b/tests/test_inspector.gd @@ -336,23 +336,22 @@ func _test_check() -> void: _eq(t.check_dice, "3d6", "dice") InspectorCard.set_check(insp, "check_dice", "") _eq(t.check_dice, "3d6", "empty dice aren't written") - _eq(InspectorCard.modifier_value("dm(@str)"), "@str", "dm(@str) reads as Strength in the picker") - _eq(InspectorCard.modifier_value(""), InspectorCard.NONE, "empty is none") - _eq(InspectorCard.modifier_value("@str + 1"), InspectorCard.AS_TEXT, "anything else is text") - var picker: ValuePicker = insp.fields["check_mod_picker"] - _eq(picker.value, "@str", "the picker shows the modifier's value") - picker.choose("@luck") + var mod: ModifierEditor = insp.fields["check_mod"] + _eq(mod.way, ModifierEditor.Way.DM, "dm(@str) opens as a value's modifier") + _eq(mod.picker.value, "@str", "the picker shows the modifier's value") + mod.picker.choose("@luck") _eq(t.check_mod, "dm(@luck)", "picking Luck writes dm(@luck)") - InspectorCard.choose_modifier(insp, InspectorCard.NONE) - _eq(t.check_mod, "", "none clears it") - InspectorCard.choose_modifier(insp, InspectorCard.AS_TEXT) - var le: LineEdit = insp.fields.get("check_mod") - _check(le != null, "Edit as text shows the modifier as a field") - le.text = "@str - 1" - le.text_changed.emit("@str - 1") + mod.set_way(ModifierEditor.Way.ADD) + _eq(t.check_mod, "@luck", "Add keeps the value: @luck") + mod.set_way(ModifierEditor.Way.NONE) + _eq(t.check_mod, "", "No modifier clears it") + mod.set_way(ModifierEditor.Way.CUSTOM) + _check(mod.field != null, "Custom shows the modifier as a field") + mod.field.text = "@str - 1" + mod.field.text_changed.emit("@str - 1") _eq(t.check_mod, "@str - 1", "typed text is written") insp.rebuild() - _check(insp.fields.has("check_mod"), "a modifier the picker can't show stays text") + _eq((insp.fields["check_mod"] as ModifierEditor).way, ModifierEditor.Way.CUSTOM, "a modifier the plain forms can't show stays Custom") InspectorCard.set_check(insp, "check_mod", "dm(@str)") InspectorCard.set_check(insp, "check_cmp", "ge") InspectorCard.set_check(insp, "check_target", "8") diff --git a/tests/test_logic_ui.gd b/tests/test_logic_ui.gd index 0c60c6d..4662d9b 100644 --- a/tests/test_logic_ui.gd +++ b/tests/test_logic_ui.gd @@ -94,18 +94,19 @@ func _test_demo_file() -> void: for k in ["roll", "choice/pick", "choice/number", "choice/text", "loop", "variable", "sheet"]: _check(kinds.has(k), "the demo has a %s card" % k) var check := b.get_table("room_check") - _check(check != null and check.is_expr_dice(), "the demo has an expression check table") + _check(check != null and check.dice == "2d6" and check.dice_mod == "@luck", "the demo's room check rolls 2d6 with Luck as its modifier") + _check(check.clamps() and not RollRange.natural_reach(check, check.entries[3]), "its vault result is only reached with luck") _check(not b.to_json().to_lower().contains("traveller"), "the demo is original") func _test_cards() -> void: var check := main.card_for("room_check") - _check(check != null and check.rows.size() == 3, "the check table shows its three ranges") + _check(check != null and check.rows.size() == 4, "the check table shows its four ranges") var nums: Array = [] for eid: String in check.rows_ui.parts: var num: Label = check.rows_ui.parts[eid]["num"] nums.append(num.text if num else "") - _eq(nums, ["≤6", "7–9", "10+"], "expression dice label the ends ≤N and N+") + _eq(nums, ["≤6", "7–9", "10–12", "13+"], "a table with a modifier labels the ends ≤N and N+") var loop := main.card_for("explore") _check(loop.rows.size() == 2 and loop.anchor_for("e1").size() > 0 and loop.anchor_for("e2").size() > 0, "a loop card has Each time and Afterwards rows with outlets") diff --git a/tests/test_modifier.gd b/tests/test_modifier.gd new file mode 100644 index 0000000..c39922a --- /dev/null +++ b/tests/test_modifier.gd @@ -0,0 +1,193 @@ +extends SceneTree +## Headless checks for the roll modifier on ranged roll tables (dice_mod, +## RollRange): results past the dice, using the nearest result past the ends, +## chances with a modifier, the file format, plain words and the Why line, +## and the ModifierEditor's plain forms. +## Run: godot --headless --path . -s res://tests/test_modifier.gd + +var _failures := 0 + + +func _init() -> void: + _test_model() + _test_chances() + _test_rolls() + _test_live_mod() + _test_words() + _test_problems() + _test_editor_forms() + print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures]) + quit(1 if _failures else 0) + + +func _eq(got: Variant, want: Variant, what: String) -> void: + if typeof(got) != typeof(want) or got != want: + _failures += 1 + print(" ✗ %s: got %s, want %s" % [what, JSON.stringify(got), JSON.stringify(want)]) + + +func _check(ok: bool, what: String) -> void: + if not ok: + _failures += 1 + print(" ✗ ", what) + + +## A 1d20 + @luck event table with results from -3 to 24: +## -3 Disaster · -2–5 Bad · 6–15 Quiet · 16–23 Good · 24 Windfall. +func _events(mod: String = "@luck") -> RollTable: + var t := RollTable.new("events", "Events") + t.dice = "1d20" + t.dice_mod = mod + for r: Array in [["Disaster", -3, -3], ["Bad", -2, 5], ["Quiet", 6, 15], ["Good", 16, 23], ["Windfall", 24, 24]]: + 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 _board(t: RollTable) -> TowerBoard: + var b := TowerBoard.new() + b.id = "modifier" + b.tables.append(t) + var luck := RollTable.create(RollTable.KIND_VARIABLE, "v_luck", "Luck") + luck.var_name = "luck" + b.tables.append(luck) + return b + + +func _luck(n: int) -> Dictionary: + return {"luck": {"value": n, "source": ""}} + + +func _test_model() -> void: + print("Model and file format") + var t := _events() + _check(t.has_mod() and t.clamps(), "a modifier makes the table use the nearest result past its ends") + _eq(t.roll_text(), "1d20 + @luck", "roll text") + _eq(RollRange.natural(t), Vector2i(1, 20), "the dice alone roll 1–20") + _eq(RollRange.span(t), Vector2i(-3, 24), "the ranges span -3–24") + _check(t.min_value() == -3 and t.die_size() == 24, "the card shows -3 to 24") + _eq(t.num_label(t.entries[0], 0), "≤-3", "the low end reads ≤-3") + _eq(t.num_label(t.entries[4], 4), "24+", "the high end reads 24+") + _eq(t.num_label(t.entries[2], 2), "6–15", "middle ranges read as written") + var back := RollTable.from_dict(t.to_dict()) + _eq(back.dice_mod, "@luck", "dice_mod survives a save") + _check(not RollTable.from_dict(_events("").to_dict()).has_mod(), "no modifier, no key") + _check(not _events("").to_dict().has("dice_mod"), "an empty modifier isn't written") + _eq(RollRange.join("2d6", "-1"), "2d6 - 1", "a negative modifier joins with minus") + _eq(RollRange.join("2d6", " "), "2d6", "a blank modifier is no modifier") + + +func _test_chances() -> void: + print("Chances") + var t := _events() + for mod in [0, 3, -5, 30]: + var sum := 0.0 + for e in t.entries: + sum += t.chance(e, mod) + _check(absf(sum - 1.0) < 1e-9, "chances add up to 1 with the modifier at %d" % mod) + _check(absf(t.chance(t.entries[2], 0) - 0.5) < 1e-9, "Quiet (6–15) is 10/20 with no modifier") + _eq(t.chance(t.entries[0], 0), 0.0, "Disaster can't come up with no modifier") + _check(absf(t.chance(t.entries[0], -5) - 0.1) < 1e-9, "-5: a 2 gives -3 and a 1 gives -4, which counts as -3") + _check(absf(t.chance(t.entries[4], 4) - 0.05) < 1e-9, "+4: a 20 gives 24") + _check(absf(t.chance(t.entries[4], 30) - 1.0) < 1e-9, "+30: every roll counts as 24") + _check(not RollRange.natural_reach(t, t.entries[0]) and RollRange.natural_reach(t, t.entries[1]), "only a modifier reaches -3") + _check(t.can_come_up(t.entries[0]), "-3 can still come up (with a modifier)") + + +func _test_rolls() -> void: + print("Rolling") + var t := _events() + var b := _board(t) + for seed_value in range(1, 40): + var rng := RandomNumberGenerator.new() + rng.seed = seed_value + var ctx := Roller.new_context(b, rng, _luck(3)) + var tree := Roller.roll(b, "events", ctx.rng, 0, {}, ctx) + var f: Dictionary = tree["why"][0] + _eq(int(f["total"]), int(f["nat"]) + 3, "total is the dice plus Luck (seed %d)" % seed_value) + _eq(int(f["mod"]), 3, "the fact's mod is Luck") + _eq(f["mod_expr"], "@luck", "the fact names the modifier") + _check(t.entries[tree["index"]].range_lo <= int(f["total"]) and int(f["total"]) <= t.entries[tree["index"]].range_hi, "the total picks its range") + # Luck +10 pushes a high roll past 24: it counts as 24. + var high := false + for seed_value in range(1, 80): + var rng := RandomNumberGenerator.new() + rng.seed = seed_value + var ctx := Roller.new_context(b, rng, _luck(10)) + var tree := Roller.roll(b, "events", ctx.rng, 0, {}, ctx) + var f: Dictionary = tree["why"][0] + if int(f["total"]) > 24: + high = true + _eq(int(f["counts_as"]), 24, "past the top counts as 24") + _eq(tree["index"], 4, "and takes Windfall") + _eq(ctx.get_value("nat"), f["nat"], "nat stays the dice alone") + break + _check(high, "some roll went past 24") + # A modifier that fails stops the card with a readable message. + t.dice_mod = "@luck +" + var ctx2 := Roller.new_context(b, RandomNumberGenerator.new(), _luck(1)) + var bad := Roller.roll(b, "events", ctx2.rng, 0, {}, ctx2) + _check(str(bad.get("stop", "")).begins_with("Can't roll 1d20 + @luck +: the modifier"), "a broken modifier stops the card and names it: %s" % str(bad.get("stop", ""))) + + +func _test_live_mod() -> void: + print("The modifier's value now") + var t := _events() + var b := _board(t) + var lm := RollRange.live_mod(t, Roller.live_context(b, _luck(2))) + _check(lm["known"] and lm["value"] == 2, "@luck reads as 2") + _eq(RollRange.live_mod(_events(""), Roller.live_context(b, {}))["value"], 0, "no modifier is 0") + _check(not RollRange.live_mod(_events("1d4"), Roller.live_context(b, {}))["known"], "dice in the modifier: unknown") + _check(not RollRange.live_mod(_events("tier"), Roller.live_context(b, {}))["known"], "an unset roll value: unknown") + var inp := _events("bonus") + inp.inputs = [{"name": "bonus", "label": "Bonus", "default": "3"}] + var il := RollRange.live_mod(inp, Roller.live_context(b, {})) + _check(il["known"] and il["value"] == 3, "a card input reads as its default") + + +func _test_words() -> void: + print("Plain words") + var t := _events() + var b := _board(t) + _eq(Describe.roll(t, b), "Roll d20 + Luck", "the roll in words") + _eq(Describe.roll(_events("-@luck"), b), "Roll d20 − Luck", "subtracting reads as minus") + _eq(RulesView.roll_line(t, b, false), "1d20 + @luck", "text view") + var f := {"type": "roll", "pick": "dice", "dice": "1d20 + @luck", "faces": [20], "nat": 20, "mod": 7, "total": 27, + "mod_expr": "@luck", "counts_as": 24} + _eq(Describe.why(f, b), "Rolled 20, +7 for Luck = 27, past the top of the table, so it counts as 24", "why, past the top") + f = {"type": "roll", "pick": "dice", "dice": "1d20 + @luck", "faces": [3], "nat": 3, "mod": -2, "total": 1, "mod_expr": "@luck"} + _eq(Describe.why(f, b), "Rolled 3, −2 for Luck = 1", "why, a negative modifier") + _check(Describe.why(f, b, false).begins_with("roll 1d20 + @luck: 3 -2 = 1"), "why in text view: %s" % Describe.why(f, b, false)) + + +func _test_problems() -> void: + print("Range problems") + _eq(_events().range_problems(), "", "a modifier table from -3 to 24 is clean") + var plain := _events("") + _check(plain.range_problems().contains("outside 1–20") and plain.range_problems().contains("modifier"), + "without a modifier, -3 and 24 are outside the dice: %s" % plain.range_problems()) + var gap := _events() + gap.entries[2].range_lo = 8 + _eq(gap.range_problems(), "No result for 6–7.", "a gap is still reported") + _check(TableSettingsRules.mod_error("@luck +") != "" and TableSettingsRules.mod_error("@luck") == "", "a broken modifier is refused") + var t := _events("") + var r := TableSettingsRules.apply_settings(t, {"ranged": true, "dice": "1d20", "dice_mod": "@luck"}) + _check(r["ok"] and t.dice_mod == "@luck", "settings apply the modifier") + r = TableSettingsRules.apply_settings(t, {"ranged": true, "dice": "1d20", "dice_mod": "@luck +"}) + _check(not r["ok"] and t.dice_mod == "@luck", "a broken modifier changes nothing") + + +func _test_editor_forms() -> void: + print("Modifier editor forms") + var W := ModifierEditor.Way + for c: Array in [["", W.NONE, ""], ["@luck", W.ADD, "@luck"], ["tier", W.ADD, "tier"], ["-@fatigue", W.SUBTRACT, "@fatigue"], + ["- @fatigue", W.SUBTRACT, "@fatigue"], ["dm(@str)", W.DM, "@str"], ["2", W.NUMBER, "2"], ["-1", W.NUMBER, "-1"], + ["@luck + 1", W.CUSTOM, "@luck + 1"], ["1d4", W.CUSTOM, "1d4"], ["max(@a, @b)", W.CUSTOM, "max(@a, @b)"]]: + var p := ModifierEditor.parse(c[0]) + _eq([p["way"], p["value"]], [c[1], c[2]], "parse %s" % c[0]) + _eq(ModifierEditor.compose(W.SUBTRACT, "@fatigue"), "-@fatigue", "compose subtract") + _eq(ModifierEditor.compose(W.DM, "@str"), "dm(@str)", "compose dm") + _eq(ModifierEditor.compose(W.ADD, ""), "", "no value yet, no text") diff --git a/tests/test_modifier.gd.uid b/tests/test_modifier.gd.uid new file mode 100644 index 0000000..cff6984 --- /dev/null +++ b/tests/test_modifier.gd.uid @@ -0,0 +1 @@ +uid://b8t3d5fox3j62 diff --git a/tests/test_navigation.gd b/tests/test_navigation.gd index 64db9ff..8321dc7 100644 --- a/tests/test_navigation.gd +++ b/tests/test_navigation.gd @@ -1,7 +1,8 @@ extends SceneTree ## Navigation on big boards: search (BoardSearch and the panel), focus_table, ## the minimap, Pack collapsed groups (and making room when a packed group -## expands), and lazily built cards for collapsed groups. +## expands), lazily built cards for collapsed groups, and the resizable tray +## and inspector. ## Run: godot --headless --path . -s res://tests/test_navigation.gd -- --sample var _failures := 0 @@ -34,6 +35,7 @@ func _init() -> void: await _load(_board_dict()) await _test_pack() await _test_zoom_range() + await _test_panels() print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures]) quit(1 if _failures else 0) @@ -339,3 +341,61 @@ func _check(ok: bool, what: String) -> void: if not ok: _failures += 1 print("FAIL ", what) + + +func _test_panels() -> void: + print("Resizable tray and inspector") + var foot: PanelSplitter = null + var side: PanelSplitter = null + for n in main.find_children("*", "PanelSplitter", true, false): + if (n as PanelSplitter).vertical: + foot = n + else: + side = n + _check(foot != null and side != null, "the tray and the inspector each have a drag handle") + if foot == null or side == null: + return + # Sixty long Earlier rows scroll inside the tray instead of growing it. + var steps: Array = [] + for k in 8: + steps.append({"text": "A long step with plenty of words in it, number %d" % k}) + main.history.clear() + for i in 60: + main.history.append({"root_name": "Start", "time": 0.0, "steps": steps}) + main.tray.set_side(ResultTray.Side.EARLIER) + main.tray.render() + await _frames() + _check(absf(main.tray.size.y - foot.size_px) < 2.0, "the tray keeps its height with 60 earlier rolls (%.0f vs %.0f)" % [main.tray.size.y, foot.size_px]) + _check(main.tray._earlier.scroll.get_v_scroll_bar().max_value > main.tray._earlier.scroll.size.y, "Earlier scrolls") + foot.set_size_px(400.0) + await _frames() + _check(absf(main.tray.size.y - 400.0) < 2.0, "dragging makes the tray 400 tall (%.0f)" % main.tray.size.y) + foot.set_size_px(10.0) + _eq(foot.size_px, ResultTray.MIN_HEIGHT, "the tray has a smallest height") + foot.set_size_px(5000.0) + _check(foot.size_px <= main.size.y * foot.max_share + 1.0, "the tray can't take the whole window") + foot.set_size_px(ResultTray.HEIGHT) + # The inspector's handle shows with it, and sizes it. + main.set_mode(Main.Mode.BUILD) + await _frames() + _check(side.visible, "the inspector's handle shows in Build mode") + side.set_size_px(500.0) + await _frames() + _check(absf(main.inspector.size.x - 500.0) < 2.0, "dragging makes the inspector 500 wide (%.0f)" % main.inspector.size.x) + main.inspector.set_collapsed(true) + _check(not side.visible, "a collapsed inspector has no handle") + main.inspector.set_collapsed(false) + _check(absf(main.inspector.custom_minimum_size.x - 500.0) < 1.0, "opening it again keeps its width") + side.set_size_px(Inspector.WIDTH) + main.set_mode(Main.Mode.PLAY) + _check(not side.visible, "no handle in Play mode") + main.history.clear() + + +func _eq(got: Variant, want: Variant, what: String) -> void: + _check(typeof(got) == typeof(want) and got == want, "%s: got %s, want %s" % [what, str(got), str(want)]) + + +func _frames(n: int = 4) -> void: + for i in n: + await process_frame diff --git a/ui/details_popup.gd b/ui/details_popup.gd index 7821fb1..1540660 100644 --- a/ui/details_popup.gd +++ b/ui/details_popup.gd @@ -304,8 +304,8 @@ func table_summary(t: RollTable) -> String: RollTable.KIND_ROUTER: return "Router · %d cases · the first true case is taken" % t.entries.size() var dl := t.dice_label() - if t.is_expr_dice() and RulesView.plain(main): - dl = Describe.dice(t.dice, main.data) + if t.clamps(): + dl = RulesView.roll_line(t, main.data, RulesView.plain(main)) var parts := PackedStringArray([dl]) parts.append("%d %s" % [t.entries.size(), "ranges" if t.is_ranged() else "results"]) if t.card_mode: diff --git a/ui/earlier_rolls.gd b/ui/earlier_rolls.gd index 9e2214d..0777caa 100644 --- a/ui/earlier_rolls.gd +++ b/ui/earlier_rolls.gd @@ -1,9 +1,10 @@ class_name EarlierRolls extends VBoxContainer ## ResultTray's Earlier tab: one row per past roll, newest first, as -## "12:04 Root: a → b → c". +## "12:04 Root: a → b → c". The rows scroll inside the tray. var main: Main +var scroll: ScrollContainer var _rows: VBoxContainer var _empty: Label @@ -11,9 +12,15 @@ var _empty: Label func setup(p_main: Main) -> void: main = p_main add_theme_constant_override("separation", 6) + size_flags_vertical = SIZE_EXPAND_FILL + scroll = ScrollContainer.new() + scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED + scroll.size_flags_vertical = SIZE_EXPAND_FILL + add_child(scroll) _rows = VBoxContainer.new() _rows.add_theme_constant_override("separation", 6) - add_child(_rows) + _rows.size_flags_horizontal = SIZE_EXPAND_FILL + scroll.add_child(_rows) _empty = Style.make_label("Older rolls show here.", Style.body(), 15, Style.ON_FELT_MUTED) add_child(_empty) @@ -23,6 +30,8 @@ func render() -> void: _rows.remove_child(c) c.queue_free() _empty.visible = main.history.is_empty() + scroll.visible = not _empty.visible + scroll.scroll_vertical = 0 for rec in main.history: var row := HBoxContainer.new() row.add_theme_constant_override("separation", 8) diff --git a/ui/inspector.gd b/ui/inspector.gd index 6f88ac4..12e67f0 100644 --- a/ui/inspector.gd +++ b/ui/inspector.gd @@ -9,8 +9,14 @@ extends PanelContainer ## selected card changes from outside (an undo, an edit on the card), and ## keeps focus in the field being typed in. +## The default and smallest widths (the player can drag it wider) and the +## collapsed strip's width. const WIDTH := 340.0 +const MIN_WIDTH := 280.0 const STRIP := 30.0 +var width := WIDTH +## The drag handle on the inspector's left edge, shown with it when open. +var splitter: PanelSplitter var main: Main ## {kind: "card" | "result" | "pipe", tid, eid?, to?}, or {} for nothing. @@ -43,6 +49,7 @@ func setup(p_main: Main) -> void: theme = Style.card_theme() custom_minimum_size = Vector2(WIDTH, 0) size_flags_vertical = Control.SIZE_EXPAND_FILL + visibility_changed.connect(_sync_splitter) var sb := Style.box(Style.CARD, 0, [0, 0, 0, 0]) sb.border_width_left = 1 sb.border_color = Color(0, 0, 0, 0.25) @@ -117,13 +124,26 @@ func _mark_cards() -> void: func set_collapsed(on: bool) -> void: collapsed = on - custom_minimum_size.x = STRIP if on else WIDTH + custom_minimum_size.x = STRIP if on else width _body.visible = not on _strip.visible = on + _sync_splitter() if main and main.state: main.state.set_setting("inspector_collapsed", on) +## Sets the open width (from the PanelSplitter). +func set_width(px: float) -> void: + width = px + if not collapsed: + custom_minimum_size.x = px + + +func _sync_splitter() -> void: + if splitter: + splitter.visible = visible and not collapsed + + func selected_table() -> RollTable: if selection.is_empty() or main == null: return null @@ -201,7 +221,7 @@ func apply_settings(over: Dictionary, rebuild_panel: bool = false) -> String: if t == null: return "Nothing selected" var s := {"name": t.name, "details": t.details, "tags": ", ".join(t.tags), "ranged": t.is_ranged(), - "dice": t.dice, "card_mode": t.card_mode, "deck_empty": t.deck_empty} + "dice": t.dice, "dice_mod": t.dice_mod, "card_mode": t.card_mode, "deck_empty": t.deck_empty} s.merge(over, true) var r := TableSettingsDialog.apply_settings(t, s) if not r["ok"]: diff --git a/ui/inspector_card.gd b/ui/inspector_card.gd index 78b91ba..c586de5 100644 --- a/ui/inspector_card.gd +++ b/ui/inspector_card.gd @@ -4,11 +4,7 @@ extends RefCounted ## every card, then the kind's own fields (roll dice, check, choice, loop, ## router cases, variable, collection members, sheet template). Writes go ## through Inspector (apply_settings / wrote), so the settings dialog's rules -## and the undo history apply. - -const DM_PATTERN := "^dm\\(\\s*(@[a-z_][a-z0-9_]*)\\s*\\)$" -const NONE := "__none" -const AS_TEXT := "__text" +## and the undo history apply. The roll section is InspectorRoll. static func build(insp: Inspector, box: VBoxContainer, t: RollTable) -> void: @@ -26,7 +22,7 @@ static func build(insp: Inspector, box: VBoxContainer, t: RollTable) -> void: match t.kind: RollTable.KIND_ROLL: - _roll(insp, box, t) + InspectorRoll.build(insp, box, t, plain) RollTable.KIND_CHECK: _check(insp, box, t, plain) RollTable.KIND_CHOICE: @@ -128,55 +124,8 @@ static func _inputs(insp: Inspector, t: RollTable) -> Control: return v -# ---------- Roll ---------- - -static func _roll(insp: Inspector, box: VBoxContainer, t: RollTable) -> void: - var v := InspectorKit.vbox(6) - var ranged := t.is_ranged() - var dice := InspectorKit.line(t.dice, "2d6", 90.0) - InspectorKit.tag(dice, "card.dice") - insp.fields["dice"] = dice - var err := InspectorKit.error_label() - var seg := ModalCard.segmented(["Plain", "Ranged"], 1 if ranged else 0, func(i: int) -> void: - var msg := insp.apply_settings({"ranged": i == 1, "dice": dice.text.strip_edges() if dice.text.strip_edges() != "" else "1d6"}, true) - InspectorKit.show_error(err, msg) - ) - v.add_child(seg) - if ranged: - var row := InspectorKit.hbox(6) - row.add_child(InspectorKit.word("Roll")) - row.add_child(dice) - v.add_child(row) - v.add_child(InspectorKit.note(Describe.dice(t.dice, insp.main.data), Style.MUTED, 13)) - dice.text_changed.connect(func(s: String) -> void: - if not TableSettingsDialog.dice_ok_text(s): - InspectorKit.show_error(err, "“%s” isn't dice such as 2d6 or 1d100." % s.strip_edges()) - InspectorKit.mark(dice, false) - return - InspectorKit.mark(dice, true) - InspectorKit.show_error(err, insp.apply_settings({"ranged": true, "dice": s.strip_edges()})) - ) - var probs := t.range_problems() - if probs != "": - v.add_child(InspectorKit.note(probs, Style.WARN_INK, 13)) - else: - v.add_child(InspectorKit.note("Each result is equally likely, unless you give it a weight on the card.", Style.MUTED, 13)) - v.add_child(err) - box.add_child(InspectorKit.field("Rolls", v)) - - # ---------- Check ---------- -## The modifier picker's value for check_mod text: "" -> none, "dm(@str)" -> -## "@str", anything else -> AS_TEXT. -static func modifier_value(mod: String) -> String: - var s := mod.strip_edges() - if s == "": - return NONE - var m := RegEx.create_from_string(DM_PATTERN).search(s) - return m.get_string(1) if m else AS_TEXT - - static func _check(insp: Inspector, box: VBoxContainer, t: RollTable, plain: bool) -> void: var main := insp.main var sentence := InspectorKit.note("", Style.INK, 15) @@ -204,46 +153,10 @@ static func _check(insp: Inspector, box: VBoxContainer, t: RollTable, plain: boo r1.add_child(dice) box.add_child(InspectorKit.field("Dice", r1)) - # Modifier: [Strength ▾] modifier, none, or text. - var mv := modifier_value(t.check_mod) - var mod_box := InspectorKit.vbox(5) - var once := insp.has_meta("mod_text_once") - if once: - insp.remove_meta("mod_text_once") - if mv == AS_TEXT or not plain or once: - var le := InspectorKit.line(t.check_mod, "e.g. dm(@str) or @skill_melee") - InspectorKit.code(le) - InspectorKit.tag(le, "card.check_mod") - insp.fields["check_mod"] = le - var merr := InspectorKit.error_label() - le.text_changed.connect(func(s: String) -> void: - var msg := InspectorKit.expr_error(s, "The modifier") - InspectorKit.show_error(merr, msg) - InspectorKit.mark(le, msg == "") - if msg == "": - set_check(insp, "check_mod", s) - ) - mod_box.add_child(le) - mod_box.add_child(merr) - var back := InspectorKit.link("Use the picker", "Pick a value's modifier instead") - back.disabled = modifier_value(t.check_mod) == AS_TEXT - back.tooltip_text = "Pick a value's modifier instead" if not back.disabled else "The picker shows \"none\" or one value's modifier, dm(@value)" - back.pressed.connect(func() -> void: insp.rebuild()) - if plain: - mod_box.add_child(back) - else: - var row := InspectorKit.flow() - var picker := ValuePicker.new(main, mv if mv != NONE else NONE) - picker.kinds = ["number"] - picker.extras = [{"name": NONE, "label": "none", "kind": ""}, {"name": AS_TEXT, "label": "Edit as text…", "kind": ""}] - picker.set_value(mv) - insp.fields["check_mod_picker"] = picker - picker.value_chosen.connect(func(n: String) -> void: choose_modifier(insp, n)) - row.add_child(picker) - row.add_child(InspectorKit.word("modifier" if mv != NONE else "", Style.INK)) - mod_box.add_child(row) - mod_box.add_child(InspectorKit.note("A value's modifier is dm(value): −1 at 3–5, 0 at 6–8, +1 at 9–11 and so on.", Style.MUTED, 12)) - box.add_child(InspectorKit.field("Modifier", mod_box)) + var mod := ModifierEditor.new(main, t.check_mod, plain, "card.check_mod") + insp.fields["check_mod"] = mod + mod.changed.connect(func(s: String) -> void: set_check(insp, "check_mod", s)) + box.add_child(InspectorKit.field("Modifier", mod)) var r3 := InspectorKit.flow() r3.add_child(InspectorKit.word("Need")) @@ -279,25 +192,6 @@ static func set_check(insp: Inspector, key: String, value: String) -> void: insp.wrote(t) -## The modifier picker: none, a value (dm(@value)) or Edit as text. -static func choose_modifier(insp: Inspector, n: String) -> void: - match n: - NONE: - set_check(insp, "check_mod", "") - insp.rebuild() - AS_TEXT: - _rebuild_as_text(insp) - _: - set_check(insp, "check_mod", "dm(%s)" % n) - insp.rebuild() - - -static func _rebuild_as_text(insp: Inspector) -> void: - # A one-shot flag: the next build shows the modifier as text. - insp.set_meta("mod_text_once", true) - insp.rebuild() - - # ---------- Choice ---------- static func _choice(insp: Inspector, box: VBoxContainer, t: RollTable, plain: bool) -> void: diff --git a/ui/inspector_roll.gd b/ui/inspector_roll.gd new file mode 100644 index 0000000..80affe9 --- /dev/null +++ b/ui/inspector_roll.gd @@ -0,0 +1,83 @@ +class_name InspectorRoll +extends RefCounted +## The inspector's section for a roll table: Plain or Ranged, the dice, the +## modifier (ModifierEditor) and a live sentence ("Roll d20 + Luck") with +## what the modifier does now. Writes go through Inspector.apply_settings, so +## the settings dialog's rules apply. + + +static func build(insp: Inspector, box: VBoxContainer, t: RollTable, plain: bool) -> void: + var v := InspectorKit.vbox(6) + var ranged := t.is_ranged() + var dice := InspectorKit.line(t.dice, "2d6", 90.0) + InspectorKit.tag(dice, "card.dice") + insp.fields["dice"] = dice + var err := InspectorKit.error_label() + var seg := ModalCard.segmented(["Plain", "Ranged"], 1 if ranged else 0, func(i: int) -> void: + var msg := insp.apply_settings({"ranged": i == 1, "dice": dice.text.strip_edges() if dice.text.strip_edges() != "" else "1d6"}, true) + InspectorKit.show_error(err, msg) + ) + v.add_child(seg) + if not ranged: + v.add_child(InspectorKit.note("Each result is equally likely, unless you give it a weight on the card. Switch to Ranged to add a modifier to the roll.", Style.MUTED, 13)) + v.add_child(err) + box.add_child(InspectorKit.field("Rolls", v)) + return + var row := InspectorKit.hbox(6) + row.add_child(InspectorKit.word("Roll")) + row.add_child(dice) + v.add_child(row) + dice.text_changed.connect(func(s: String) -> void: + if not TableSettingsDialog.dice_ok_text(s): + InspectorKit.show_error(err, "“%s” isn't dice such as 2d6 or 1d100." % s.strip_edges()) + InspectorKit.mark(dice, false) + return + InspectorKit.mark(dice, true) + InspectorKit.show_error(err, insp.apply_settings({"ranged": true, "dice": s.strip_edges()})) + ) + v.add_child(err) + box.add_child(InspectorKit.field("Rolls", v)) + + var mod := ModifierEditor.new(insp.main, t.dice_mod, plain, "card.dice_mod") + insp.fields["dice_mod"] = mod + var merr := InspectorKit.error_label() + mod.changed.connect(func(s: String) -> void: InspectorKit.show_error(merr, insp.apply_settings({"dice_mod": s}))) + var mbox := InspectorKit.vbox(5) + mbox.add_child(mod) + mbox.add_child(merr) + box.add_child(InspectorKit.field("Modifier", mbox)) + + # A live sentence, what the modifier does, and any range problems. + var sentence := InspectorKit.note("", Style.INK, 14) + sentence.add_theme_font_override("font", Style.body_bold()) + var how := InspectorKit.note("", Style.MUTED, 13) + var probs := InspectorKit.note("", Style.WARN_INK, 13) + insp.fields["roll_sentence"] = sentence + insp.fields["roll_help"] = how + box.add_child(sentence) + box.add_child(how) + box.add_child(probs) + var refresh := func() -> void: + sentence.text = RulesView.roll_line(t, insp.main.data, plain) + how.text = help(t, insp.main) + how.visible = how.text != "" + probs.text = t.range_problems() + probs.visible = probs.text != "" + insp._live.append(refresh) + refresh.call() + + +## What a ranged table's modifier means, in words: the dice's own range, the +## modifier's value now, and how the ends work. "" without a modifier. +static func help(t: RollTable, main: Main) -> String: + if not t.has_mod(): + return "" + var parts := PackedStringArray() + if not t.is_expr_dice(): + var nat := RollRange.natural(t) + parts.append("The dice alone roll %s–%s." % [t.fmt(nat.x), t.fmt(nat.y)]) + var lm := RollRange.live_mod(t, Roller.live_context(main.data, main.persistent_vars)) + if lm["known"]: + parts.append("The modifier is %s right now." % Describe.signed_number(int(lm["value"]))) + parts.append("A total past the lowest or highest result counts as that result.") + return " ".join(parts) diff --git a/ui/inspector_roll.gd.uid b/ui/inspector_roll.gd.uid new file mode 100644 index 0000000..357a4d7 --- /dev/null +++ b/ui/inspector_roll.gd.uid @@ -0,0 +1 @@ +uid://dr6bct10vne3w diff --git a/ui/main.gd b/ui/main.gd index af36555..5e6f002 100644 --- a/ui/main.gd +++ b/ui/main.gd @@ -164,12 +164,23 @@ func _build_ui() -> void: inspector = Inspector.new() inspector.setup(self) inspector.visible = false + # Drag handles size the inspector and the tray (kept in local settings). + var side := PanelSplitter.new(self, false, "inspector_width", Inspector.WIDTH, Inspector.MIN_WIDTH) + side.size_changed.connect(inspector.set_width) + inspector.splitter = side + inspector.set_width(side.size_px) + middle.add_child(side) if state and bool(state.get_setting("inspector_collapsed", false)): inspector.set_collapsed(true) middle.add_child(inspector) + inspector._sync_splitter() editing._build_selection_bar() tray = ResultTray.new() tray.setup(self) + var foot := PanelSplitter.new(self, true, "tray_height", ResultTray.HEIGHT, ResultTray.MIN_HEIGHT) + foot.size_changed.connect(tray.set_height) + tray.set_height(foot.size_px) + root.add_child(foot) root.add_child(tray) top_bar._build_toast() undo_redo._build_edit_timer() diff --git a/ui/main_editing.gd b/ui/main_editing.gd index b1024f9..0063f70 100644 --- a/ui/main_editing.gd +++ b/ui/main_editing.gd @@ -159,7 +159,8 @@ func add_entry(tid: String) -> void: for x in t.entries: hi = maxi(hi, x.range_hi) e.has_range = true - e.range_lo = clampi(hi + 1, t.min_value(), t.die_size()) + # A table with a modifier grows past its dice; others stay within them. + 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) diff --git a/ui/modifier_editor.gd b/ui/modifier_editor.gd new file mode 100644 index 0000000..f27660e --- /dev/null +++ b/ui/modifier_editor.gd @@ -0,0 +1,181 @@ +class_name ModifierEditor +extends VBoxContainer +## Builds a roll modifier in plain words, for roll tables (dice_mod) and +## check cards (check_mod): [Add ▾] [Luck ▾]. The ways: +## none "" +## Add a value "@luck" (or a roll value such as an input: "tier") +## Subtract a value "-@fatigue" +## Add a value's modifier "dm(@str)" (the 2D-game characteristic modifier) +## Add a number "2", "-1" +## Custom any expression, typed as text +## A modifier that fits none of the plain forms opens as Custom. In Text view +## (plain = false) it's only the text field. `changed` gives the new text. + +signal changed(text: String) + +enum Way { NONE, ADD, SUBTRACT, DM, NUMBER, CUSTOM } +const WAY_LABELS := ["No modifier", "Add", "Subtract", "Add the modifier of", "Add the number", "Custom…"] +const DM_NOTE := "A value's modifier is dm(value): −1 at 3–5, 0 at 6–8, +1 at 9–11 and so on." + +var main: Main +var text := "" +var way: int = Way.NONE +var plain := true +## The inspector tag key for the text field (keeps focus across rebuilds). +var tag_key := "" +## Parts, for tests: the way dropdown, value picker, number and text fields. +var way_menu: OptionButton +var picker: ValuePicker +var number: LineEdit +var field: LineEdit + +var _value := "" +var _row: HFlowContainer +var _foot: VBoxContainer + + +func _init(p_main: Main, p_text: String, p_plain: bool = true, p_tag: String = "") -> void: + main = p_main + text = p_text.strip_edges() + plain = p_plain + tag_key = p_tag + add_theme_constant_override("separation", 5) + var p := parse(text) + way = p["way"] + _value = p["value"] + _build() + + +## The plain form of a modifier: {"way": Way, "value": String}. The value is +## the value's name ("@luck", "tier") or the number as text. +static func parse(src: String) -> Dictionary: + var s := src.strip_edges() + if s == "": + return {"way": Way.NONE, "value": ""} + var toks := Builder.tokens(s) + var kinds := PackedStringArray() + for tk: Dictionary in toks: + kinds.append(str(tk["t"]) if str(tk["t"]) != "op" else str(tk["s"])) + var shape := " ".join(kinds) + match shape: + "var", "name": + return {"way": Way.ADD, "value": toks[0]["s"]} + "- var", "- name": + return {"way": Way.SUBTRACT, "value": toks[1]["s"]} + "num", "- num": + if s.replace(" ", "").is_valid_int(): + return {"way": Way.NUMBER, "value": s.replace(" ", "")} + "name ( var )", "name ( name )": + if toks[0]["s"] == "dm": + return {"way": Way.DM, "value": toks[2]["s"]} + return {"way": Way.CUSTOM, "value": s} + + +## The modifier text for a way and value ("" when a value is still missing). +static func compose(p_way: int, value: String) -> String: + var v := value.strip_edges() + match p_way: + Way.ADD: + return v + Way.SUBTRACT: + return ("-" + v) if v != "" else "" + Way.DM: + return ("dm(%s)" % v) if v != "" else "" + Way.NUMBER, Way.CUSTOM: + return v + return "" + + +## Switches the way (as the dropdown does). A way that needs a value keeps +## the current one when it fits, and waits for a pick otherwise. +func set_way(w: int) -> void: + var keep := _value if way in [Way.ADD, Way.SUBTRACT, Way.DM] and w in [Way.ADD, Way.SUBTRACT, Way.DM] else "" + if w == Way.NUMBER: + keep = _value if way == Way.NUMBER else "1" + elif w == Way.CUSTOM: + keep = text + way = w + _value = keep + _build() + var t := compose(way, _value) + if w == Way.NONE or t != "": + _emit(t) + + +## Picks the value (as the value picker does). +func choose_value(n: String) -> void: + _value = n + if picker: + picker.set_value(n) + _emit(compose(way, _value)) + + +func _emit(t: String) -> void: + if t == text: + return + text = t + changed.emit(t) + + +func _build() -> void: + for c in get_children(): + remove_child(c) + c.queue_free() + way_menu = null + picker = null + number = null + field = null + _row = InspectorKit.flow() + add_child(_row) + _foot = InspectorKit.vbox(3) + add_child(_foot) + if not plain: + _add_field() + return + way_menu = InspectorKit.dropdown(WAY_LABELS, way) + way_menu.item_selected.connect(set_way) + _row.add_child(way_menu) + match way: + Way.ADD, Way.SUBTRACT, Way.DM: + picker = ValuePicker.new(main, _value) + picker.kinds = ["number"] + picker.set_value(_value) + picker.value_chosen.connect(choose_value) + _row.add_child(picker) + if way == Way.DM: + _foot.add_child(InspectorKit.note(DM_NOTE, Style.MUTED, 12)) + Way.NUMBER: + number = InspectorKit.amount(_value, "1") + if tag_key != "": + InspectorKit.tag(number, tag_key) + number.text_changed.connect(func(s: String) -> void: + var ok := s.strip_edges().is_valid_int() + InspectorKit.mark(number, ok) + if ok: + _value = str(s.strip_edges().to_int()) + _emit(_value) + ) + _row.add_child(number) + Way.CUSTOM: + _add_field() + + +func _add_field() -> void: + field = InspectorKit.line(text, "e.g. @luck, -@fatigue or dm(@str)") + InspectorKit.code(field) + if tag_key != "": + InspectorKit.tag(field, tag_key) + var err := InspectorKit.error_label() + field.text_changed.connect(func(s: String) -> void: + var msg := InspectorKit.expr_error(s, "The modifier") if s.strip_edges() != "" else "" + InspectorKit.show_error(err, msg) + InspectorKit.mark(field, msg == "") + if msg == "": + _emit(s.strip_edges()) + ) + field.size_flags_horizontal = Control.SIZE_EXPAND_FILL + if plain: + _foot.add_child(field) + else: + _row.add_child(field) + _foot.add_child(err) diff --git a/ui/modifier_editor.gd.uid b/ui/modifier_editor.gd.uid new file mode 100644 index 0000000..57e4c98 --- /dev/null +++ b/ui/modifier_editor.gd.uid @@ -0,0 +1 @@ +uid://bqaafmvc1f4kw diff --git a/ui/panel_splitter.gd b/ui/panel_splitter.gd new file mode 100644 index 0000000..7238371 --- /dev/null +++ b/ui/panel_splitter.gd @@ -0,0 +1,114 @@ +class_name PanelSplitter +extends Control +## A drag handle between the board and a docked panel: above the result tray +## (dragged up and down) or left of the inspector (dragged left and right). +## Dragging toward the board makes the panel bigger. A double-click puts back +## the default size. The panel's size is kept in local settings under +## `setting` when the drag ends. + +signal size_changed(px: float) + +const THICK := 7.0 +const GRIP := 36.0 + +var main: Main +## True for a handle dragged up and down (it sizes a panel's height). +var vertical := true +var setting := "" +var size_px := 0.0 +var default_px := 0.0 +var min_px := 0.0 +## The panel never takes more than this share of the window. +var max_share := 0.7 + +var _dragging := false +var _hover := false +var _from := 0.0 +var _start := 0.0 + + +func _init(p_main: Main, p_vertical: bool, p_setting: String, p_default: float, p_min: float) -> void: + main = p_main + vertical = p_vertical + setting = p_setting + default_px = p_default + min_px = p_min + size_px = p_default + if main and main.state: + size_px = float(main.state.get_setting(setting, p_default)) + custom_minimum_size = Vector2(0, THICK) if vertical else Vector2(THICK, 0) + mouse_filter = Control.MOUSE_FILTER_STOP + mouse_default_cursor_shape = Control.CURSOR_VSIZE if vertical else Control.CURSOR_HSIZE + tooltip_text = "Drag to resize · double-click for the default size" + mouse_entered.connect(func() -> void: + _hover = true + queue_redraw() + ) + mouse_exited.connect(func() -> void: + _hover = false + queue_redraw() + ) + + +func _ready() -> void: + # A smaller window shrinks a panel that no longer fits. + get_viewport().size_changed.connect(func() -> void: + if size_px > max_px(): + set_size_px(size_px) + ) + if size_px > max_px(): + set_size_px.call_deferred(size_px) + + +## The largest size allowed now: a share of the area the handle divides +## (its parent container), or of the window. +func max_px() -> float: + var area := Vector2(1600, 1000) + if get_parent() is Control and (get_parent() as Control).size != Vector2.ZERO: + area = (get_parent() as Control).size + elif is_inside_tree(): + area = get_viewport_rect().size + return maxf(min_px, (area.y if vertical else area.x) * max_share) + + +## Sets the panel's size (clamped) and tells the panel. `save` stores it. +func set_size_px(px: float, save: bool = false) -> void: + size_px = clampf(px, min_px, max_px()) + size_changed.emit(size_px) + if save and main and main.state: + main.state.set_setting(setting, roundi(size_px)) + + +func _gui_input(ev: InputEvent) -> void: + if ev is InputEventMouseButton and (ev as InputEventMouseButton).button_index == MOUSE_BUTTON_LEFT: + var mb := ev as InputEventMouseButton + if mb.double_click: + _dragging = false + set_size_px(default_px, true) + elif mb.pressed: + _dragging = true + _from = _axis(mb.global_position) + _start = size_px + elif _dragging: + _dragging = false + set_size_px(size_px, true) + accept_event() + queue_redraw() + elif ev is InputEventMouseMotion and _dragging: + # The panel sits after the handle, so moving toward the board grows it. + set_size_px(_start - (_axis((ev as InputEventMouseMotion).global_position) - _from)) + accept_event() + + +func _axis(p: Vector2) -> float: + return p.y if vertical else p.x + + +func _draw() -> void: + draw_rect(Rect2(Vector2.ZERO, size), Style.FELT_DEEP) + var lit := _hover or _dragging + var c := Style.BRASS if lit else Color(1, 1, 1, 0.18) + var mid := size / 2.0 + var r := Rect2(mid - Vector2(GRIP / 2.0, 1.5), Vector2(GRIP, 3)) if vertical \ + else Rect2(mid - Vector2(1.5, GRIP / 2.0), Vector2(3, GRIP)) + draw_rect(r, c) diff --git a/ui/panel_splitter.gd.uid b/ui/panel_splitter.gd.uid new file mode 100644 index 0000000..60c8bd9 --- /dev/null +++ b/ui/panel_splitter.gd.uid @@ -0,0 +1 @@ +uid://bfcma1ovaajku diff --git a/ui/result_tray.gd b/ui/result_tray.gd index 62fee1d..96a5463 100644 --- a/ui/result_tray.gd +++ b/ui/result_tray.gd @@ -14,6 +14,10 @@ extends PanelContainer ## ## Pieces: TrayChips builds the chips and links, TrayText words them, and ## EarlierRolls is the Earlier tab. +## +## The tray keeps the height the player drags it to (a PanelSplitter above it, +## setting "tray_height"); the chips, the sheet, Earlier and Variables each +## scroll inside it. enum Side { EARLIER, VARIABLES } @@ -42,7 +46,6 @@ var _headline_cap: Label var _headline_text: RichTextLabel var _headline_scroll: ScrollContainer const HEADLINE_W := 420.0 -const HEADLINE_MAX_H := 220.0 ## True when "+N earlier steps" has been opened for the current roll. var expanded := false var _scroll_to_end := false @@ -55,8 +58,12 @@ var _why_flag_done := false const TAIL := 12 ## Most chips shown even when expanded (a chain may have thousands). const MAX_EXPANDED := 300 -## The chips area scrolls past this height instead of pushing the board up. -const MAX_FLOW_HEIGHT := 200.0 +## The tray's default and smallest heights (it's resizable). +const HEIGHT := 230.0 +const MIN_HEIGHT := 120.0 +## Room the tray's padding, head row and gaps take from its height. +const CHROME_H := 84.0 +var height := HEIGHT func setup(p_main: Main) -> void: @@ -73,6 +80,7 @@ func setup(p_main: Main) -> void: var now := VBoxContainer.new() now.add_theme_constant_override("separation", 10) now.size_flags_horizontal = SIZE_EXPAND_FILL + now.size_flags_vertical = SIZE_EXPAND_FILL h.add_child(now) var head := HBoxContainer.new() head.add_theme_constant_override("separation", 12) @@ -108,7 +116,7 @@ func setup(p_main: Main) -> void: _headline.add_child(hv) _headline_cap = Style.make_label("", Style.body(), 12, Style.MUTED) hv.add_child(_headline_cap) - # A sheet wraps at a fixed width and scrolls past HEADLINE_MAX_H, so a long + # A sheet wraps at a fixed width and scrolls inside the tray, so a long # sheet can't widen the window or take over the tray. _headline_text = RichText.label("", 17, Style.INK, false, true) _headline_text.custom_minimum_size = Vector2(HEADLINE_W, 0) @@ -123,21 +131,19 @@ func setup(p_main: Main) -> void: # The headline sits left of the chips, so a sheet doesn't make the tray taller. var body_row := HBoxContainer.new() body_row.add_theme_constant_override("separation", 14) + body_row.size_flags_vertical = SIZE_EXPAND_FILL now.add_child(body_row) body_row.add_child(_headline) _scroll = ScrollContainer.new() _scroll.size_flags_horizontal = SIZE_EXPAND_FILL _scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED - _scroll.custom_minimum_size = Vector2(0, 58) + _scroll.size_flags_vertical = SIZE_EXPAND_FILL _flow = HFlowContainer.new() _flow.add_theme_constant_override("h_separation", 0) _flow.add_theme_constant_override("v_separation", 8) _flow.size_flags_horizontal = SIZE_EXPAND_FILL - # Keep the tray's height steady while a new roll's chips arrive. - _flow.custom_minimum_size = Vector2(0, 58) _flow.minimum_size_changed.connect(_fit_scroll.call_deferred) - _flow.resized.connect(_fit_scroll.call_deferred) _scroll.add_child(_flow) body_row.add_child(_scroll) _empty = Style.make_label("Click a die on any table to roll.", Style.body(), 16, Style.ON_FELT_MUTED) @@ -146,6 +152,7 @@ func setup(p_main: Main) -> void: var right := VBoxContainer.new() right.add_theme_constant_override("separation", 8) right.custom_minimum_size = Vector2(340, 0) + right.size_flags_vertical = SIZE_EXPAND_FILL h.add_child(right) var tabs := HBoxContainer.new() tabs.add_theme_constant_override("separation", 14) @@ -357,11 +364,17 @@ func _render_status(current: Dictionary, steps: Array) -> void: _fit_headline() +## Sets the tray's height (from its PanelSplitter); the parts inside scroll. +func set_height(px: float) -> void: + height = px + custom_minimum_size.y = px + _fit_headline() + + +## Scrolls the chips to the newest step after a roll. func _fit_scroll() -> void: if _scroll == null or _flow == null: return - var want := _flow.get_combined_minimum_size().y - _scroll.custom_minimum_size.y = clampf(want, 58.0, MAX_FLOW_HEIGHT) if _scroll_to_end: # The newest steps (and an open question) are at the end of the chain. _scroll_to_end = false @@ -371,8 +384,12 @@ func _fit_scroll() -> void: _scroll.scroll_vertical = int(_scroll.get_v_scroll_bar().max_value) -## Sizes the sheet headline's scroll area to its text, up to HEADLINE_MAX_H. +## Sizes the sheet headline's scroll area to its text, up to what the +## tray's height leaves room for. func _fit_headline() -> void: + if not is_inside_tree(): + return await get_tree().process_frame if is_instance_valid(_headline_text): - _headline_scroll.custom_minimum_size.y = minf(_headline_text.get_content_height(), HEADLINE_MAX_H) + var room := maxf(40.0, height - CHROME_H - 30.0) + _headline_scroll.custom_minimum_size.y = minf(_headline_text.get_content_height(), room) diff --git a/ui/rules_view.gd b/ui/rules_view.gd index 381f748..1fe7eb5 100644 --- a/ui/rules_view.gd +++ b/ui/rules_view.gd @@ -103,15 +103,20 @@ static func dice(expr: String, board: TowerBoard, is_plain: bool) -> String: return Describe.dice(expr, board) if is_plain else expr.strip_edges() +## A ranged roll table's roll: "Roll d20 + Luck" or "1d20 + @luck". "" when +## it isn't ranged. +static func roll_line(t: RollTable, board: TowerBoard, is_plain: bool) -> String: + if t.kind != RollTable.KIND_ROLL or not t.is_ranged(): + return "" + return Describe.roll(t, board) if is_plain else t.roll_text() + + ## A check card's rule: "Roll 2D + Strength modifier, need 8 or more" or ## "2d6 + dm(@str) vs 8+". static func check_line(t: RollTable, board: TowerBoard, is_plain: bool) -> String: if is_plain: return Describe.check(t, board) - var roll := t.check_dice.strip_edges() - if t.check_mod.strip_edges() != "": - var m := t.check_mod.strip_edges() - roll += (" " + m) if m.begins_with("-") else " + " + m + var roll := RollRange.join(t.check_dice, t.check_mod) return "%s vs %s%s" % [roll, t.check_target.strip_edges(), "-" if t.check_cmp == "le" else "+"] diff --git a/ui/table_card.gd b/ui/table_card.gd index e5039fb..01031db 100644 --- a/ui/table_card.gd +++ b/ui/table_card.gd @@ -348,6 +348,7 @@ func update_deck() -> void: func refresh_live() -> void: value_ui.refresh() rows_ui.refresh_sheet() + rows_ui.refresh_odds() header_ui.refresh_live() diff --git a/ui/table_card_editing.gd b/ui/table_card_editing.gd index a2e8ecb..589c627 100644 --- a/ui/table_card_editing.gd +++ b/ui/table_card_editing.gd @@ -163,20 +163,26 @@ func weight_edit(e: TableEntry) -> LineEdit: return edit +## Largest range value the card's range boxes take, either way. +const RANGE_LIMIT := 99999 + + func range_edit(e: TableEntry, is_lo: bool) -> LineEdit: var table := card.table var edit := LineEdit.new() edit.text = str(e.range_lo if is_lo else e.range_hi) edit.custom_minimum_size = Vector2(40, 0) edit.alignment = HORIZONTAL_ALIGNMENT_CENTER - edit.max_length = 3 - edit.tooltip_text = "Range start" if is_lo else "Range end" + edit.max_length = 6 + edit.tooltip_text = ("Range start" if is_lo else "Range end") + "\nValues past the dice (such as -3 or 24) need a modifier to come up" edit.add_theme_font_override("font", Style.display(true)) edit.add_theme_font_size_override("font_size", 15) 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.COPPER)) var commit := func() -> void: - var v := clampi(edit.text.to_int(), table.min_value(), table.die_size()) + # Any whole number: results past the dice are reached with a modifier. + var typed := edit.text.strip_edges() + var v := clampi(typed.to_int(), -RANGE_LIMIT, RANGE_LIMIT) if typed.is_valid_int() else (e.range_lo if is_lo else e.range_hi) if is_lo: e.range_lo = v else: diff --git a/ui/table_card_header.gd b/ui/table_card_header.gd index b9986bd..1810ca1 100644 --- a/ui/table_card_header.gd +++ b/ui/table_card_header.gd @@ -125,9 +125,8 @@ func _subtitle() -> String: RollTable.KIND_ROLL: if table.is_ranged(): var n := "%d ranges" % table.entries.size() - if table.is_expr_dice(): - var dl := ("Roll " + Describe.dice(table.dice, card.main.data)) if card.plain else table.dice_label() - return "%s · %s" % [dl, n] + if table.clamps(): + return "%s · %s" % [RulesView.roll_line(table, card.main.data, card.plain), n] return n if table.collapsed: return "%d results" % table.entries.size() @@ -188,10 +187,13 @@ func _make_go_button() -> Button: _: left = 34 var label := "d%d" % table.die_size() - if table.is_expr_dice(): + if table.has_mod() and not table.is_expr_dice(): + # The dice, not the ranges' end (which a modifier stretches). + label = table.dice_label() + elif table.is_expr_dice(): label = table.dice_label() if table.dice_label().length() <= 5 else "Roll" b.text = label - b.tooltip_text = "Roll %s on %s\nShift-click to skip the animation" % [table.dice_label(), table.name] + b.tooltip_text = "Roll %s on %s\nShift-click to skip the animation" % [table.roll_text() if table.is_ranged() else table.dice_label(), table.name] var rn := Style.box(Style.FELT, 8, [left, 6, 10, 6]) rn.border_width_bottom = 2 rn.border_color = Style.FELT_DEEP diff --git a/ui/table_card_rows.gd b/ui/table_card_rows.gd index a63da38..55b3e6d 100644 --- a/ui/table_card_rows.gd +++ b/ui/table_card_rows.gd @@ -21,6 +21,9 @@ var sheet_label: RichTextLabel var _row_styles: Array[StyleBoxFlat] = [] var _flick_id := "" +## Chance labels by entry id (ranged rows in Play mode), kept current by +## refresh_odds as the modifier's values change. +var _odds: Dictionary = {} func _init(p_card: TableCard) -> void: @@ -39,6 +42,7 @@ func _init(p_card: TableCard) -> void: ## Forgets the previous build's rows. func clear() -> void: parts.clear() + _odds.clear() more_label = null _flick_id = "" sheet_label = null @@ -135,9 +139,16 @@ func make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float) h.add_child(col) row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id)) if ranged and table.has_chances(): - var pct := Style.make_label("%d%%" % roundi(table.chance(e) * 100.0), Style.body(true), 12, Style.MUTED) + var pct := Style.make_label("", Style.body(true), 12, Style.MUTED) pct.size_flags_vertical = Control.SIZE_SHRINK_CENTER + pct.mouse_filter = Control.MOUSE_FILTER_PASS h.add_child(pct) + _odds[e.id] = pct + _set_odds(pct, e, live_mod()) + if ranged and table.has_mod() and num != null and not RollRange.natural_reach(table, e): + var nat := RollRange.natural(table) + num.tooltip_text = "Only a modifier reaches this: the dice alone roll %s–%s" % [table.fmt(nat.x), table.fmt(nat.y)] + num.mouse_filter = Control.MOUSE_FILTER_PASS register(e, row, num, text, index) return row @@ -332,6 +343,33 @@ func make_sheet_row(e: TableEntry, build: bool) -> Control: return row +## The roll modifier's value now (RollRange.live_mod): {"known", "value"}. +func live_mod() -> Dictionary: + var main := card.main + return RollRange.live_mod(card.table, Roller.live_context(main.data, main.persistent_vars)) + + +## Updates the chance labels for the modifier's current value. +func refresh_odds() -> void: + if _odds.is_empty(): + return + var lm := live_mod() + for eid: String in _odds: + var e := card.table.find_entry(eid) + if e != null and is_instance_valid(_odds[eid]): + _set_odds(_odds[eid], e, lm) + + +func _set_odds(pct: Label, e: TableEntry, lm: Dictionary) -> void: + var t := card.table + var txt := TablePreview.chance_text(t, e, int(lm["value"])) if lm["known"] else "" + if pct.text != txt: + pct.text = txt + if t.has_mod(): + pct.tooltip_text = "Chance with the modifier at %s" % Describe.signed_number(int(lm["value"])) if lm["known"] \ + else "The chance depends on the modifier" + + ## Re-renders a sheet card's template from the current variables. func refresh_sheet() -> void: if is_instance_valid(sheet_label): diff --git a/ui/table_preview.gd b/ui/table_preview.gd index 2041d20..be0eae4 100644 --- a/ui/table_preview.gd +++ b/ui/table_preview.gd @@ -158,8 +158,8 @@ static func _plain_summary(t: RollTable, board: TowerBoard) -> String: RollTable.KIND_CHECK: return Describe.check(t, board) RollTable.KIND_ROLL: - if t.is_expr_dice(): - return "Roll " + Describe.dice(t.dice, board) + if t.clamps(): + return Describe.roll(t, board) return "" @@ -209,7 +209,8 @@ static func _row(t: RollTable, e: TableEntry, index: int, board: TowerBoard = nu col.add_child(_label(NEXT_HINT, 11, Style.COPPER, false)) row.add_child(col) if t.kind == RollTable.KIND_ROLL: - var ch := chance_text(t, e) + # The preview doesn't know the modifier's value, so it shows no chances. + var ch := "" if t.has_mod() else chance_text(t, e) if ch != "": var c := _label(ch, 12, Style.MUTED, false) c.size_flags_vertical = Control.SIZE_SHRINK_BEGIN @@ -237,11 +238,12 @@ static func row_label(t: RollTable, e: TableEntry, index: int) -> String: return t.num_label(e, index) -## "25%", "<1%" or "" when the chances can't be known. -static func chance_text(t: RollTable, e: TableEntry) -> String: +## "25%", "<1%" or "" when the chances can't be known. `mod` is the roll +## modifier's value (RollRange.live_mod), for a table that has one. +static func chance_text(t: RollTable, e: TableEntry, mod: int = 0) -> String: if not t.has_chances(): return "" - var p := t.chance(e) * 100.0 + var p := t.chance(e, mod) * 100.0 if p <= 0.0: return "0%" if p < 1.0: diff --git a/ui/table_settings_dialog.gd b/ui/table_settings_dialog.gd index c01e8b9..b24d845 100644 --- a/ui/table_settings_dialog.gd +++ b/ui/table_settings_dialog.gd @@ -24,6 +24,8 @@ var _preview: RichTextLabel var _tags: LineEdit var _dice: LineEdit var _dice_row: Control +var _mod: LineEdit +var _mod_note: Label var _type_note: Label var _problem: Label var _deck_block: Control @@ -122,8 +124,30 @@ func _build() -> void: var eg := note("e.g. 1d100, 2d6, 1d8+2") eg.size_flags_vertical = SIZE_SHRINK_CENTER drow.add_child(eg) - _dice_row = drow - type_box.add_child(drow) + # The modifier: added to every roll, e.g. @luck. The inspector has the + # plain builder for it; here it's text with a plain reading under it. + _mod = LineEdit.new() + _mod.text = table.dice_mod + _mod.placeholder_text = "none" + _mod.custom_minimum_size.x = 140 + style_line_edit(_mod) + _mod.size_flags_horizontal = SIZE_SHRINK_BEGIN + _mod.text_changed.connect(func(_t: String) -> void: _refresh()) + var mrow := HBoxContainer.new() + mrow.add_theme_constant_override("separation", 10) + var ml := Style.make_label("Modifier", Style.body(), 15, Style.INK) + ml.size_flags_vertical = SIZE_SHRINK_CENTER + mrow.add_child(ml) + mrow.add_child(_mod) + _mod_note = note("") + _mod_note.size_flags_vertical = SIZE_SHRINK_CENTER + mrow.add_child(_mod_note) + var dice_box := VBoxContainer.new() + dice_box.add_theme_constant_override("separation", 6) + dice_box.add_child(drow) + dice_box.add_child(mrow) + _dice_row = dice_box + type_box.add_child(dice_box) _type_note = note("") type_box.add_child(_type_note) _problem = note("", Style.WARN_INK) @@ -228,7 +252,7 @@ func _set_caret_at_offset(off: int) -> void: func settings() -> Dictionary: var s := { "name": _name.text, "details": _details.text, "tags": _tags.text, - "ranged": _ranged, "dice": _dice.text.strip_edges(), + "ranged": _ranged, "dice": _dice.text.strip_edges(), "dice_mod": _mod.text.strip_edges(), "card_mode": _card_mode, "deck_empty": _deck_empty, } _kind.add_settings(s) @@ -254,13 +278,17 @@ func _refresh() -> void: msgs.append("Ranges are removed; results become plain picks.") _type_note.text = " ".join(msgs) _type_note.visible = not msgs.is_empty() + var mod_err := TableSettingsRules.mod_error(s["dice_mod"]) if _ranged else "" + _mod_note.text = "e.g. @luck, -@fatigue, dm(@str)" + if s["dice_mod"] != "" and mod_err == "": + _mod_note.text = Describe.roll(_preview_table(s), null).trim_prefix("Roll ") var problem := "" if not dice_ok: problem = "“%s” is not a valid dice expression." % s["dice"] + elif mod_err != "": + problem = mod_err elif _type_box == null or _type_box.visible: - var clone := RollTable.from_dict(table.to_dict()) - TableSettingsRules.apply_settings(clone, s) - problem = clone.range_problems() + problem = _preview_table(s).range_problems() _problem.text = problem _problem.visible = problem != "" if _type_box != null: @@ -284,6 +312,13 @@ func _on_apply() -> void: close() +## A copy of the table with the settings `s` applied, for live wording. +func _preview_table(s: Dictionary) -> RollTable: + var clone := RollTable.from_dict(table.to_dict()) + TableSettingsRules.apply_settings(clone, s) + return clone + + ## TableSettingsRules.apply_settings. static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary: return TableSettingsRules.apply_settings(t, s) diff --git a/ui/table_settings_rules.gd b/ui/table_settings_rules.gd index 8eb6d83..4df668b 100644 --- a/ui/table_settings_rules.gd +++ b/ui/table_settings_rules.gd @@ -107,6 +107,14 @@ static func dice_ok_text(text: String) -> bool: return _re("^[A-Za-z_][A-Za-z0-9_]*$").search(s) == null +## The problem with a roll modifier's text, or "" when it's fine (or empty). +static func mod_error(mod: String) -> String: + if mod.strip_edges() == "": + return "" + var err := Expr.check(TemplateKit.probe(mod.strip_edges())) + return "The modifier “%s” doesn't work: %s." % [mod.strip_edges(), err] if err != "" else "" + + ## Applies the kind-specific settings. Turning a pick choice into a number or ## text one keeps only its first entry (as the Answer); the other way, the ## Answer becomes the first of three options. @@ -227,8 +235,8 @@ static func extra_pipe_count(t: RollTable) -> int: return n -## Applies a settings Dictionary (name, details, tags, ranged, dice, card_mode, -## deck_empty) to the table. Returns {ok, error, deck_reset}: on a bad dice +## Applies a settings Dictionary (name, details, tags, ranged, dice, dice_mod, +## card_mode, deck_empty) to the table. Returns {ok, error, deck_reset}: on a bad dice ## expression nothing is changed. deck_reset says the card deck no longer fits ## (type, dice or card mode changed), so a saved deck should be cleared. static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary: @@ -244,6 +252,10 @@ static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary: var dice := str(s.get("dice", t.dice)).strip_edges() if ranged and not dice_ok_text(dice): return {"ok": false, "error": "“%s” is not a valid dice expression." % dice, "deck_reset": false} + var mod := str(s.get("dice_mod", t.dice_mod)).strip_edges() + var mod_err := mod_error(mod) + if ranged and mod_err != "": + return {"ok": false, "error": mod_err, "deck_reset": false} var was_ranged := t.is_ranged() var old_dice := t.dice var old_card := t.card_mode @@ -256,6 +268,7 @@ static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary: t.deck_empty = "stop" if str(s.get("deck_empty", t.deck_empty)) == "stop" else "reshuffle" if ranged: t.dice = dice + t.dice_mod = mod if not was_ranged: assign_ranges(t) elif was_ranged: diff --git a/ui/variables_panel.gd b/ui/variables_panel.gd index ef9f78b..6059e8a 100644 --- a/ui/variables_panel.gd +++ b/ui/variables_panel.gd @@ -7,7 +7,8 @@ extends VBoxContainer ## in-app confirmation. Below them, the last roll's chain variables (read ## only). -const HEIGHT := 112.0 +## Smallest height of the list; it fills the rest of the tray and scrolls. +const HEIGHT := 40.0 var main: Main var _list: VBoxContainer @@ -19,11 +20,14 @@ var _field_focus: StyleBoxFlat func setup(p_main: Main) -> void: main = p_main add_theme_constant_override("separation", 6) + size_flags_vertical = SIZE_EXPAND_FILL _field = Style.bordered(Style.box(Color(1, 1, 1, 0.05), 6, [8, 3, 8, 3]), 1, Color(1, 1, 1, 0.12)) _field_focus = Style.bordered(Style.box(Color(1, 1, 1, 0.1), 6, [8, 3, 8, 3]), 1, Style.BRASS) var scroll := ScrollContainer.new() scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED + # The list fills the tray's height and scrolls (the tray is resizable). scroll.custom_minimum_size = Vector2(0, HEIGHT) + scroll.size_flags_vertical = SIZE_EXPAND_FILL add_child(scroll) _list = VBoxContainer.new() _list.add_theme_constant_override("separation", 5)