diff --git a/README.md b/README.md index 6f9a77d..b0ebb9d 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,14 @@ godot --path . `[[Names -> hero]]` (saves the result as `{hero}` for the rest of the roll). `{@town|Towns}` keeps a value across rolls until you clear it in the tray's Variables tab. BBCode such as `[b]bold[/b]` works anywhere you type. +- **Logic cards** (see `docs/LOGIC.md`): Build mode's **+ Table ▾** also adds choice cards + (which option, how many, open ended), loops, variables and sheets. A choice card pauses the + roll with a pop-up (1–9 pick, R for Random, Enter confirms, Esc cancels); the steps so far + light up behind it. Loops show their rule (`× @rooms`, `while @hp > 0`); variable cards show + their live value; sheet cards show their template filled in, and become the tray's + headline when a chain reaches them. Results can carry effects (`@hp -= 2`), edited with + the **ƒ** button in Build mode. The tray's Variables tab lists every variable, with + **Reset all…**. Try `examples/logic_demo.json` (Board ▾ → Import). - **Collections:** the switcher in the top bar holds separate sets of tables. Build mode's **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 @@ -66,6 +74,11 @@ tools/test_window.sh -- --screenshot=/tmp/board.png [--build] [--expand-all] [-- [--roll=wilderness] [--fast] [--shot-delay=0.75] ``` +Logic-card views: `--board=examples/logic_demo.json --roll=start "--answers=Brin|3"` answers +the first questions and leaves the next pop-up open; `--menu=add`, `--open-settings=`, +`--edit-effects=`, `--demo-long=` (a chain of n steps) and `--confirm-reset` show the +rest. + This uses the sample board and doesn't save anything. `tools/test_window.sh` runs the game under the window class "TableTower Test" (via a temporary `override.cfg`), which a KWin window rule keeps in the background without focus. diff --git a/examples/logic_demo.json b/examples/logic_demo.json new file mode 100644 index 0000000..b6511aa --- /dev/null +++ b/examples/logic_demo.json @@ -0,0 +1,144 @@ +{ + "format_version": 2, + "id": "logic-demo", + "name": "Logic demo", + "tables": [ + { + "id": "start", + "name": "Start a delve", + "x": 40, + "y": 40, + "details": "Click the die to send a new delver down the stairs. It resets the variables, then asks two questions.", + "entries": [ + { + "id": "e1", + "text": "A new delver steps up", + "effects": "reset @hp; reset @gold; reset @luck; reset @loot", + "pipes": ["name_q"] + } + ] + }, + { + "id": "v_hp", + "name": "Hit points", + "kind": "variable", + "x": 40, + "y": 640, + "details": "Traps and fights take these away.", + "var_name": "hp", + "initial": "10", + "entries": [] + }, + { + "id": "v_gold", + "name": "Gold", + "kind": "variable", + "x": 360, + "y": 640, + "var_name": "gold", + "initial": "0", + "entries": [] + }, + { + "id": "v_luck", + "name": "Luck", + "kind": "variable", + "x": 680, + "y": 640, + "details": "Added to every room check.", + "var_name": "luck", + "initial": "0", + "entries": [] + }, + { + "id": "v_loot", + "name": "Loot", + "kind": "variable", + "x": 1000, + "y": 640, + "var_name": "loot", + "var_type": "list", + "entries": [] + }, + { + "id": "name_q", + "name": "Name your delver", + "kind": "choice", + "choice": "text", + "prompt": "Who goes down the stairs?", + "save_as": "@name", + "x": 360, + "y": 40, + "entries": [ + { "id": "e1", "text": "Answer", "pipes": ["rooms_q"] } + ] + }, + { + "id": "rooms_q", + "name": "How many rooms?", + "kind": "choice", + "choice": "number", + "prompt": "[b]{@name}[/b] studies the map. How many rooms will they try?", + "save_as": "@rooms", + "min": "1", + "max": "5", + "x": 360, + "y": 270, + "entries": [ + { "id": "e1", "text": "Answer", "pipes": ["explore"] } + ] + }, + { + "id": "explore", + "name": "Explore", + "kind": "loop", + "loop_expr": "@rooms", + "x": 680, + "y": 40, + "details": "One room check per room the player chose, then the way out.", + "entries": [ + { "id": "e1", "text": "Room {i}", "pipes": ["room_check"] }, + { "id": "e2", "text": "Head back up", "pipes": ["way_out"] } + ] + }, + { + "id": "room_check", + "name": "Room check", + "x": 1000, + "y": 40, + "dice": "2d6 + @luck", + "details": "2d6 plus Luck. Low rolls hurt, high rolls pay.", + "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 += \"gem\"", "range": [10, 12] } + ] + }, + { + "id": "way_out", + "name": "Way out", + "kind": "choice", + "prompt": "{@name} has {@gold} gold and {@hp} HP left. How do they leave?", + "x": 680, + "y": 330, + "entries": [ + { "id": "e1", "text": "Sneak past the guard", "details": "Quiet and slow. Luck grows.", "effects": "@luck += 1", "pipes": ["report"] }, + { "id": "e2", "text": "Fight through", "details": "Costs some blood.", "effects": "@hp -= 1d3", "pipes": ["report"] }, + { "id": "e3", "text": "Pay the toll", "details": "Ten gold, if they have it.", "effects": "@gold -= min(@gold, 10)", "pipes": ["report"] } + ] + }, + { + "id": "report", + "name": "Delve report", + "kind": "sheet", + "x": 1000, + "y": 330, + "entries": [ + { + "id": "e1", + "text": "[b]{@name}[/b] the delver\nRooms tried: {@rooms}\nHP {@hp} · Gold {@gold} · Luck {@luck}\nLoot: {@loot}\nScore: {= @gold + @hp * 5}" + } + ] + } + ] +} diff --git a/tests/test_logic_ui.gd b/tests/test_logic_ui.gd new file mode 100644 index 0000000..3864c46 --- /dev/null +++ b/tests/test_logic_ui.gd @@ -0,0 +1,440 @@ +extends SceneTree +## Logic cards in the app: the choice pop-up, progress while it's open, +## cancelling, a new roll replacing an open question, live variable and sheet +## cards, the long-chain tray and the Build-mode settings rules. +## Run: godot --headless --path . -s res://tests/test_logic_ui.gd -- --sample +## (--sample keeps the app from reading or writing saved collections.) + +const DEMO := "res://examples/logic_demo.json" + +var _failures := 0 +var main: Main + + +func _init() -> void: + if not OS.get_cmdline_user_args().has("--sample"): + print("Run with -- --sample so the test can't touch saved data.") + quit(2) + return + main = load("res://ui/main.tscn").instantiate() + root.add_child(main) + for i in 5: + await process_frame + if main._saving_enabled: + print("Saving is enabled; refusing to roll.") + quit(2) + return + main.rng.seed = 11 + + _test_demo_file() + await _load_demo() + _test_cards() + await _test_scripted() + await _test_dialog_answers() + await _test_cancel() + await _test_replace() + await _test_keys() + await _test_live_edits() + _test_settings_rules() + _test_add_kinds() + await _test_long_chain() + await _test_action_limit() + + print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures]) + quit(1 if _failures else 0) + + +func _load_demo() -> void: + main.prompt_hook = main._ask_player + await main._load_board_file(DEMO) + for i in 3: + await process_frame + + +## A prompt hook answering from a script by kind (scripts can be Callables). +func _scripted(answers: Dictionary, log: Array) -> Callable: + return func(req: Dictionary) -> Variant: + log.append(req) + var a: Variant = answers.get(str(req["kind"])) + if a is Callable: + return (a as Callable).call(req) + return a + + +func _var(name: String) -> Variant: + var v: Variant = main.persistent_vars.get(name) + return (v as Dictionary).get("value") if v is Dictionary else null + + +# ---------------------------------------------------------------- demo file + +func _test_demo_file() -> void: + var text := FileAccess.get_file_as_string(DEMO) + var r := IoMenu.parse_import(text, IoMenu.detect_format("logic_demo.json", text)) + _check(r["ok"] and (r["errors"] as Array).is_empty(), "the demo imports through Board ▾ → Import: %s" % str(r["errors"])) + var b := TowerBoard.new() + _check(b.load_json(text), "the demo loads as a board") + var kinds := {} + for t in b.tables: + kinds[t.kind + ("/" + t.choice if t.kind == "choice" else "")] = true + 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(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") + var nums: Array = [] + for eid: String in check._row_parts: + var num: Label = check._row_parts[eid]["num"] + nums.append(num.text if num else "") + _eq(nums, ["≤6", "7–9", "10+"], "expression dice label 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") + _eq(TableCard.loop_rule(loop.table), "× @rooms", "the loop rule reads × @rooms") + var hp := main.card_for("v_hp") + _check(hp.rows.is_empty() and hp.anchor_for("x").is_empty(), "a variable card has no outlets") + var sheet := main.card_for("report") + _check(sheet.rows.size() == 1 and not sheet.anchor_for("e1").is_empty(), "a sheet card has one outlet") + _eq(TableCard.effect_summary("@hp -= 2\n@gold += 1; @luck = 3", main.data), "Hit points -= 2 · Gold += 1 · +1", + "effect summaries use the variable card's name") + + +# ---------------------------------------------------------------- prompts + +func _test_scripted() -> void: + var log: Array = [] + main.prompt_hook = _scripted({"text": "Brin", "number": 3, "pick": 1}, log) + main.start_roll("start") + _eq(log.size(), 3, "three questions: name, rooms, way out") + var kinds: Array = [] + for r: Dictionary in log: + kinds.append(r["kind"]) + _eq(kinds, ["text", "number", "pick"], "asked in chain order") + _check(main.current.get("done", false), "a roll with questions shows at once after the last answer") + _eq(_var("name"), "Brin", "text answer saved") + _eq(_var("rooms"), 3, "number answer saved") + var passes := 0 + for s: Dictionary in main.current["all"]: + if s.has("pass"): + passes += 1 + _eq(passes, 3, "the number answer drives the loop") + var last: Dictionary = (main.current["all"] as Array).back() + _eq(last.get("table_id"), "report", "the chain ends at the sheet") + _check(main.tray._headline.visible and Formatter.strip_tags(main.tray._headline_text.text).begins_with("Brin the delver"), + "the tray headline is the rendered sheet") + # Option 1 is "Fight through", which costs 1d3 HP. + var picked := false + for s: Dictionary in main.current["all"]: + if s.get("table_id") == "way_out" and s.get("picked", false) and Formatter.strip_tags(str(s["text"])) == "Fight through": + picked = true + _check(picked, "the picked option is the step") + # Live cards after the roll. + var hp := main.card_for("v_hp") + _eq(hp._var_value.text, Expr.format_value(_var("hp")), "the HP card shows the new value after the roll") + var sheet := main.card_for("report") + _check(Formatter.strip_tags(sheet._sheet_label.text).contains("HP %s" % Expr.format_value(_var("hp"))), "the sheet card is up to date") + _check(Formatter.strip_tags(sheet._sheet_label.text).begins_with("Brin the delver"), "the sheet shows the name") + main.prompt_hook = main._ask_player + + +func _test_dialog_answers() -> void: + main.start_roll("start", true) + await process_frame + var d := main.pending_choice() + _check(d != null and d.kind == "text", "the text pop-up opens (fast roll still asks)") + if d == null: + return + _eq(d.title_label.text, "Name your delver", "pop-up title") + # Partial progress is lit before the pop-up: the start card's result. + _check(main.is_entry_lit("start", "e1"), "steps so far are lit while the question is open") + _check(not main.is_entry_lit("name_q", "e1"), "the question's own row isn't lit yet") + _check((main.current["steps"] as Array).size() == 1 and str(main.current.get("asking", "")) == "Name your delver", + "the tray shows the steps so far and the open question") + d._text.text = "Ann" + d._confirm() + await process_frame + d = main.pending_choice() + _check(d != null and d.kind == "number", "then the number pop-up") + if d == null: + return + _check(main.is_entry_lit("name_q", "e1") and main.is_entry_lit("start", "e1"), "progress grows with each answer") + _check(d._spin.min_value == 1 and d._spin.max_value == 5 and int(d._spin.value) == 1, "number pop-up has min, max and default") + d._spin.value = 2 + d._confirm() + await process_frame + d = main.pending_choice() + _check(d != null and d.kind == "pick" and d._options.size() == 3, "then the pick pop-up with three options") + if d == null: + return + _check(main.is_entry_lit("explore", "e1") and main.is_entry_lit("explore", "e2"), "the loop's steps are lit before the pick") + d.answer(-1) + await process_frame + _check(main.pending_choice() == null and main.current.get("done", false), "Random finishes the roll") + _eq(_var("name"), "Ann", "typed name saved") + _eq(_var("rooms"), 2, "typed number saved") + var random := false + for s: Dictionary in main.current["all"]: + if s.get("table_id") == "way_out" and s.get("random", false): + random = true + _check(random, "Random rolls the pick card normally") + + +func _test_cancel() -> void: + main.start_roll("start") + await process_frame + var d := main.pending_choice() + _check(d != null, "a pop-up is open") + if d == null: + return + d.close() # Esc does this + await process_frame + _check(main.pending_choice() == null, "Esc closes the pop-up") + _eq(main.current.get("halted", ""), "Cancelled", "Cancel stops the roll with Cancelled") + _check(main.current.get("done", false), "the cancelled roll is shown, not left hanging") + var last: Dictionary = (main.current["all"] as Array).back() + _check(last.get("cancelled", false) and last.get("stop", false), "the chain ends with a Cancelled marker") + _check(main.tray._halt.visible and main.tray._halt_label.text.contains("Cancelled"), "the tray says Cancelled") + _check(main.rolling_ctx == null, "no roll is left running") + # Freeing the dialog some other way also answers Cancel. + main.start_roll("start") + await process_frame + d = main.pending_choice() + if d: + d.free() + await process_frame + _check(main.current.get("done", false) and main.current.get("halted", "") == "Cancelled", "a freed pop-up cancels its roll instead of hanging") + + +func _test_replace() -> void: + main.start_roll("start") + await process_frame + var first := main.pending_choice() + _check(first != null, "first roll asks") + var first_reply := first.reply if first else null + var history := main.history.size() + main.start_roll("start") + _check(first_reply != null and first_reply.finished, "a new roll answers the old question with Cancel") + await process_frame + var second := main.pending_choice() + _check(second != null and second != first, "the new roll opens its own pop-up") + _check(not is_instance_valid(first) or first.is_queued_for_deletion(), "the old pop-up goes away") + _check(not main.current.has("halted"), "the old roll doesn't overwrite the new one") + _eq(main.history.size(), history, "the replaced (unanswered) roll isn't added to Earlier") + if second == null: + return + second._text.text = "Cy" + second._confirm() + await process_frame + var n := main.pending_choice() + if n: + n.answer(1) + await process_frame + var p := main.pending_choice() + if p: + p.answer(2) + await process_frame + _check(main.current.get("done", false) and main.current.get("halted", "") == "", "the new roll finishes normally") + _eq(_var("name"), "Cy", "with its own answers") + + +func _test_keys() -> void: + main.start_roll("start") + await process_frame + var d := main.pending_choice() + if d: + d._text.text = "Dee" + d._confirm() + await process_frame + d = main.pending_choice() + if d: + # Typing in the number field, then Enter. + var le := d._spin.get_line_edit() + le.text = "4" + le.text_changed.emit(le.text) # what typing does + le.text_submitted.emit(le.text) + await process_frame + _eq(_var("rooms"), 4, "a typed number is used") + d = main.pending_choice() + _check(d != null and d.kind == "pick", "pick pop-up for the key test") + if d == null: + return + var ev := InputEventKey.new() + ev.keycode = KEY_3 + ev.pressed = true + d._input(ev) + await process_frame + _check(main.pending_choice() == null and main.current.get("done", false), "pressing 3 answers") + var paid := false + for s: Dictionary in main.current["all"]: + if s.get("table_id") == "way_out" and Formatter.strip_tags(str(s["text"])) == "Pay the toll": + paid = true + _check(paid, "key 3 picks the third option") + + +# ---------------------------------------------------------------- live cards + +func _test_live_edits() -> void: + main.set_variable("gold", "42") + _eq(_var("gold"), 42, "a number variable stays a number") + _eq(main.card_for("v_gold")._var_value.text, "42", "the variable card follows an edit") + _check(Formatter.strip_tags(main.card_for("report")._sheet_label.text).contains("Gold 42"), "the sheet follows an edit") + main.reset_variable("gold") + _eq(_var("gold"), 0, "reset goes back to the starting value") + main.set_variable("hp", "3") + main.persistent_vars["stray"] = {"value": "x", "source": ""} + main.reset_all_variables() + _check(_var("hp") == 10 and not main.persistent_vars.has("stray"), "Reset all: declared to start, undeclared cleared") + _eq(main.card_for("v_hp")._var_value.text, "10", "cards show the reset values") + main.tray.set_side(ResultTray.Side.VARIABLES) + main.tray.render() + var rows := 0 + for c in main.tray._vars._list.get_children(): + if c is HBoxContainer: + rows += 1 + _check(rows >= 4, "the Variables tab lists every board variable, numbers included (%d rows)" % rows) + var dlg := main.tray._vars.confirm_reset_all() + _check(dlg != null and dlg.is_inside_tree(), "Reset all asks first, in the app") + dlg.close() + main.tray.set_side(ResultTray.Side.EARLIER) + # Rendering live cards doesn't happen per frame: the sheet's text stays put. + var before := main.card_for("report")._sheet_label.text + for i in 3: + await process_frame + _eq(main.card_for("report")._sheet_label.text, before, "live cards only re-render on change") + + +# ---------------------------------------------------------------- build rules + +func _test_settings_rules() -> void: + var c := RollTable.create(RollTable.KIND_CHOICE, "c", "C", "pick") + c.entries[0].effects = "@a = 1" + c.entries[0].add_pipe("x") + var r := TableSettingsDialog.apply_settings(c, {"name": "C", "choice": "number", "min": "1", "max": "@top", "prompt": "How many?", "save_as": "@n"}) + _check(r["ok"] and c.choice == "number" and c.entries.size() == 1 and c.entries[0].text == "Answer", "pick → number keeps one Answer row") + _check(Array(c.entries[0].pipes) == ["x"] and c.entries[0].effects == "@a = 1", "…with the first option's pipes and effects") + _check(c.max_expr == "@top" and c.save_as == "@n", "min/max and save as applied") + var bad := TableSettingsDialog.apply_settings(c, {"name": "C", "choice": "number", "min": "1 +", "max": "5"}) + _check(not bad["ok"] and c.min_expr == "1", "a bad min is refused and nothing changes") + var back := TableSettingsDialog.apply_settings(c, {"name": "C", "choice": "pick"}) + _check(back["ok"] and c.entries.size() == 3 and c.entries[0].text == "Option 1", "number → pick gives three options") + var l := RollTable.create(RollTable.KIND_LOOP, "l", "L", "times") + _check(not TableSettingsDialog.apply_settings(l, {"loop_mode": "while", "loop_expr": "@hp >"})["ok"], "a bad loop rule is refused") + _check(TableSettingsDialog.apply_settings(l, {"loop_mode": "while", "loop_expr": "@hp > 0"})["ok"] and l.loop_mode == "while", "a loop rule is applied") + var v := RollTable.create(RollTable.KIND_VARIABLE, "v", "V") + _check(not TableSettingsDialog.apply_settings(v, {"var_name": "Bad Name"})["ok"], "variable names are checked") + _check(TableSettingsDialog.apply_settings(v, {"var_name": "@str", "var_type": "number", "initial": "2d6"})["ok"] and v.var_name == "str", + "variable name, type and starting value applied") + var t := RollTable.create(RollTable.KIND_ROLL, "t", "T") + _check(TableSettingsDialog.apply_settings(t, {"ranged": true, "dice": "2d6 + dm(@end)"})["ok"], "expression dice are accepted") + var s := RollTable.create(RollTable.KIND_SHEET, "s", "S") + TableSettingsDialog.apply_settings(s, {"template": "HP {@hp}"}) + _eq(s.entries[0].text, "HP {@hp}", "sheet template applied") + _eq(PipePopover._count_error("@terms"), "", "pipe counts take expressions") + _check(PipePopover._count_error("@terms +") != "", "bad pipe counts are flagged") + var e := TableEntry.new("e", "x") + e.set_pipe_count("y", "@terms") + _eq(PipeLayer._pipe_tag(e, "y"), "×@terms", "expression counts show on the pipe") + # Previews. + var pv := RichText.preview("{@skill_*} and {= dm(@str)} and {= 1 +}", main.data) + _check(pv.contains("{@skill_*}") and pv.contains("{= dm(@str)}"), "previews show {@x_*} and {= expr} readably") + _check(pv.contains("error:expr"), "a broken {= expr} is marked") + _check(RichText.decorate(TextExpander.error_marker("oops")).contains(Style.DANGER_INK.to_html(false)), "error markers are red") + + +func _test_add_kinds() -> void: + main.set_mode(Main.Mode.BUILD) + var n := main.data.tables.size() + for k: Array in Main.ADD_KINDS: + var t := main.add_table(str(k[1]), str(k[2])) + _check(t.kind == k[1] and main.card_for(t.id) != null, "+ Table adds a %s" % str(k[0])) + _eq(main.data.tables.size(), n + Main.ADD_KINDS.size(), "one card per menu item") + var v1 := main.add_table(RollTable.KIND_VARIABLE, "number") + var v2 := main.add_table(RollTable.KIND_VARIABLE, "number") + _check(v1.var_name != v2.var_name, "new variable cards get distinct names") + main.set_mode(Main.Mode.PLAY) + + +# ---------------------------------------------------------------- long chains + +func _long_chain(n: int) -> void: + for id in ["long_start", "long_link"]: + if main.data.get_table(id): + main.data.remove_table(id) + var head := RollTable.create(RollTable.KIND_ROLL, "long_start", "Long chain") + head.entries.resize(1) + head.entries[0].text = "Go" + head.entries[0].effects = "@k = 0" + head.entries[0].add_pipe("long_link") + var link := RollTable.create(RollTable.KIND_ROLL, "long_link", "Link") + link.entries.resize(1) + link.entries[0].text = "Link {@k}" + link.entries[0].effects = "@k += 1" + link.entries[0].add_pipe("long_link", "@k < %d" % n) + head.position = Vector2(40, 1200) + link.position = Vector2(360, 1200) + main.data.tables.append(head) + main.data.tables.append(link) + main._rebuild_cards() + + +func _chips() -> int: + var k := 0 + for c in main.tray._flow.get_children(): + if c is PanelContainer: + k += 1 + return k + + +func _test_long_chain() -> void: + _long_chain(3000) + await process_frame + var t0 := Time.get_ticks_msec() + main.start_roll("long_start") + var ms := Time.get_ticks_msec() - t0 + var all: Array = main.current["all"] + _eq(all.size(), 3001, "a 3,001-step chain") + _check(main.current.get("done", false), "a long chain shows at once, without animating") + _check(main.is_entry_lit("long_link", "e1"), "its path is lit") + _eq(_chips(), ResultTray.TAIL, "the tray shows only the last %d steps" % ResultTray.TAIL) + var toggle: Button = null + for c in main.tray._flow.get_children(): + if c is HBoxContainer and c.get_child(0) is Button: + toggle = c.get_child(0) + _check(toggle != null and toggle.text == "+2,989 earlier steps", "a +N earlier steps toggle: %s" % (toggle.text if toggle else "none")) + if toggle: + toggle.pressed.emit() + _eq(_chips(), ResultTray.MAX_EXPANDED, "expanding shows more steps (capped)") + _check(ms < 4000, "lighting 3,000 steps is quick (%d ms)" % ms) + print(" (3,001-step roll, lit and shown in %d ms)" % ms) + _check(main.result_text(all, ResultTray.COPY_TEXT).length() < 3001 * 40, "copy text indents are capped") + var line := ResultTray.earlier_line({"root_name": "x", "steps": all}) + _check(line.length() < 2000, "Earlier rows show the last few steps of a long chain") + await process_frame + + +func _test_action_limit() -> void: + _long_chain(20000) + await process_frame + main.start_roll("long_start") + _check(str(main.current.get("halted", "")).begins_with("Stopped after 10,000"), "the action limit is reported: %s" % str(main.current.get("halted", ""))) + _check(main.tray._halt.visible and main.tray._halt_label.text.contains("10,000"), "the tray shows the limit clearly") + await process_frame + + +# ---------------------------------------------------------------- checks + +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, str(got), str(want)]) + + +func _check(ok: bool, what: String) -> void: + if not ok: + _failures += 1 + print(" ✗ ", what) diff --git a/tests/test_logic_ui.gd.uid b/tests/test_logic_ui.gd.uid new file mode 100644 index 0000000..38ecaf6 --- /dev/null +++ b/tests/test_logic_ui.gd.uid @@ -0,0 +1 @@ +uid://bvol3ms6pww03 diff --git a/ui/choice_dialog.gd b/ui/choice_dialog.gd new file mode 100644 index 0000000..46d07f8 --- /dev/null +++ b/ui/choice_dialog.gd @@ -0,0 +1,243 @@ +class_name ChoiceDialog +extends ModalCard +## The pop-up a choice card opens mid-roll (docs/LOGIC.md §2, §8): the card's +## question and either its options (pick), a number field (number) or a text +## field (text), with Cancel. +## +## Keys: 1–9 pick an option, R picks Random, Enter confirms, Esc cancels. +## +## The answer arrives through `reply.done`, a signal on a separate object so +## the waiting roll never hangs: closing or freeing the dialog in any way +## (Esc, the window closing, a new roll replacing this one) answers null, +## which is Cancel. + +## Holds the answer signal. It outlives the dialog, so an awaiting roll +## resumes even when the dialog is freed. +class Reply extends RefCounted: + signal done(value: Variant) + var finished := false + + func finish(value: Variant) -> void: + if finished: + return + finished = true + done.emit(value) + + +var request: Dictionary +var reply := Reply.new() +var kind := "pick" + +var _spin: SpinBox +var _text: LineEdit +var _options: Array[Control] = [] +var _range_note: Label +var _typed := false + + +func _init(p_request: Dictionary = {}) -> void: + request = p_request + kind = str(request.get("kind", "pick")) + var title := Formatter.strip_tags(str(request.get("title", ""))).strip_edges() + super._init(title if title != "" else "A question", 500.0) + # A stray click on the board behind shouldn't throw the answer away. + close_on_backdrop = false + # A lighter dim, so the steps that led here stay readable behind the card. + var dim := get_child(0) as ColorRect + if dim: + dim.color = Color(0, 0, 0, 0.32) + _build() + + +func _build() -> void: + var prompt := str(request.get("prompt", "")).strip_edges() + if prompt != "": + var p := RichText.label(RichText.decorate(prompt), 18, Style.INK, false) + p.size_flags_horizontal = SIZE_EXPAND_FILL + body.add_child(p) + match kind: + "number": + _build_number() + "text": + _build_text() + _: + _build_pick() + + +func _build_pick() -> void: + var list := VBoxContainer.new() + list.add_theme_constant_override("separation", 6) + body.add_child(list) + var opts: Array = request.get("options", []) + for k in opts.size(): + var o: Dictionary = opts[k] + var row := _option_row(k, o) + list.add_child(row) + _options.append(row) + var hint := note("Press 1–%d to choose, R for Random, Esc to cancel." % mini(9, maxi(1, opts.size()))) + hint.add_theme_font_size_override("font_size", 13) + body.add_child(hint) + add_button("Cancel", "plain", func() -> void: answer(null)) + var r := add_button("Random", "primary", func() -> void: answer(-1)) + r.tooltip_text = "Roll this card normally instead of choosing (R)" + + +## One option: number key, text and details as a subtitle; the whole row is a +## button. +func _option_row(k: int, o: Dictionary) -> Control: + var b := Button.new() + b.focus_mode = Control.FOCUS_ALL + b.size_flags_horizontal = SIZE_EXPAND_FILL + var m := [14, 8, 14, 9] + var n := Style.bordered(Style.box(Color.WHITE, 9, m), 1, Style.RULE) + var h := Style.bordered(Style.box(Style.LIT, 9, m), 1, Style.BRASS_DARK) + Style.skin_button(b, n, h, h, Style.INK) + b.add_theme_stylebox_override("focus", Style.focus_ring(9)) + var row := HBoxContainer.new() + row.add_theme_constant_override("separation", 12) + row.mouse_filter = MOUSE_FILTER_IGNORE + row.set_anchors_and_offsets_preset(PRESET_FULL_RECT) + row.offset_left = 14 + row.offset_right = -14 + row.offset_top = 8 + row.offset_bottom = -9 + var key := Style.make_label(str(k + 1) if k < 9 else "", Style.display(), 20, Style.COPPER) + key.custom_minimum_size = Vector2(16, 0) + key.size_flags_vertical = SIZE_SHRINK_CENTER + key.mouse_filter = MOUSE_FILTER_IGNORE + row.add_child(key) + var col := VBoxContainer.new() + col.add_theme_constant_override("separation", 1) + col.size_flags_horizontal = SIZE_EXPAND_FILL + col.mouse_filter = MOUSE_FILTER_IGNORE + row.add_child(col) + var text := RichText.label(RichText.decorate(str(o.get("text", ""))), 17, Style.INK, false, true, true) + text.mouse_filter = MOUSE_FILTER_IGNORE + col.add_child(text) + var det := Formatter.strip_tags(str(o.get("details", ""))).strip_edges() + if det != "": + var sub := Style.make_label(det, Style.body(), 13, Style.MUTED) + sub.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + sub.max_lines_visible = 2 + sub.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS + sub.mouse_filter = MOUSE_FILTER_IGNORE + col.add_child(sub) + b.tooltip_text = det + b.add_child(row) + # Buttons don't size to their children, so follow the row's height. + var fit := func() -> void: b.custom_minimum_size.y = row.get_combined_minimum_size().y + 17.0 + row.minimum_size_changed.connect(fit) + fit.call_deferred() + var index := int(o.get("index", k)) + b.pressed.connect(func() -> void: answer(index)) + return b + + +func _build_number() -> void: + var lo := int(request.get("min", 0)) + var hi := maxi(lo, int(request.get("max", 99))) + var def: Variant = request.get("default", lo) + _spin = SpinBox.new() + _spin.min_value = lo + _spin.max_value = hi + _spin.step = 1 + _spin.rounded = true + _spin.value = clampi(int(def) if (def is int or def is float) else lo, lo, hi) + _spin.custom_minimum_size = Vector2(150, 46) + _spin.size_flags_horizontal = SIZE_SHRINK_BEGIN + var le := _spin.get_line_edit() + style_line_edit(le) + le.add_theme_font_override("font", Style.body_bold()) + le.add_theme_font_size_override("font_size", 22) + le.add_theme_color_override("font_selected_color", Style.INK) + _spin.add_theme_color_override("up_icon_modulate", Style.MUTED) + _spin.add_theme_color_override("down_icon_modulate", Style.MUTED) + # Typed text is applied on confirm; the arrows (or code) set the value directly. + le.text_changed.connect(func(_t: String) -> void: _typed = true) + _spin.value_changed.connect(func(_v: float) -> void: _typed = false) + le.text_submitted.connect(func(_t: String) -> void: _confirm()) + var row := HBoxContainer.new() + row.add_theme_constant_override("separation", 12) + row.add_child(_spin) + _range_note = note("A whole number from %d to %d." % [lo, hi]) + _range_note.size_flags_vertical = SIZE_SHRINK_CENTER + row.add_child(_range_note) + body.add_child(row) + add_button("Cancel", "plain", func() -> void: answer(null)) + add_button("OK", "primary", _confirm) + + +func _build_text() -> void: + _text = LineEdit.new() + _text.placeholder_text = "Type your answer" + _text.text = str(request.get("default", "")) + style_line_edit(_text) + _text.add_theme_font_size_override("font_size", 18) + _text.text_submitted.connect(func(_t: String) -> void: _confirm()) + body.add_child(_text) + add_button("Cancel", "plain", func() -> void: answer(null)) + add_button("OK", "primary", _confirm) + + +func _ready() -> void: + super._ready() + if _spin: + _spin.get_line_edit().grab_focus() + _spin.get_line_edit().select_all() + elif _text: + _text.grab_focus() + elif not _options.is_empty(): + _options[0].grab_focus() + + +## Enter on the number or text field, or OK. +func _confirm() -> void: + if _spin: + if _typed: + _spin.apply() + answer(int(_spin.value)) + elif _text: + answer(_text.text) + + +## Gives the answer (null = Cancel) and closes. Only the first answer counts. +func answer(value: Variant) -> void: + reply.finish(value) + if is_inside_tree() and not is_queued_for_deletion(): + super.close() + + +## Esc and every other way of closing answer Cancel. +func close() -> void: + answer(null) + + +func _input(event: InputEvent) -> void: + if not is_inside_tree(): + return + var k := event as InputEventKey + if k and k.pressed and not k.echo and kind == "pick": + var code := k.keycode + if code >= KEY_1 and code <= KEY_9: + var i := code - KEY_1 + if i < _options.size(): + get_viewport().set_input_as_handled() + _options[i].emit_signal("pressed") + return + if code >= KEY_KP_1 and code <= KEY_KP_9: + var j := code - KEY_KP_1 + if j < _options.size(): + get_viewport().set_input_as_handled() + _options[j].emit_signal("pressed") + return + if code == KEY_R: + get_viewport().set_input_as_handled() + answer(-1) + return + super._input(event) + + +func _notification(what: int) -> void: + # Freed or taken off the screen without an answer: the roll gets Cancel. + if what == NOTIFICATION_EXIT_TREE or what == NOTIFICATION_PREDELETE: + reply.finish(null) diff --git a/ui/choice_dialog.gd.uid b/ui/choice_dialog.gd.uid new file mode 100644 index 0000000..871efc8 --- /dev/null +++ b/ui/choice_dialog.gd.uid @@ -0,0 +1 @@ +uid://bac7rv8cja4tc diff --git a/ui/details_popup.gd b/ui/details_popup.gd index 3b92fce..ef58848 100644 --- a/ui/details_popup.gd +++ b/ui/details_popup.gd @@ -186,16 +186,27 @@ func show_meta(owner: Control, meta: String) -> void: show_for(owner, "{%s} isn't set" % arg, "Nothing has saved this variable yet. Save it earlier in the roll with [lb][lb]Table -> %s]] or a pipe's [i]Save as[/i]." % RichText.plain(arg)) "deep": show_for(owner, "Chain too deep", "The roll stopped after %d levels so a loop can't run forever." % Roller.MAX_DEPTH) + "error": + show_for(owner, "Can't work this out", "This expression has a mistake; the message after ⚠ says what. Expressions use @variables, dice such as 2d6, + - * / and functions such as max() and dm().") + "expr": + show_for(owner, "{= %s}" % RichText.plain(arg), "A computed value, worked out each time the text is shown.") func _show_var(owner: Control, name: String) -> void: var persistent := name.begins_with("@") var value: Variant = null var source := "" + if persistent and name.ends_with("*"): + var parts := PackedStringArray() + for v: Dictionary in RollContext.vars_with_prefix(main.persistent_vars, name.substr(1)): + parts.append("%s %s" % [v["label"], Expr.format_value(v["value"])]) + show_for(owner, "{%s}" % name, ", ".join(parts) if not parts.is_empty() else "[i]None set yet[/i]", + "Every variable starting with %s" % name.trim_suffix("*")) + return if persistent: var v: Variant = main.persistent_vars.get(name.substr(1)) if v is Dictionary: - value = str(v.get("value", "")) + value = Expr.format_value(v.get("value", "")) source = str(v.get("source", "")) else: value = (main.current.get("chain_vars", {}) as Dictionary).get(name) @@ -209,6 +220,15 @@ func _show_var(owner: Control, name: String) -> void: ## "d100 · 6 ranges · 4 / 6 cards left" func table_summary(t: RollTable) -> String: + match t.kind: + RollTable.KIND_CHOICE: + return {"pick": "Choice · %d options" % t.entries.size(), "number": "Choice · a number", "text": "Choice · open ended"}.get(t.choice, "Choice") + RollTable.KIND_LOOP: + return "Loop · " + TableCard.loop_rule(t) + RollTable.KIND_VARIABLE: + return "Variable @%s · %s" % [t.var_name, t.var_type] + RollTable.KIND_SHEET: + return "Sheet" var parts := PackedStringArray([t.dice_label()]) parts.append("%d %s" % [t.entries.size(), "ranges" if t.is_ranged() else "results"]) if t.card_mode: diff --git a/ui/icons.gd b/ui/icons.gd index 94d1ad1..b498865 100644 --- a/ui/icons.gd +++ b/ui/icons.gd @@ -18,3 +18,19 @@ static func draw_tower(ci: CanvasItem, origin: Vector2, scale: float, color: Col door.append(origin + (Vector2(11, 19) + Vector2(cos(a), sin(a)) * 4.0) * scale) door.append(origin + Vector2(15, 25) * scale) ci.draw_polyline(door, accent, 1.7 * scale, true) + + +## A loop arrow: most of a circle with an arrowhead, centred on `center`. +static func draw_loop(ci: CanvasItem, center: Vector2, radius: float, color: Color, width: float = 2.0) -> void: + var start := -PI * 0.35 + var end := start + TAU * 0.8 + ci.draw_arc(center, radius, start, end, 24, color, width, true) + var tip := center + Vector2(cos(end), sin(end)) * radius + var tangent := Vector2(-sin(end), cos(end)) + var normal := Vector2(cos(end), sin(end)) + var s := radius * 0.62 + ci.draw_colored_polygon(PackedVector2Array([ + tip + tangent * s, + tip - normal * s * 0.85 - tangent * s * 0.15, + tip + normal * s * 0.85 - tangent * s * 0.15, + ]), color) diff --git a/ui/main.gd b/ui/main.gd index e89fdb8..69b6ca5 100644 --- a/ui/main.gd +++ b/ui/main.gd @@ -52,13 +52,21 @@ var _details_popup: DetailsPopup var _pipe_popover: PipePopover var _ref_cache: Dictionary = {} # entry text -> Array[String] of referenced table ids ## Choice cards: func(request: Dictionary) -> Variant, awaited by the roller -## (docs/LOGIC.md §8). Until the pop-up exists this gives the headless answers. -var prompt_hook: Callable = func(req: Dictionary) -> Variant: return Roller.default_reply(req) +## (docs/LOGIC.md §8). It opens the choice pop-up (_ask_player); tests swap in +## a script. +var prompt_hook: Callable = Callable() +var _choice: ChoiceDialog ## The context of the roll in progress, or null; its root is the tree so far ## (Roller.progress()). var rolling_ctx: RollContext = null ## Chains longer than this show at once instead of animating. const LONG_CHAIN := 40 +## Copy-as-text indents by depth up to this many levels. +const MAX_INDENT := 8 + + +func _init() -> void: + prompt_hook = _ask_player func _ready() -> void: @@ -197,9 +205,8 @@ func _build_top_bar() -> Control: var tools := HBoxContainer.new() tools.add_theme_constant_override("separation", 6) _build_tools = tools - var add := Style.bar_button("+ Table", true) - add.pressed.connect(add_table) - tools.add_child(add) + _add_menu = _make_add_menu() + tools.add_child(_add_menu) _board_menu = IoMenu.new() _board_menu.setup(true, collections_enabled()) _board_menu.reset_requested.connect(reset_sample) @@ -360,6 +367,8 @@ func mark_dirty() -> void: _ref_cache.clear() _update_collapse_all() _update_endless_chip() + if mode == Mode.BUILD: + refresh_live() func _any_expanded() -> bool: @@ -393,18 +402,83 @@ func set_all_collapsed(collapsed: bool) -> void: mark_dirty() -func add_table() -> void: +## The "+ Table ▾" kinds: [label, kind, sub, default name]. +const ADD_KINDS := [ + ["Roll table", RollTable.KIND_ROLL, "", "New table"], + ["Choice: which option", RollTable.KIND_CHOICE, "pick", "New choice"], + ["Choice: how many", RollTable.KIND_CHOICE, "number", "How many?"], + ["Choice: open ended", RollTable.KIND_CHOICE, "text", "What is it?"], + ["Loop", RollTable.KIND_LOOP, "times", "Repeat"], + ["Variable", RollTable.KIND_VARIABLE, "number", "New variable"], + ["Sheet", RollTable.KIND_SHEET, "", "Sheet"], +] + +var _add_menu: MenuButton + + +func _make_add_menu() -> MenuButton: + var mb := MenuButton.new() + mb.text = "+ Table ▾" + mb.tooltip_text = "Add a roll table or a logic card" + mb.flat = false + var ref := Style.bar_button("", true) + for n in ["normal", "hover", "pressed", "hover_pressed", "disabled", "focus"]: + mb.add_theme_stylebox_override(n, ref.get_theme_stylebox(n)) + for c in ["font_color", "font_hover_color", "font_focus_color", "font_pressed_color", "font_hover_pressed_color"]: + mb.add_theme_color_override(c, ref.get_theme_color(c)) + mb.add_theme_font_override("font", Style.body_bold()) + mb.add_theme_font_size_override("font_size", 15) + mb.mouse_default_cursor_shape = CURSOR_POINTING_HAND + ref.free() + var pm := mb.get_popup() + ModalCard.style_popup(pm) + for i in ADD_KINDS.size(): + if i == 1: + pm.add_separator("Logic cards") + pm.add_item(str(ADD_KINDS[i][0]), i) + pm.id_pressed.connect(func(id: int) -> void: + var k: Array = ADD_KINDS[id] + add_table(str(k[1]), str(k[2])) + ) + return mb + + +## Adds a card of any kind (RollTable.create) in the middle of the view. +func add_table(kind: String = RollTable.KIND_ROLL, sub: String = "") -> RollTable: var center := board.screen_to_world(board.size / 2.0) - var t := RollTable.new(TowerBoard.new_id("t"), "New table") + var name := "New table" + for k: Array in ADD_KINDS: + if k[1] == kind and (sub == "" or k[2] == sub or kind != RollTable.KIND_CHOICE): + name = str(k[3]) + break + var t := RollTable.create(kind, TowerBoard.new_id("t"), name, sub) + if kind == RollTable.KIND_ROLL: + for e in t.entries: + e.id = TowerBoard.new_id("e") + if kind == RollTable.KIND_VARIABLE: + t.var_name = _free_var_name(t.var_name) t.position = Vector2(maxf(20.0, roundf(center.x - 128.0)), maxf(20.0, roundf(center.y - 120.0))) - for n in range(1, 5): - t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Result %d" % n)) data.tables.append(t) var card := TableCard.new() board.cards.add_child(card) card.setup(self, t) cards[t.id] = card mark_dirty() + return t + + +## `base`, or base_2, base_3… when another variable card already uses it. +func _free_var_name(base: String) -> String: + var used := {} + for t in data.tables: + if t.kind == RollTable.KIND_VARIABLE: + used[t.var_name] = true + var n := base + var k := 2 + while used.has(n): + n = "%s_%d" % [base, k] + k += 1 + return n func reset_sample() -> void: @@ -511,6 +585,9 @@ func finish_link() -> void: _link_from = {} if e == null or e.pipes.has(over.table.id): return + if over.table.kind == RollTable.KIND_VARIABLE: + toast("Variable cards aren't rolled, so pipes can't lead into them. Use an effect such as @%s += 1." % over.table.var_name) + return # Each range on a ranged table takes a single pipe, so a new one replaces the old. var replaced: RollTable = null if t.is_ranged(): @@ -540,7 +617,10 @@ func _card_under_mouse() -> TableCard: ## Rolls a table and plays the result down its pipes. A fast roll (Shift held ## while clicking, or `fast`) skips the flicker and the beads and shows the -## whole result at once. +## whole result at once. Choice cards still ask (docs/LOGIC.md §8): before a +## question opens, the steps so far light up; after the last answer the rest +## of the roll shows at once. Starting a roll while a question is open cancels +## the old roll. func start_roll(tid: String, fast: bool = false) -> void: var t := data.get_table(tid) if t == null or t.kind == RollTable.KIND_VARIABLE: @@ -549,6 +629,9 @@ func start_roll(tid: String, fast: bool = false) -> void: _archive_current() _token += 1 var my := _token + # A question left open by the previous roll answers Cancel; that roll then + # sees it has been replaced and stops quietly. + cancel_choice() if _pulse_tween and _pulse_tween.is_valid(): _pulse_tween.kill() board.pipes.pulse_key = "" @@ -556,33 +639,101 @@ func start_roll(tid: String, fast: bool = false) -> void: (c as TableCard).set_rolling(false) (c as TableCard).clear_flick() var ctx := Roller.new_context(data, rng, persistent_vars, decks) - ctx.prompt = prompt_hook + ctx.prompt = _prompt_for.bind(my) rolling_ctx = ctx + current = {"collection": data.id, "root": tid, "root_name": t.name, "time": Time.get_unix_time_from_system(), + "steps": [], "all": [], "done": false, "pending": true} var tree: Dictionary = await Roller.roll_async(data, tid, ctx) if rolling_ctx == ctx: rolling_ctx = null - if my != _token: + if my != _token or not is_inside_tree(): # Another roll started while this one waited for an answer. _store_decks() if ctx.persistent_changed: _store_variables() return + var prompted: bool = current.get("prompted", false) lit_entries.clear() lit_pipes.clear() lit_texts.clear() - _refresh_lit() - current = {"collection": data.id, "root": tid, "root_name": t.name, "time": Time.get_unix_time_from_system(), + current = {"collection": data.id, "root": tid, "root_name": t.name, "time": current.get("time", Time.get_unix_time_from_system()), "steps": [], "all": Roller.flatten(tree, []), "done": false, "chain_vars": ctx.chain_vars.duplicate()} + if ctx.halted != "": + current["halted"] = ctx.halted _store_roll(ctx) - if fast or (current["all"] as Array).size() > LONG_CHAIN: + if fast or prompted or (current["all"] as Array).size() > LONG_CHAIN: _finish_fast_roll() return + _refresh_lit() tray.render() await _play_node(tree, my) if my == _token: current["steps"] = current["all"] current["done"] = true tray.render() + refresh_live() + + +## The roll's prompt hook: lights the steps so far, then asks through +## prompt_hook (the pop-up, or a test's script). A reply for a roll that has +## been replaced in the meantime is turned into Cancel. +func _prompt_for(req: Dictionary, my: int) -> Variant: + if my != _token: + return null + current["prompted"] = true + current["asking"] = Formatter.strip_tags(str(req.get("title", ""))) + show_progress() + var reply: Variant = await prompt_hook.call(req) + if my != _token: + return null + current.erase("asking") + return reply + + +## Lights the steps of the running roll so far (Roller.progress) on the board +## and in the tray, all at once. Used just before a question opens. +func show_progress() -> void: + if rolling_ctx == null: + return + var steps := Roller.progress(rolling_ctx) + lit_entries.clear() + lit_pipes.clear() + lit_texts.clear() + _light_steps(steps) + _refresh_lit() + _reveal_steps(steps) + current["steps"] = steps + current["all"] = steps + current["fast"] = true + refresh_live() + tray.render() + + +## The real prompt hook: opens the choice pop-up and waits for its answer +## (an index or -1 for a pick, an int, a String, or null for Cancel). +func _ask_player(req: Dictionary) -> Variant: + cancel_choice() + var d := ChoiceDialog.new(req) + _choice = d + var waiter := d.reply + _add_modal(d) + var v: Variant = await waiter.done + if _choice == d: + _choice = null + return v + + +## The open choice pop-up, or null. +func pending_choice() -> ChoiceDialog: + return _choice if is_instance_valid(_choice) else null + + +## Closes an open choice pop-up as Cancel (its roll stops with "Cancelled"). +func cancel_choice() -> void: + var d := pending_choice() + _choice = null + if d != null: + d.answer(null) ## Plays a result tree step by step. Iterative (an explicit stack), so long @@ -655,16 +806,35 @@ func _finish_fast_roll() -> void: var all: Array = current["all"] _light_steps(all) _refresh_lit() - for s: Dictionary in all: - var card := card_for(str(s.get("table_id", ""))) - if card and s.has("entry_id"): - card.reveal(str(s["entry_id"])) + _reveal_steps(all) current["steps"] = all current["done"] = true current["fast"] = true + refresh_live() tray.render() +## Scrolls long cards to the last result each table gave in `steps` (one +## reveal per table, so thousands of steps cost one pass). +func _reveal_steps(steps: Array) -> void: + var last := {} + for s: Dictionary in steps: + if s.has("entry_id") and not s.get("stop", false): + last[str(s.get("table_id", ""))] = str(s["entry_id"]) + for tid: String in last: + var card := card_for(tid) + if card: + card.reveal(last[tid]) + + +## Re-renders the live cards (variables, sheets, questions). Called after a +## roll, after variable edits and after edits in Build, never per frame, so +## dice inside {= } don't re-roll all the time. +func refresh_live() -> void: + for card in cards.values(): + (card as TableCard).refresh_live() + + func _pulse(key: String, my: int) -> void: var length := board.pipes.path_length(key) if length <= 0.0 or my != _token: @@ -680,7 +850,8 @@ func _pulse(key: String, my: int) -> void: ## Moves the current roll to the Earlier list (it's already in the saved history). func _archive_current() -> void: - if current.is_empty() or current.get("archived", false): + # A roll still waiting for an answer is cancelled, not kept. + if current.is_empty() or current.get("archived", false) or current.get("pending", false): return current["archived"] = true var rec := current.duplicate() @@ -700,6 +871,7 @@ func _seed_session() -> void: if not current.is_empty(): _light_steps(current.get("all", [])) _refresh_lit() + refresh_live() tray.render() return var now := Time.get_unix_time_from_system() @@ -720,23 +892,39 @@ func _seed_session() -> void: var n := Roller.roll(data, pair[1], rng, 0, scratch, ctx) if not n.is_empty() and not n.has("stop"): ctx.save(pair[0], Formatter.to_export_bbcode(str(n["summary"])), pair[1]) - var start := "wilderness" if data.get_table("wilderness") else (data.tables[0].id if not data.tables.is_empty() else "") + var start := "wilderness" if data.get_table("wilderness") else _first_rollable() if start == "": + refresh_live() tray.render() return - var best := Roller.roll(data, start, rng, 0, scratch) - for i in 400: - if Roller.reaches(best, "trinkets"): - break + var best: Dictionary + if data.get_table("trinkets"): best = Roller.roll(data, start, rng, 0, scratch) + for i in 400: + if Roller.reaches(best, "trinkets"): + break + best = Roller.roll(data, start, rng, 0, scratch) + else: + # Any other board: one roll with the headless answers, through the real + # variables, so variable and sheet cards have values to show. + best = Roller.roll(data, start, rng, 0, scratch, Roller.new_context(data, rng, persistent_vars, scratch)) var all := Roller.flatten(best, []) current = {"collection": data.id, "root": start, "root_name": data.get_table(start).name, "time": now - 60, "steps": all, "all": all, "done": true, "chain_vars": {}} Roller.collect_lit(best, lit_entries, lit_pipes, lit_texts) _refresh_lit() + refresh_live() tray.render() +## The first table that can start a roll (not a variable card), or "". +func _first_rollable() -> String: + for t in data.tables: + if t.kind != RollTable.KIND_VARIABLE: + return t.id + return "" + + # ---------- Command line (used for screenshots and checks) ---------- # godot --path . -- --screenshot=/tmp/shot.png [--build] [--expand-all] [--collapse-all] # [--roll=] [--fast] [--shot-delay=] @@ -761,6 +949,7 @@ func _run_cli(args: PackedStringArray) -> void: if args.has("--collapse-all"): set_all_collapsed(true) _run_shell_cli(args) + _run_logic_cli(args) var roll := _arg_value(args, "--roll") if roll != "": start_roll(roll, args.has("--fast")) @@ -805,10 +994,16 @@ func open_table_settings(table_id: String) -> void: d.applied.connect(func(result: Dictionary) -> void: if result.get("deck_reset", false) and state and data.id != "": state.clear_deck(data.id, t.id) - var card := card_for(t.id) - if card: - card.rebuild() + if t.kind == RollTable.KIND_VARIABLE: + # Effect chips on other cards name variables by their card. + for c in cards.values(): + (c as TableCard).rebuild() + else: + var card := card_for(t.id) + if card: + card.rebuild() mark_dirty() + refresh_live() toast("Updated %s" % t.name, snap) ) _add_modal(d) @@ -833,6 +1028,8 @@ func switch_collection(id: String) -> void: func _show_collection(b: TowerBoard) -> void: data = b _token += 1 + cancel_choice() + rolling_ctx = null board.pipes.pulse_key = "" load_local_state() if not current.is_empty(): @@ -1010,6 +1207,59 @@ func _run_shell_cli(args: PackedStringArray) -> void: _board_menu.show_popup() elif menu == "collections": _switcher.show_popup() + elif menu == "add": + # The Build tools were only just shown; let them lay out first. + await get_tree().process_frame + await get_tree().process_frame + _add_menu.show_popup() + + +# ----- Logic-card screenshot flags ----- +# --answers=||… answer the first questions automatically, in order +# (an option index or -1 for a pick, a number, or text); +# later questions open the pop-up +# --demo-long= add a table that pipes into itself n times, and fast-roll it +# --confirm-reset open the Variables tab's "Reset all…" confirmation +# --edit-effects=
open the effects editor on every row of a card (Build) + +func _run_logic_cli(args: PackedStringArray) -> void: + var answers := _arg_value(args, "--answers") + if answers != "": + var queue: Array = Array(answers.split("|")) + prompt_hook = func(req: Dictionary) -> Variant: + if queue.is_empty(): + return await _ask_player(req) + var a := str(queue.pop_front()) + return a if str(req.get("kind", "")) == "text" else a.to_int() + var n := _arg_value(args, "--demo-long").to_int() + if n > 0: + var head := RollTable.create(RollTable.KIND_ROLL, "long_start", "Long chain") + head.entries.resize(1) + head.entries[0].text = "Off we go" + head.entries[0].effects = "@k = 0" + head.entries[0].add_pipe("long_link") + var link := RollTable.create(RollTable.KIND_ROLL, "long_link", "Link") + link.entries.resize(1) + link.entries[0].text = "Link {@k}" + link.entries[0].effects = "@k += 1" + link.entries[0].add_pipe("long_link", "@k < %d" % n) + var y := 40.0 + for t in data.tables: + y = maxf(y, t.position.y + 80.0) + head.position = Vector2(40, y + 400) + link.position = Vector2(360, y + 400) + data.tables.append(head) + data.tables.append(link) + _rebuild_cards() + start_roll("long_start", true) + var fx := card_for(_arg_value(args, "--edit-effects")) + if fx: + for e in fx.table.entries: + fx._open_effects[e.id] = true + fx.rebuild() + if args.has("--confirm-reset"): + tray.set_side(ResultTray.Side.VARIABLES) + tray._vars.confirm_reset_all() # ---------- Local state: decks, persistent variables, history ---------- @@ -1157,22 +1407,74 @@ func set_variable(name: String, value: String) -> void: var source := str(old.get("source", "")) if old is Dictionary else "" # A number stays a number when the new text is one too. var was: Variant = old.get("value") if old is Dictionary else null - var typed: Variant = Expr.to_value(value) if Expr.is_number(was) and Expr.is_number(value) else value + var card := variable_card(name) + if source == "" and card: + source = card.id + var as_number := Expr.is_number(was) or (card != null and card.var_type == "number") + var typed: Variant = Expr.to_value(value) if as_number and Expr.is_number(value) else value persistent_vars[name] = {"value": typed, "source": source} - _store_variables() - if state: - state.save() - tray.render() + _variables_changed() func clear_variable(name: String) -> void: if not persistent_vars.erase(name): return + _variables_changed() + toast("Cleared {@%s}" % name) + + +## The variable card declaring `name` (no "@"), or null. +func variable_card(name: String) -> RollTable: + for t in data.tables: + if t.kind == RollTable.KIND_VARIABLE and t.var_name == name: + return t + return null + + +## Every board variable name: the set ones and the ones variable cards declare. +func variable_names() -> Array[String]: + var seen := {} + for n: String in persistent_vars: + seen[n] = true + for t in data.tables: + if t.kind == RollTable.KIND_VARIABLE and t.var_name != "": + seen[t.var_name] = true + var out: Array[String] = [] + for n: String in seen: + out.append(n) + out.sort_custom(func(a: String, b: String) -> bool: return a.naturalnocasecmp_to(b) < 0) + return out + + +## `reset @name`: a declared variable goes back to its starting value, an +## undeclared one is cleared. +func reset_variable(name: String) -> void: + var ctx := Roller.new_context(data, rng, persistent_vars, decks) + var err := Effects.reset_one(name, ctx) + _variables_changed() + if err != "": + toast("Couldn't reset @%s: %s" % [name, err]) + else: + var v: Variant = ctx.get_value("@" + name) + toast("Reset @%s%s" % [name, "" if v == null else " to " + Expr.format_value(v)]) + + +## Resets every board variable (see reset_variable). +func reset_all_variables() -> void: + var ctx := Roller.new_context(data, rng, persistent_vars, decks) + for n in variable_names(): + Effects.reset_one(n, ctx) + _variables_changed() + toast("Reset every variable") + + +## Saves the variables and re-renders what shows them. +func _variables_changed() -> void: _store_variables() if state: state.save() + refresh_live() tray.render() - toast("Cleared {@%s}" % name) ## Rolls the variable's source table again and saves the new result. @@ -1195,10 +1497,23 @@ func reroll_variable(name: String) -> void: if state: state.save() _refresh_lit() + refresh_live() tray.render() toast("{@%s} is now %s" % [name, Formatter.strip_tags(value)]) +## Re-rolling only makes sense for a text value a roll table gave (a pipe's +## "save as" or a {@var|Table}); numbers and logic-card values can't be. +func can_reroll_variable(name: String) -> bool: + var v: Variant = persistent_vars.get(name) + if not (v is Dictionary) or variable_card(name) != null: + return false + if Expr.is_number((v as Dictionary).get("value")): + return false + var t := data.get_table(str((v as Dictionary).get("source", ""))) + return t != null and t.kind == RollTable.KIND_ROLL + + # ---------- Copy ---------- ## Copies the current result: ResultTray.COPY_TEXT, COPY_BBCODE or COPY_DETAILS. @@ -1217,7 +1532,8 @@ func result_text(steps: Array, kind: int) -> String: for s: Dictionary in steps: if s.get("inline", false): continue - var indent := " ".repeat(int(s.get("depth", 0))) + # Long pipe chains nest thousands deep; cap the indent so the text stays usable. + var indent := " ".repeat(mini(int(s.get("depth", 0)), MAX_INDENT)) var tname := str(s.get("table", "")) var text := str(s.get("text", "")) if kind == ResultTray.COPY_BBCODE: @@ -1271,6 +1587,9 @@ func _load_board_file(path: String) -> void: if text == "" or not data.load_json(text): push_warning("Couldn't load board file %s" % path) return + _token += 1 + cancel_choice() + _switcher.refresh() _rebuild_cards() _seed_session() await get_tree().process_frame diff --git a/ui/pipe_layer.gd b/ui/pipe_layer.gd index 860e6e6..76038e9 100644 --- a/ui/pipe_layer.gd +++ b/ui/pipe_layer.gd @@ -102,7 +102,10 @@ func _draw() -> void: ## "×2 → foe" for a pipe with options, or "". static func _pipe_tag(e: TableEntry, to: String) -> String: var parts := PackedStringArray() - if e.count_for(to) > 1: + if e.count_expr(to) != "": + var ex := e.count_expr(to) + parts.append("×" + (ex if ex.length() <= 18 else ex.substr(0, 17) + "…")) + elif e.count_for(to) > 1: parts.append("×%d" % e.count_for(to)) if e.save_for(to) != "": parts.append("→ " + e.save_for(to)) diff --git a/ui/pipe_popover.gd b/ui/pipe_popover.gd index f90e598..fa9a480 100644 --- a/ui/pipe_popover.gd +++ b/ui/pipe_popover.gd @@ -11,6 +11,7 @@ var _entry: TableEntry var _to: String = "" var _title: RichTextLabel var _count: LineEdit +var _count_msg: Label var _save: LineEdit var _save_ok: StyleBoxFlat var _save_bad: StyleBoxFlat @@ -50,21 +51,35 @@ func setup(p_main: Main) -> void: cl.custom_minimum_size = Vector2(62, 0) count_row.add_child(cl) var minus := _small_button("−") - minus.pressed.connect(func() -> void: _set_count(_entry.count_for(_to) - 1 if _entry else 1)) + minus.pressed.connect(func() -> void: _set_count(str(_entry.count_for(_to) - 1) if _entry else "1")) count_row.add_child(minus) _count = LineEdit.new() - _count.custom_minimum_size = Vector2(44, 0) + _count.custom_minimum_size = Vector2(64, 0) _count.alignment = HORIZONTAL_ALIGNMENT_CENTER - _count.max_length = 2 + _count.max_length = 60 + _count.tooltip_text = "A number, or an expression such as @terms, answer or 1d3 (worked out when the pipe runs)" _count.add_theme_stylebox_override("normal", field_ok) _count.add_theme_stylebox_override("focus", field_focus) - _count.text_submitted.connect(func(s: String) -> void: _set_count(s.to_int())) - _count.focus_exited.connect(func() -> void: _set_count(_count.text.to_int())) + _count.text_changed.connect(func(s: String) -> void: + var ok := _count_error(s) == "" + _count.add_theme_stylebox_override("normal", field_ok if ok else _save_bad) + _count.add_theme_stylebox_override("focus", field_focus if ok else _save_bad) + _count_msg.text = _count_error(s) + _count_msg.visible = not ok + reset_size() + ) + _count.text_submitted.connect(func(s: String) -> void: _set_count(s)) + _count.focus_exited.connect(func() -> void: _set_count(_count.text)) count_row.add_child(_count) var plus := _small_button("+") - plus.pressed.connect(func() -> void: _set_count(_entry.count_for(_to) + 1 if _entry else 1)) + plus.pressed.connect(func() -> void: _set_count(str(_entry.count_for(_to) + 1) if _entry else "1")) count_row.add_child(plus) count_row.add_child(Style.make_label("times", Style.body(), 14, Style.MUTED)) + _count_msg = Style.make_label("", Style.body(), 12, Style.DANGER_INK) + _count_msg.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + _count_msg.custom_minimum_size = Vector2(260, 0) + _count_msg.hide() + v.add_child(_count_msg) var save_row := HBoxContainer.new() save_row.add_theme_constant_override("separation", 6) @@ -128,7 +143,9 @@ func open(pipe_key: String, at: Vector2) -> void: key = pipe_key var target := main.data.get_table(_to) _title.text = "%s [color=#%s]→[/color] [b]%s[/b]" % [RichText.preview(_entry.text, main.data), Style.COPPER.to_html(false), RichText.plain(Formatter.strip_tags(target.name)) if target else _to] - _count.text = str(_entry.count_for(_to)) + _count.text = _entry.count_text(_to) + _count.add_theme_stylebox_override("normal", _save_ok) + _count_msg.hide() _save.text = _entry.save_for(_to) _save.add_theme_stylebox_override("normal", _save_ok) main.board.pipes.select_key = pipe_key @@ -141,12 +158,25 @@ func open(pipe_key: String, at: Vector2) -> void: popup(Rect2i(Vector2i(p), Vector2i.ZERO)) -func _set_count(n: int) -> void: - if _entry == null: +## Sets the count from typed text: a whole number (1–99) or an expression. +## Text that isn't a valid expression is left in the field, unsaved. +func _set_count(text: String) -> void: + if _entry == null or _count_error(text) != "": return - _entry.set_pipe_count(_to, n) - _count.text = str(_entry.count_for(_to)) - main.mark_dirty() + var before := _entry.count_text(_to) + _entry.set_pipe_count(_to, text.strip_edges()) + _count.text = _entry.count_text(_to) + if _entry.count_text(_to) != before: + main.mark_dirty() + + +## "" when `text` is a usable pipe count, else why not. +static func _count_error(text: String) -> String: + var s := text.strip_edges() + if s == "" or s.is_valid_int(): + return "" + var err := Expr.check(s) + return "" if err == "" else "Not a number or expression: " + err func _commit_save() -> void: diff --git a/ui/port_layer.gd b/ui/port_layer.gd index 8842bff..73e8b26 100644 --- a/ui/port_layer.gd +++ b/ui/port_layer.gd @@ -43,7 +43,9 @@ func _draw() -> void: var card := main.card_for(t.id) if card == null or not card.is_inside_tree(): continue - _port(card.inlet_point(), Style.COPPER, Style.COPPER_DARK, 1.0) + # Variable cards are never rolled, so nothing pipes into them. + if t.kind != RollTable.KIND_VARIABLE: + _port(card.inlet_point(), Style.COPPER, Style.COPPER_DARK, 1.0) for e in t.entries: if not card.rows.has(e.id): continue diff --git a/ui/result_tray.gd b/ui/result_tray.gd index e87b1d2..b39332a 100644 --- a/ui/result_tray.gd +++ b/ui/result_tray.gd @@ -25,6 +25,24 @@ var _tab_earlier: Button var _tab_vars: Button var _shown_for: Dictionary = {} var _shown_count := 0 +var _scroll: ScrollContainer +var _halt: PanelContainer +var _halt_label: Label +var _headline: PanelContainer +var _headline_cap: Label +var _headline_text: RichTextLabel +## True when "+N earlier steps" has been opened for the current roll. +var expanded := false +var _scroll_to_end := false + +## A long chain shows only its last steps; the rest sit behind a toggle. +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 +## Most effect lines listed under one chip. +const EFFECT_LINES := 3 func setup(p_main: Main) -> void: @@ -57,12 +75,50 @@ func setup(p_main: Main) -> void: head.add_child(_again) _copy = _make_copy_menu() head.add_child(_copy) + _halt = PanelContainer.new() + _halt.add_theme_stylebox_override("panel", Style.box(Style.WARN_BG, 8, [10, 3, 10, 4])) + _halt.size_flags_vertical = SIZE_SHRINK_CENTER + _halt_label = Style.make_label("", Style.body_bold(), 14, Style.WARN_INK) + _halt.add_child(_halt_label) + _halt.hide() + head.add_child(_halt) + + # A chain that reached a sheet card leads with the rendered sheet. + _headline = PanelContainer.new() + var hsb := Style.box(Style.CARD, 10, [16, 10, 16, 12]) + Style.bordered(hsb, 2, Style.BRASS) + _headline.add_theme_stylebox_override("panel", hsb) + _headline.size_flags_horizontal = SIZE_SHRINK_BEGIN + var hv := VBoxContainer.new() + hv.add_theme_constant_override("separation", 2) + _headline.add_child(hv) + _headline_cap = Style.make_label("", Style.body(), 12, Style.MUTED) + hv.add_child(_headline_cap) + _headline_text = RichText.label("", 17, Style.INK, false, false) + RichText.hook_hover(_headline_text, main) + hv.add_child(_headline_text) + _headline.hide() + _headline.size_flags_vertical = SIZE_SHRINK_BEGIN + # 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) + 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) _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) - now.add_child(_flow) + _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) now.add_child(_empty) @@ -149,6 +205,8 @@ func render() -> void: var fresh_from := 0 if is_same(current, _shown_for): fresh_from = _shown_count + else: + expanded = false _shown_for = current _shown_count = steps.size() @@ -156,6 +214,7 @@ func render() -> void: _flow.remove_child(c) c.queue_free() _empty.visible = current.is_empty() + _render_status(current, steps) if current.is_empty(): _title.text = "RESULT" _again.hide() @@ -167,15 +226,23 @@ func render() -> void: _again.visible = main.data.get_table(current["root"]) != null var done: bool = current.get("done", false) _copy.visible = done - for i in steps.size(): + var first := visible_from(steps.size(), expanded) + if first > 0 or expanded and steps.size() > TAIL: + _flow.add_child(_earlier_toggle(first, steps.size())) + for i in range(first, steps.size()): var step: Dictionary = steps[i] - if i > 0: + if i > first: _flow.add_child(_link(step.get("inline", false))) var chip := _chip(step, done and i == steps.size() - 1) _flow.add_child(chip) if i >= fresh_from and not current.get("fast", false): chip.modulate.a = 0.3 create_tween().tween_property(chip, "modulate:a", 1.0, 0.25) + var asking := str(current.get("asking", "")) + if asking != "" and not done: + if steps.size() > first: + _flow.add_child(_link(false)) + _flow.add_child(_asking_chip(asking)) for c in _earlier.get_children(): _earlier.remove_child(c) @@ -188,21 +255,185 @@ func render() -> void: time.custom_minimum_size = Vector2(44, 0) time.size_flags_vertical = SIZE_SHRINK_BEGIN row.add_child(time) - var texts := PackedStringArray() - for s: Dictionary in rec["steps"]: - if not s.get("inline", false): - texts.append(RichText.decorate(str(s["text"]), true)) - var line := RichText.label("[color=#%s]%s:[/color] %s" % [Style.ON_FELT_MUTED.to_html(false), - RichText.plain(Formatter.strip_tags(str(rec["root_name"]))), " → ".join(texts)], 14, Style.ON_FELT, false) + var line := RichText.label(earlier_line(rec), 14, Style.ON_FELT, false) line.size_flags_horizontal = SIZE_EXPAND_FILL RichText.hook_hover(line, main) row.add_child(line) _earlier.add_child(row) - var n := main.persistent_vars.size() + var n := main.variable_names().size() _tab_vars.text = "VARIABLES · %d" % n if n > 0 else "VARIABLES" if side == Side.VARIABLES: _vars.render() + _scroll_to_end = not expanded + _fit_scroll.call_deferred() + + +## Index of the first chip shown for a chain of `count` steps: only the last +## TAIL steps of a long chain, or up to MAX_EXPANDED when expanded. +static func visible_from(count: int, is_expanded: bool) -> int: + if count <= TAIL: + return 0 + if is_expanded: + return maxi(0, count - MAX_EXPANDED) + return count - TAIL + + +## One Earlier row: "Root: a → b → c", with only the last few steps of a long +## chain. +static func earlier_line(rec: Dictionary) -> String: + var texts := PackedStringArray() + var all: Array = rec.get("steps", []) + var shown := 0 + var skipped := 0 + for k in range(all.size() - 1, -1, -1): + var s: Dictionary = all[k] + if s.get("inline", false): + continue + if shown >= 6: + skipped += 1 + continue + texts.insert(0, RichText.decorate(_one_line(str(s["text"])), true)) + shown += 1 + var lead := "[color=#%s]%s:[/color] " % [Style.ON_FELT_MUTED.to_html(false), RichText.plain(Formatter.strip_tags(str(rec.get("root_name", ""))))] + if skipped > 0: + lead += "[color=#%s]… %d earlier →[/color] " % [Style.ON_FELT_MUTED.to_html(false), skipped] + return lead + " → ".join(texts) + + +## The first line of a (sheet's) multi-line text, with "…" when there's more. +static func _one_line(text: String) -> String: + var nl := text.find("\n") + if nl < 0: + return text + return Formatter.close_open_tags(text.substr(0, nl)) + " …" + + +## The "Cancelled" / "Stopped after 10,000 actions" pill, and the sheet headline. +func _render_status(current: Dictionary, steps: Array) -> void: + var halted := str(current.get("halted", "")) + if halted == "" and current.get("done", false): + for k in range(steps.size() - 1, maxi(-1, steps.size() - 4), -1): + var s: Dictionary = steps[k] + if s.get("cancelled", false) or s.get("limit", false): + halted = Formatter.strip_tags(str(s.get("text", ""))) + break + _halt.visible = halted != "" + if halted != "": + _halt_label.text = ("✕ " if halted == Roller.CANCELLED else "⚠ ") + halted + _halt.tooltip_text = "The roll was cancelled at a question; what came before is kept." if halted == Roller.CANCELLED \ + else "This roll took too many steps, so it stopped; everything up to that point is kept." + var sheet := sheet_step(steps) if current.get("done", false) else {} + _headline.visible = not sheet.is_empty() + if not sheet.is_empty(): + _headline_cap.text = Formatter.strip_tags(str(sheet.get("table", ""))).to_upper() + _headline_text.text = RichText.decorate(str(sheet.get("text", ""))) + + +## The last sheet step of a chain (the headline), or {}. +static func sheet_step(steps: Array) -> Dictionary: + for k in range(steps.size() - 1, -1, -1): + var s: Dictionary = steps[k] + if str(s.get("kind", "")) == RollTable.KIND_SHEET and not s.get("stop", false): + return s + return {} + + +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 + await get_tree().process_frame + await get_tree().process_frame + if is_instance_valid(_scroll): + _scroll.scroll_vertical = int(_scroll.get_v_scroll_bar().max_value) + + +## "+N earlier steps" (or "Hide earlier steps") at the start of a long chain. +func _earlier_toggle(first: int, total: int) -> Control: + var b := Button.new() + if expanded: + b.text = "Hide earlier steps" if first == 0 else "Hide earlier steps (%s not shown)" % _thousands(first) + else: + b.text = "+%s earlier steps" % _thousands(first) + b.tooltip_text = "This chain has %s steps" % _thousands(total) + b.size_flags_vertical = SIZE_SHRINK_CENTER + var n := Style.bordered(Style.box(Color(1, 1, 1, 0.04), 8, [12, 6, 12, 6]), 1, Color(1, 1, 1, 0.16)) + var h := Style.bordered(Style.box(Color(1, 1, 1, 0.1), 8, [12, 6, 12, 6]), 1, Color(Style.BRASS, 0.5)) + Style.skin_button(b, n, h, h, Style.ON_FELT_MUTED, Style.ON_FELT) + b.add_theme_font_size_override("font_size", 14) + b.pressed.connect(func() -> void: + expanded = not expanded + render() + ) + var wrap := HBoxContainer.new() + wrap.add_theme_constant_override("separation", 0) + wrap.add_child(b) + var gap := Control.new() + gap.custom_minimum_size = Vector2(10, 0) + wrap.add_child(gap) + return wrap + + +static func _thousands(n: int) -> String: + var s := str(n) + var out := "" + while s.length() > 3: + out = "," + s.substr(s.length() - 3) + out + s = s.substr(0, s.length() - 3) + return s + out + + +## A dashed placeholder chip for the question that is open right now. +func _asking_chip(title: String) -> Control: + var p := PanelContainer.new() + var sb := Style.box(Color(1, 1, 1, 0.05), 9, [12, 7, 12, 8]) + Style.bordered(sb, 1, Color(Style.BRASS, 0.6)) + p.add_theme_stylebox_override("panel", sb) + p.size_flags_vertical = SIZE_SHRINK_CENTER + var v := VBoxContainer.new() + v.add_theme_constant_override("separation", 1) + p.add_child(v) + v.add_child(Style.make_label(title, Style.body(), 12, Style.ON_FELT_MUTED)) + v.add_child(Style.make_label("Waiting for your answer…", Style.display(), 20, Style.BRASS)) + return p + + +## The muted line above a chip's text: table name and how it got its result. +static func caption_for(step: Dictionary) -> String: + var caption := Formatter.strip_tags(str(step["table"])) + var num: String = str(step.get("num", "")) + match str(step.get("kind", "")): + RollTable.KIND_CHOICE: + if step.get("cancelled", false): + pass + elif step.has("answer"): + caption += " · answered" + elif step.get("picked", false): + caption += " · picked" + elif step.get("random", false): + caption += " · random" + if num != "": + caption += ", rolled %s on %s" % [num, step.get("dice", "d%d" % int(step.get("die", 0)))] + RollTable.KIND_LOOP: + if step.has("pass"): + caption += " · pass %s" % str(step["pass"]) + elif step.get("after", false): + caption += " · afterwards" + RollTable.KIND_SHEET: + caption += " · sheet" + _: + if num != "": + caption += " · rolled %s on %s" % [num, step.get("dice", "d%d" % int(step.get("die", 0)))] + if step.get("reshuffled", false): + caption += " · deck reshuffled" + if str(step.get("save_as", "")) != "": + caption += " · saved as {%s}" % step["save_as"] + return caption func _chip(step: Dictionary, last: bool) -> Control: @@ -223,32 +454,63 @@ func _chip(step: Dictionary, last: bool) -> Control: var v := VBoxContainer.new() v.add_theme_constant_override("separation", 1) p.add_child(v) - var num: String = step["num"] - var caption := Formatter.strip_tags(str(step["table"])) - if num != "": - caption += " · rolled %s on %s" % [num, step.get("dice", "d%d" % int(step["die"]))] - if step.get("reshuffled", false): - caption += " · deck reshuffled" - if str(step.get("save_as", "")) != "": - caption += " · saved as {%s}" % step["save_as"] + var caption := caption_for(step) var has_details := main.details().step_has_details(step) if has_details: caption += " " + RichText.INFO_MARK var cap := Style.make_label(caption, Style.body(), 11 if inline else 12, Style.MUTED) cap.mouse_filter = MOUSE_FILTER_IGNORE v.add_child(cap) - var shown := RichText.decorate(str(step["text"])) + var raw := str(step["text"]) + if str(step.get("kind", "")) == RollTable.KIND_SHEET: + raw = _one_line(raw) + if step.has("answer") and Formatter.strip_tags(raw).strip_edges() == "": + raw = "[i]no answer[/i]" + var shown := RichText.decorate(raw) var body := RichText.display_label(shown, 16 if inline else 20, Style.DANGER_INK if step.get("stop", false) else Style.INK) if Formatter.strip_tags(shown).length() > 56: body.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART body.custom_minimum_size = Vector2(420, 0) RichText.hook_hover(body, main) v.add_child(body) + var fx: Array = step.get("effects", []) + if not fx.is_empty(): + v.add_child(_effect_lines(fx)) if has_details: p.mouse_entered.connect(func() -> void: main.details().show_step(p, step)) return p +## The effect log under a chip: a few compact lines, errors in red. +func _effect_lines(fx: Array) -> Control: + var box := VBoxContainer.new() + box.add_theme_constant_override("separation", 0) + box.mouse_filter = MOUSE_FILTER_IGNORE + var shown := 0 + var errors := 0 + for l: Variant in fx: + var d: Dictionary = l if l is Dictionary else {"text": str(l)} + var bad: bool = d.get("error", false) + if bad: + errors += 1 + # Errors are always listed; ordinary lines up to EFFECT_LINES. + if shown >= EFFECT_LINES and not bad: + continue + var lab := Style.make_label(("⚠ " if bad else "") + str(d.get("text", "")), Style.body_bold() if bad else Style.body(), 12, + Style.DANGER_INK if bad else Style.COPPER_DARK) + lab.mouse_filter = MOUSE_FILTER_IGNORE + lab.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS + lab.custom_minimum_size.x = 0 + box.add_child(lab) + shown += 1 + var more := fx.size() - shown + if more > 0: + box.add_child(Style.make_label("+%d more" % more, Style.body(), 11, Style.MUTED)) + var tip := Effects.log_text(fx) + box.tooltip_text = "\n".join(tip) + return box + + func _link(inline: bool = false) -> Control: var link := Panel.new() var sb := Style.box(Style.BRASS) diff --git a/ui/rich_text.gd b/ui/rich_text.gd index 52a4556..3eb5393 100644 --- a/ui/rich_text.gd +++ b/ui/rich_text.gd @@ -12,6 +12,7 @@ const _COUNT_PATTERN := "^(?:(\\d+)\\s*[x×]|(\\d*[dD]\\d+(?:\\s*[+-]\\s*\\d+)?) static var _var_re: RegEx static var _count_re: RegEx +static var _list_re: RegEx ## Colours for marker text, on cards (light) and on the felt (dark). const REF_INK := Color("#1d6656") @@ -111,6 +112,24 @@ static func preview(text: String, board: TowerBoard) -> String: i += (tag["raw"] as String).length() continue elif c == "{": + # {= expr}: a computed value, shown as written (red if it can't parse). + if i + 1 < n and text[i + 1] == "=": + var close := text.find("}", i + 2) + var nl := text.find("\n", i + 2) + if close >= 0 and (nl < 0 or close < nl): + var src := text.substr(i + 2, close - i - 2).strip_edges() + var err := Expr.check(src) + var ink := Style.DANGER_INK if err != "" else VAR_INK + out += "[url=%s][color=#%s]{= %s}[/color][/url]" % ["error:expr" if err != "" else "expr:" + plain(src).replace("]", ""), + ink.to_html(false), plain(src)] + i = close + 1 + continue + # {@prefix_*}: a list of every variable with the prefix. + var lm := _lre().search(text, i) + if lm != null and lm.get_start() == i: + out += "[url=var:@%s*][color=#%s]{@%s*}[/color][/url]" % [lm.get_string(1), VAR_INK.to_html(false), lm.get_string(1)] + i = lm.get_end() + continue var m := _vre().search(text, i) if m != null and m.get_start() == i: var vname := m.get_string(1) @@ -182,7 +201,7 @@ static func _marker_color(meta: String, on_felt: bool) -> String: return (REF_INK_FELT if on_felt else REF_INK).to_html(false) if meta.begins_with("var:"): return (VAR_INK_FELT if on_felt else VAR_INK).to_html(false) - if meta.begins_with("missing:") or meta.begins_with("unset:") or meta.begins_with("deep:"): + if meta.begins_with("missing:") or meta.begins_with("unset:") or meta.begins_with("deep:") or meta.begins_with("error:"): return (BAD_INK_FELT if on_felt else Style.DANGER_INK).to_html(false) return "" @@ -198,6 +217,13 @@ static func _vre() -> RegEx: return _var_re +static func _lre() -> RegEx: + if _list_re == null: + _list_re = RegEx.new() + _list_re.compile("\\{@([A-Za-z0-9_]*)\\*\\}") + return _list_re + + static func _cre() -> RegEx: if _count_re == null: _count_re = RegEx.new() diff --git a/ui/table_card.gd b/ui/table_card.gd index 30b05d5..42f1f7d 100644 --- a/ui/table_card.gd +++ b/ui/table_card.gd @@ -3,6 +3,13 @@ extends PanelContainer ## One table on the board: a header with the collapse toggle, name and die ## button, then its numbered results. Rebuilt from the RollTable whenever the ## mode, the table's shape, or (when collapsed) the lit result changes. +## +## Logic cards (docs/LOGIC.md) share the layout: a choice card has a "?" +## badge, its question and its options (or one Answer row); a loop card shows +## its rule and the Each time / Afterwards rows; a variable card shows its +## live value and has no rows; a sheet card's one row is its rendered +## template. Live text (values, sheets, prompts) is only re-rendered by +## refresh_live(), which Main calls after rolls and edits, never per frame. const WIDTH := 256.0 ## Build mode has more controls per row, so cards are a little wider there. @@ -40,7 +47,15 @@ var _deck_row: Control var _deck_label: Label ## Entry ids whose details editor is open (Build mode). var _open_details: Dictionary = {} +## Entry ids whose effects editor is open (Build mode). +var _open_effects: Dictionary = {} var _table_details_open := false +## Live parts, updated by refresh_live(). +var _prompt_label: RichTextLabel +var _var_value: Label +var _var_hint: Label +var _sheet_label: RichTextLabel +var _live_cache: Dictionary = {} func setup(p_main: Main, p_table: RollTable) -> void: @@ -89,11 +104,17 @@ func rebuild() -> void: _flick_id = "" _deck_row = null _deck_label = null + _prompt_label = null + _var_value = null + _var_hint = null + _sheet_label = null + _live_cache.clear() var build := main.mode == Main.Mode.BUILD custom_minimum_size = Vector2(card_width(), 0) _shrink.call_deferred() var ranged := table.is_ranged() + var collapsed := is_collapsed() var col := _vbox(0) add_child(col) col.add_child(_make_header(build, ranged)) @@ -105,13 +126,24 @@ func rebuild() -> void: ted.add_theme_constant_override("margin_top", 8) col.add_child(ted) + if table.kind == RollTable.KIND_VARIABLE: + col.add_child(_make_variable_body(build)) + _warn_panel = _make_warning() + col.add_child(_warn_panel) + _update_warning() + if build: + col.add_child(_make_footer(ranged)) + _apply_style() + refresh_live() + return + var pad := MarginContainer.new() pad.mouse_filter = MOUSE_FILTER_PASS pad.add_theme_constant_override("margin_top", 6) pad.add_theme_constant_override("margin_bottom", 8) _list_box = _vbox(0) pad.add_child(_list_box) - if not table.collapsed and table.entries.size() > LONG_LIST: + if not collapsed and table.entries.size() > LONG_LIST: list_scroll = ScrollContainer.new() list_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED list_scroll.custom_minimum_size = Vector2(0, LIST_HEIGHT) @@ -127,16 +159,21 @@ func rebuild() -> void: for i in table.entries.size(): var e := table.entries[i] var lit := main.is_entry_lit(table.id, e.id) - if table.collapsed and not lit: + if collapsed and not lit: continue - _list_box.add_child(_make_row(e, i, build, ranged, numw)) + if table.kind == RollTable.KIND_SHEET: + _list_box.add_child(_make_sheet_row(e, build)) + else: + _list_box.add_child(_make_row(e, i, build, ranged, numw)) _set_row_state(e.id, RowState.LIT if lit else RowState.NORMAL) + if build and _open_effects.has(e.id): + _list_box.add_child(_effects_editor(e, 12.0 + numw + 4.0)) if build and _open_details.has(e.id): _list_box.add_child(_details_editor(e.details, "Details for this result (BBCode)", 12.0 + numw + 4.0, func(s: String) -> void: e.details = s main.mark_dirty())) - if table.collapsed: + if collapsed: _list_box.add_child(_make_more_row(numw)) _warn_panel = _make_warning() @@ -145,6 +182,7 @@ func rebuild() -> void: if build: col.add_child(_make_footer(ranged)) _apply_style() + refresh_live() if list_scroll != null: for eid in rows: if main.is_entry_lit(table.id, eid): @@ -152,6 +190,15 @@ func rebuild() -> void: break +## Variable and sheet cards always show everything; other cards collapse. +func is_collapsed() -> bool: + return table.collapsed and can_collapse() + + +func can_collapse() -> bool: + return table.kind != RollTable.KIND_VARIABLE and table.kind != RollTable.KIND_SHEET + + func _reveal_when_laid_out(eid: String) -> void: await get_tree().process_frame if is_instance_valid(list_scroll): @@ -198,12 +245,13 @@ func _make_header(build: bool, ranged: bool) -> Control: header.add_child(head_box) head_box.add_child(row) - var chevron := ChevronButton.new() - chevron.open = not table.collapsed - chevron.tooltip_text = ("Expand " if table.collapsed else "Collapse ") + table.name - chevron.size_flags_vertical = SIZE_SHRINK_CENTER - chevron.pressed.connect(func() -> void: main.toggle_collapse(table.id)) - row.add_child(chevron) + if can_collapse(): + var chevron := ChevronButton.new() + chevron.open = not table.collapsed + chevron.tooltip_text = ("Expand " if table.collapsed else "Collapse ") + table.name + chevron.size_flags_vertical = SIZE_SHRINK_CENTER + chevron.pressed.connect(func() -> void: main.toggle_collapse(table.id)) + row.add_child(chevron) header.mouse_entered.connect(func() -> void: if not _dragging and main.mode == Main.Mode.PLAY: @@ -252,23 +300,81 @@ func _make_header(build: bool, ranged: bool) -> Control: titles.add_child(name_row) else: titles.add_child(title) - if ranged or table.collapsed: - var count := "%d %s" % [table.entries.size(), "ranges" if ranged else "results"] - var cl := Style.make_label(count, Style.body(true), 12, Style.MUTED) + var sub := _subtitle() + if sub != "": + var cl := Style.make_label(sub, Style.body(true), 12, Style.MUTED) cl.mouse_filter = MOUSE_FILTER_IGNORE + cl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART titles.add_child(cl) row.add_child(titles) if table.card_mode: _deck_row = _make_deck_row() - var die := table.die_size() - var roll := Button.new() - roll.text = "d%d" % die - roll.tooltip_text = "Roll d%d on %s\nShift-click to skip the animation" % [die, table.name] - roll.size_flags_vertical = SIZE_SHRINK_CENTER - roll.add_theme_font_override("font", Style.display(true)) - roll.add_theme_font_size_override("font_size", 17) - var rn := Style.box(Style.FELT, 8, [34, 6, 10, 6]) + var go := _make_go_button() + if go != null: + row.add_child(go) + if _deck_row != null: + head_box.add_child(_deck_row) + var extra := _make_kind_header(build) + if extra != null: + head_box.add_child(extra) + return header + + +## The small line under the title in Play mode ("2d6 + dm(@end) · 2 ranges"). +func _subtitle() -> String: + match table.kind: + RollTable.KIND_ROLL: + if table.is_ranged(): + var n := "%d ranges" % table.entries.size() + return "%s · %s" % [table.dice_label(), n] if table.is_expr_dice() else n + if table.collapsed: + return "%d results" % table.entries.size() + RollTable.KIND_CHOICE: + if table.collapsed: + return "%d options" % table.entries.size() + return "" + + +## The header button that starts a roll: the die on roll tables, a "?" badge on +## choice cards, a loop arrow on loop cards and "Print" on sheets. Variable +## cards have none. +func _make_go_button() -> Button: + _die_icon = null + if table.kind == RollTable.KIND_VARIABLE: + return null + var b := Button.new() + b.size_flags_vertical = SIZE_SHRINK_CENTER + b.add_theme_font_override("font", Style.display(true)) + b.add_theme_font_size_override("font_size", 17) + var left := 10 + match table.kind: + RollTable.KIND_CHOICE: + b.text = "?" + b.add_theme_font_size_override("font_size", 20) + b.custom_minimum_size = Vector2(36, 0) + b.tooltip_text = "Ask: %s" % Formatter.strip_tags(table.prompt if table.prompt != "" else table.name) + RollTable.KIND_LOOP: + b.custom_minimum_size = Vector2(38, 32) + b.tooltip_text = "Run %s" % Formatter.strip_tags(table.name) + var icon := Control.new() + icon.mouse_filter = MOUSE_FILTER_IGNORE + icon.set_anchors_and_offsets_preset(PRESET_FULL_RECT) + icon.draw.connect(func() -> void: Icons.draw_loop(icon, icon.size / 2.0 + Vector2(0, -1), 7.0, Style.BRASS, 2.2)) + b.add_child(icon) + RollTable.KIND_SHEET: + b.text = "Print" + b.add_theme_font_override("font", Style.body_bold(true)) + b.add_theme_font_size_override("font_size", 14) + b.tooltip_text = "Print this sheet in the tray" + _: + left = 34 + var label := "d%d" % table.die_size() + if 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] + var rn := Style.box(Style.FELT, 8, [left, 6, 10, 6]) rn.border_width_bottom = 2 rn.border_color = Style.FELT_DEEP var rh := rn.duplicate() as StyleBoxFlat @@ -277,16 +383,67 @@ func _make_header(build: bool, ranged: bool) -> Control: rp.border_width_bottom = 1 rp.content_margin_top = 7 rp.content_margin_bottom = 5 - Style.skin_button(roll, rn, rh, rp, Style.BRASS) - _die_icon = DieIcon.new() - _die_icon.spinning = _rolling - roll.add_child(_die_icon) - roll.resized.connect(func() -> void: _die_icon.position = Vector2(8, (roll.size.y - 20.0) / 2.0 - 1.0)) - roll.pressed.connect(func() -> void: main.start_roll(table.id)) - row.add_child(roll) - if _deck_row != null: - head_box.add_child(_deck_row) - return header + Style.skin_button(b, rn, rh, rp, Style.BRASS) + if table.kind == RollTable.KIND_ROLL: + var die := DieIcon.new() + die.spinning = _rolling + _die_icon = die + b.add_child(die) + b.resized.connect(func() -> void: die.position = Vector2(8, (b.size.y - 20.0) / 2.0 - 1.0)) + b.pressed.connect(func() -> void: main.start_roll(table.id)) + return b + + +## Kind-specific lines under the header: a choice card's question, a loop's +## rule, a variable's name. +func _make_kind_header(_build: bool) -> Control: + match table.kind: + RollTable.KIND_CHOICE: + var v := _vbox(3) + _prompt_label = RichText.label("", 15, Style.INK, true) + _prompt_label.mouse_filter = MOUSE_FILTER_IGNORE + v.add_child(_prompt_label) + var kinds := {"pick": "Pick one", "number": "A number", "text": "Your words"} + var info := str(kinds.get(table.choice, "")) + if table.choice == "number": + info += " · %s to %s" % [table.min_expr, table.max_expr] + if table.save_as != "": + info += " · saves %s" % table.save_as + var l := Style.make_label(info, Style.body(true), 12, Style.MUTED) + l.mouse_filter = MOUSE_FILTER_IGNORE + l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + v.add_child(l) + return v + RollTable.KIND_LOOP: + var chip := PanelContainer.new() + chip.mouse_filter = MOUSE_FILTER_PASS + chip.size_flags_horizontal = SIZE_SHRINK_BEGIN + chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(Color(Style.BRASS, 0.16), 6, [8, 1, 8, 2]), 1, Color(Style.BRASS_DARK, 0.35))) + var err := Expr.check(table.loop_expr) if table.loop_expr.strip_edges() != "" else "No rule yet" + var l := Style.make_label(loop_rule(table), Style.display(true), 16, Style.DANGER_INK if err != "" else Style.COPPER_DARK) + l.mouse_filter = MOUSE_FILTER_IGNORE + chip.add_child(l) + chip.tooltip_text = err + return chip + RollTable.KIND_VARIABLE: + var txt := "@%s · %s" % [table.var_name, table.var_type] + var l := Style.make_label(txt, Style.body(true), 12, Style.MUTED) + l.mouse_filter = MOUSE_FILTER_IGNORE + return l + return null + + +## "× @answer", "while @alive = 1", "until @done". +static func loop_rule(t: RollTable) -> String: + var e := t.loop_expr.strip_edges() + if e == "": + e = "?" + match t.loop_mode: + "while": + return "while " + e + "until": + return "until " + e + return "× " + e ## Card mode: "4 / 6 left" and a small Reshuffle link under the title. @@ -330,6 +487,9 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float row.custom_minimum_size = Vector2(0, 36) var h := _hbox(8) row.add_child(h) + # Loop rows and the Answer row of number/text choices are fixed: no number, + # weight or delete. + var fixed := table.kind == RollTable.KIND_LOOP or (table.kind == RollTable.KIND_CHOICE and table.choice != "pick") var num: Label = null if build and ranged: @@ -341,65 +501,67 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float r.add_child(_range_edit(e, false)) h.add_child(r) else: - num = Style.make_label(table.num_label(e, index), Style.display(true), 16, Style.MUTED) + num = Style.make_label("" if fixed else table.num_label(e, index), Style.display(true), 16, Style.MUTED) num.custom_minimum_size = Vector2(numw, 0) num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT num.size_flags_vertical = SIZE_SHRINK_CENTER + if fixed: + num.text = "↻" if table.kind == RollTable.KIND_LOOP and index == 0 else "→" + num.add_theme_font_override("font", Style.body_bold(true)) + num.add_theme_font_size_override("font_size", 14) h.add_child(num) var text: RichTextLabel = null if build: h.add_theme_constant_override("separation", 4) - var edit := LineEdit.new() - edit.text = e.text - edit.size_flags_horizontal = SIZE_EXPAND_FILL - edit.size_flags_vertical = SIZE_SHRINK_CENTER - edit.custom_minimum_size = Vector2(40, 0) - edit.add_theme_font_size_override("font_size", 15) - edit.text_changed.connect(func(s: String) -> void: - e.text = s - main.mark_dirty() - ) - h.add_child(edit) - if not ranged: + if table.kind == RollTable.KIND_CHOICE and table.choice != "pick": + var al := Style.make_label("Answer", Style.body_italic(true), 15, Style.MUTED) + al.size_flags_horizontal = SIZE_EXPAND_FILL + al.size_flags_vertical = SIZE_SHRINK_CENTER + al.tooltip_text = "Its effects and pipes run after the player answers ({answer} holds the answer)" + h.add_child(al) + else: + var edit := LineEdit.new() + edit.text = e.text + edit.size_flags_horizontal = SIZE_EXPAND_FILL + edit.size_flags_vertical = SIZE_SHRINK_CENTER + edit.custom_minimum_size = Vector2(40, 0) + edit.add_theme_font_size_override("font_size", 15) + if table.kind == RollTable.KIND_LOOP: + edit.placeholder_text = LOOP_ROWS[clampi(index, 0, 1)] + edit.tooltip_text = "%s: shown each pass ({i} is the pass number)" % LOOP_ROWS[0] if index == 0 else "%s: runs once when the loop ends" % LOOP_ROWS[1] + edit.text_changed.connect(func(s: String) -> void: + e.text = s + main.mark_dirty() + ) + h.add_child(edit) + if not ranged and not fixed: h.add_child(_weight_edit(e)) - var info := Button.new() - info.text = "i" - info.toggle_mode = true - info.button_pressed = _open_details.has(e.id) - info.tooltip_text = "Details shown when hovering this result" - info.custom_minimum_size = Vector2(22, 22) - info.size_flags_vertical = SIZE_SHRINK_CENTER - info.add_theme_font_override("font", Style.body_bold(true)) - info.add_theme_font_size_override("font_size", 13) - var has := e.details.strip_edges() != "" - var inn := Style.bordered(Style.box(Color(0, 0, 0, 0), 11), 1, Style.COPPER if has else Style.DASH) - var inh := Style.bordered(Style.box(Color("#e6dfcd"), 11), 1, Style.COPPER) - var inp := Style.bordered(Style.box(Style.LIT, 11), 1, Style.COPPER) - Style.skin_button(info, inn, inh, inp, Style.COPPER if has else Style.MUTED, Style.INK) - info.toggled.connect(func(on: bool) -> void: - if on: - _open_details[e.id] = true - else: - _open_details.erase(e.id) - rebuild() - ) - h.add_child(info) - var x := Button.new() - x.text = "×" - x.tooltip_text = "Delete this result" - x.custom_minimum_size = Vector2(22, 22) - x.size_flags_vertical = SIZE_SHRINK_CENTER - x.add_theme_font_size_override("font_size", 18) - Style.skin_button(x, Style.box(Color(0, 0, 0, 0), 5), Style.box(Color("#e6dfcd"), 5), Style.box(Color("#e6dfcd"), 5), Style.MUTED, Style.DANGER_INK) - x.pressed.connect(func() -> void: main.delete_entry(table.id, e.id)) - h.add_child(x) + h.add_child(_toggle_button("ƒ", "Effects: statements such as @hp -= 1 that run when this comes up", + _open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(e.effects).is_empty())) + h.add_child(_toggle_button("i", "Details shown when hovering this result", + _open_details, e.id, e.details.strip_edges() != "", false)) + if not fixed: + var x := Button.new() + x.text = "×" + x.tooltip_text = "Delete this result" + x.custom_minimum_size = Vector2(22, 22) + x.size_flags_vertical = SIZE_SHRINK_CENTER + x.add_theme_font_size_override("font_size", 18) + Style.skin_button(x, Style.box(Color(0, 0, 0, 0), 5), Style.box(Color("#e6dfcd"), 5), Style.box(Color("#e6dfcd"), 5), Style.MUTED, Style.DANGER_INK) + x.pressed.connect(func() -> void: main.delete_entry(table.id, e.id)) + h.add_child(x) else: + var col := _vbox(3) + col.size_flags_horizontal = SIZE_EXPAND_FILL + col.size_flags_vertical = SIZE_SHRINK_CENTER text = RichText.label(_row_text(e), 16, Style.INK, true) text.size_flags_horizontal = SIZE_EXPAND_FILL - text.size_flags_vertical = SIZE_SHRINK_CENTER RichText.hook_hover(text, main) - h.add_child(text) + col.add_child(text) + if e.effects.strip_edges() != "": + col.add_child(_effects_chip(e)) + 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) @@ -407,20 +569,284 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float h.add_child(pct) rows[e.id] = row - _row_parts[e.id] = {"num": num, "text": text, "entry": e} + _row_parts[e.id] = {"num": num, "text": text, "entry": e, "index": index} return row +const LOOP_ROWS := ["Each time", "Afterwards"] +## Longest effects summary shown on a Play-mode chip. +const CHIP_CHARS := 30 + + +## A small round toggle in a Build row ("i" details, "ƒ" effects). `open` is +## the dictionary of entry ids whose editor is shown. +func _toggle_button(glyph: String, tip: String, open: Dictionary, eid: String, has: bool, bad: bool) -> Button: + var b := Button.new() + b.text = glyph + b.toggle_mode = true + b.button_pressed = open.has(eid) + b.tooltip_text = tip + b.custom_minimum_size = Vector2(22, 22) + b.size_flags_vertical = SIZE_SHRINK_CENTER + b.add_theme_font_override("font", Style.body_bold(true)) + b.add_theme_font_size_override("font_size", 13) + var ring := Style.DANGER_INK if bad else (Style.COPPER if has else Style.DASH) + var inn := Style.bordered(Style.box(Color(0, 0, 0, 0), 11), 1, ring) + var inh := Style.bordered(Style.box(Color("#e6dfcd"), 11), 1, Style.COPPER) + var inp := Style.bordered(Style.box(Style.LIT, 11), 1, Style.COPPER) + Style.skin_button(b, inn, inh, inp, ring if (has or bad) else Style.MUTED, Style.INK) + b.toggled.connect(func(on: bool) -> void: + if on: + open[eid] = true + else: + open.erase(eid) + rebuild() + ) + return b + + ## Play-mode text of a row: the last rolled (expanded) text when the row is ## lit, otherwise the entry as written with its references shown readably. +## Loop rows read "Each time · …"; a number/text choice's row is its answer. func _row_text(e: TableEntry) -> String: var rolled := main.lit_text(table.id, e.id) var s := RichText.decorate(rolled) if rolled != "" else RichText.preview(e.text, main.data) + var muted := Style.MUTED.to_html(false) + if table.kind == RollTable.KIND_LOOP: + var index := table.entries.find(e) + var cap: String = LOOP_ROWS[clampi(index, 0, 1)] + var plain_text := Formatter.strip_tags(e.text).strip_edges() + if plain_text == "" or plain_text == cap: + s = "[b]%s[/b]" % cap + else: + s = "[color=#%s]%s ·[/color] %s" % [muted, cap, s] + elif table.kind == RollTable.KIND_CHOICE and table.choice != "pick": + if rolled != "": + s = "[color=#%s]Answer ·[/color] [b]%s[/b]" % [muted, RichText.decorate(rolled)] + else: + s = "[i][color=#%s]Answer[/color][/i]" % muted if e.details.strip_edges() != "": s += RichText.info_mark() return s +## Play mode: a subtle brass chip summarising an entry's effects ("STR = 2d6"). +func _effects_chip(e: TableEntry) -> Control: + var bad := not Effects.validate(e.effects).is_empty() + var chip := PanelContainer.new() + chip.mouse_filter = MOUSE_FILTER_PASS + chip.size_flags_horizontal = SIZE_SHRINK_BEGIN + var bg := Color(Style.DANGER_INK, 0.1) if bad else Color(Style.BRASS, 0.2) + var line := Color(Style.DANGER_INK, 0.4) if bad else Color(Style.BRASS_DARK, 0.3) + chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(bg, 5, [6, 0, 6, 1]), 1, line)) + var summary := effect_summary(e.effects, main.data) + # Cut long summaries by hand: a clipped Label would collapse to nothing. + if summary.length() > CHIP_CHARS: + summary = summary.substr(0, CHIP_CHARS - 1).strip_edges() + "…" + var l := Style.make_label(summary, Style.body(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK) + l.mouse_filter = MOUSE_FILTER_IGNORE + chip.add_child(l) + chip.tooltip_text = "\n".join(Effects.split(e.effects)) + return chip + + +## A short summary of effect text: the first two statements, with declared +## variables by their card's name ("STR = 2d6 · Terms += 1 · +3"). +static func effect_summary(text: String, board: TowerBoard) -> String: + var list := Effects.split(text) + var parts := PackedStringArray() + for k in mini(2, list.size()): + var st := Effects.parse_statement(list[k]) + if st.has("error"): + parts.append("⚠ " + list[k]) + continue + var target: String = st["target"] + var shown := target + if board != null and target.begins_with("@") and not target.ends_with("*"): + for t in board.tables: + if t.kind == RollTable.KIND_VARIABLE and t.var_name == target.substr(1): + shown = Formatter.strip_tags(t.name).strip_edges() + break + if st["op"] == "reset": + parts.append("reset " + shown) + else: + parts.append("%s %s %s" % [shown, st["op"], st["expr"]]) + if list.size() > 2: + parts.append("+%d" % (list.size() - 2)) + return " · ".join(parts) + + +## Build mode: the effects editor under a row, validated as you type. +func _effects_editor(e: TableEntry, left: float) -> Control: + var wrap := MarginContainer.new() + wrap.mouse_filter = MOUSE_FILTER_PASS + wrap.add_theme_constant_override("margin_left", int(left)) + wrap.add_theme_constant_override("margin_right", 12) + wrap.add_theme_constant_override("margin_top", 2) + wrap.add_theme_constant_override("margin_bottom", 6) + var v := _vbox(3) + wrap.add_child(v) + var te := TextEdit.new() + te.text = e.effects + te.placeholder_text = "@hp -= 1\n@gold += 2d6\nreset @loot" + te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY + te.custom_minimum_size = Vector2(0, 58) + te.scroll_fit_content_height = true + te.add_theme_font_override("font", Style.body(true)) + te.add_theme_font_size_override("font_size", 13) + te.add_theme_color_override("font_color", Style.INK) + te.add_theme_color_override("font_placeholder_color", Style.MUTED) + te.add_theme_color_override("caret_color", Style.INK) + te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55)) + var ok_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 4, 7, 4]), 1, Color(Style.BRASS_DARK, 0.4)) + var focus_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 4, 7, 4]), 1, Style.COPPER) + var bad_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 4, 7, 4]), 1, Style.DANGER_INK) + v.add_child(te) + var msg := Style.make_label("", Style.body(true), 12, Style.DANGER_INK) + msg.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + v.add_child(msg) + var check := func() -> void: + var problems := Effects.validate(te.text) + var lines := PackedStringArray() + for p: Dictionary in problems: + lines.append("⚠ %s: %s" % [p["src"], p["error"]]) + msg.text = "\n".join(lines) + msg.visible = not lines.is_empty() + te.add_theme_stylebox_override("normal", bad_box if not lines.is_empty() else ok_box) + te.add_theme_stylebox_override("focus", bad_box if not lines.is_empty() else focus_box) + te.text_changed.connect(func() -> void: + e.effects = te.text + check.call() + main.mark_dirty() + ) + check.call() + return wrap + + +## A sheet card's one row: the rendered template in Play, its editor in Build. +func _make_sheet_row(e: TableEntry, build: bool) -> Control: + var row := PanelContainer.new() + row.mouse_filter = MOUSE_FILTER_PASS + row.custom_minimum_size = Vector2(0, 36) + var v := _vbox(6) + row.add_child(v) + if build: + var te := TextEdit.new() + te.text = e.text + te.placeholder_text = "[b]Name[/b] {@name}\nHP {@hp} · Skills {@skill_*}" + te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY + te.custom_minimum_size = Vector2(0, 90) + te.scroll_fit_content_height = true + te.add_theme_font_override("font", Style.body(true)) + te.add_theme_font_size_override("font_size", 14) + te.add_theme_color_override("font_color", Style.INK) + te.add_theme_color_override("font_placeholder_color", Style.MUTED) + te.add_theme_color_override("caret_color", Style.INK) + te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55)) + te.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.RULE)) + te.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.COPPER)) + te.tooltip_text = "The sheet's template: BBCode with {@var}, {@prefix_*} and {= expr}" + te.text_changed.connect(func() -> void: + e.text = te.text + main.mark_dirty() + ) + v.add_child(te) + var tools := _hbox(4) + tools.add_child(_toggle_button("ƒ", "Effects that run when the chain reaches this sheet", + _open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(e.effects).is_empty())) + tools.add_child(_toggle_button("i", "Details shown when hovering the sheet", + _open_details, e.id, e.details.strip_edges() != "", false)) + var pv := Style.make_label("Preview on the board in Play", Style.body_italic(true), 12, Style.MUTED) + pv.size_flags_vertical = SIZE_SHRINK_CENTER + tools.add_child(pv) + v.add_child(tools) + _sheet_label = null + else: + _sheet_label = RichText.label("", 15, Style.INK, true) + _sheet_label.size_flags_horizontal = SIZE_EXPAND_FILL + RichText.hook_hover(_sheet_label, main) + v.add_child(_sheet_label) + row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id)) + rows[e.id] = row + _row_parts[e.id] = {"num": null, "text": null, "entry": e, "index": 0} + return row + + +## A variable card's body: its live value, big, and in Build its starting value +## and a reset button. +func _make_variable_body(build: bool) -> Control: + var wrap := MarginContainer.new() + wrap.mouse_filter = MOUSE_FILTER_PASS + wrap.add_theme_constant_override("margin_left", 14) + wrap.add_theme_constant_override("margin_right", 12) + wrap.add_theme_constant_override("margin_top", 6) + wrap.add_theme_constant_override("margin_bottom", 10) + var v := _vbox(2) + wrap.add_child(v) + _var_value = Style.make_label("", Style.display(true), 34, Style.INK) + _var_value.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + _var_value.mouse_filter = MOUSE_FILTER_PASS + v.add_child(_var_value) + _var_hint = Style.make_label("", Style.body(true), 12, Style.MUTED) + _var_hint.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + _var_hint.mouse_filter = MOUSE_FILTER_IGNORE + v.add_child(_var_hint) + if build: + var h := _hbox(8) + var start := Style.make_label("Starts at %s" % (table.initial if table.initial.strip_edges() != "" else ("0" if table.var_type == "number" else "nothing")), + Style.body(true), 12, Style.MUTED) + start.size_flags_horizontal = SIZE_EXPAND_FILL + start.size_flags_vertical = SIZE_SHRINK_CENTER + h.add_child(start) + var reset := Button.new() + reset.text = "↺ Reset" + reset.tooltip_text = "Set @%s back to its starting value" % table.var_name + reset.add_theme_font_override("font", Style.body(true)) + reset.add_theme_font_size_override("font_size", 12) + var n := Style.box(Color(0, 0, 0, 0), 5, [5, 0, 5, 1]) + var hv := Style.box(Color("#e6dfcd"), 5, [5, 0, 5, 1]) + Style.skin_button(reset, n, hv, hv, Style.COPPER, Style.INK) + reset.pressed.connect(func() -> void: main.reset_variable(table.var_name)) + h.add_child(reset) + v.add_child(h) + return wrap + + +## Re-renders the live parts (a variable's value, a sheet, a choice's +## question) from the current variables. Only touches labels whose text +## changed. Main calls it after rolls and edits, never per frame. +func refresh_live() -> void: + if is_instance_valid(_var_value): + var d := Roller.variable_display(main.data, main.persistent_vars, table) + var shown := str(d["text"]) if str(d["text"]) != "" else "—" + if _var_value.text != shown: + _var_value.text = shown + var size_px := 34 if shown.length() <= 8 else (24 if shown.length() <= 18 else 17) + _var_value.add_theme_font_size_override("font_size", size_px) + _var_value.add_theme_color_override("font_color", Style.INK if d["set"] else Style.MUTED) + var hint := "" + if str(d["error"]) != "": + hint = "⚠ " + str(d["error"]) + elif not d["set"]: + hint = "Not set yet · starts at this" + _var_hint.text = hint + _var_hint.add_theme_color_override("font_color", Style.DANGER_INK if str(d["error"]) != "" else Style.MUTED) + _var_hint.visible = hint != "" + if is_instance_valid(_sheet_label): + var s := RichText.decorate(Roller.render_sheet(main.data, main.persistent_vars, table)) + if _sheet_label.text != s: + _sheet_label.text = s + if is_instance_valid(_prompt_label): + var p: String + if main.mode == Main.Mode.BUILD: + p = RichText.preview(table.prompt, main.data) + else: + p = RichText.decorate(TextExpander.render(table.prompt, Roller.live_context(main.data, main.persistent_vars))) + if _prompt_label.text != p: + _prompt_label.text = p + _prompt_label.visible = table.prompt.strip_edges() != "" + + ## Weight on a plain table, shown as ×N. Also the number of copies in card mode. func _weight_edit(e: TableEntry) -> LineEdit: var edit := LineEdit.new() @@ -571,9 +997,12 @@ func _make_footer(ranged: bool) -> Control: wrap.add_theme_constant_override("margin_bottom", 10) var h := _hbox(8) wrap.add_child(h) - var add := _footer_button("+ Add range" if ranged else "+ Add result", Style.INK) - add.pressed.connect(func() -> void: main.add_entry(table.id)) - h.add_child(add) + # Loops, sheets, variables and number/text choices have fixed rows. + if table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and table.choice == "pick"): + var label := "+ Add range" if ranged else ("+ Add option" if table.kind == RollTable.KIND_CHOICE else "+ Add result") + var add := _footer_button(label, Style.INK) + add.pressed.connect(func() -> void: main.add_entry(table.id)) + h.add_child(add) var det := _footer_button("Details", Style.INK) det.tooltip_text = "Details shown when hovering the table's name" if table.details.strip_edges() != "": @@ -694,7 +1123,7 @@ func set_more_text(text: String) -> void: ## Updates highlights after a roll. Collapsed cards rebuild so the rolled result shows. func refresh_lit() -> void: update_deck() - if table.collapsed: + if is_collapsed(): var want: Array = [] for e in table.entries: if main.is_entry_lit(table.id, e.id): diff --git a/ui/table_settings_dialog.gd b/ui/table_settings_dialog.gd index 5e7b867..b6de055 100644 --- a/ui/table_settings_dialog.gd +++ b/ui/table_settings_dialog.gd @@ -29,13 +29,53 @@ var _ranged := false var _card_mode := false var _deck_empty := "reshuffle" +# Logic-card fields (docs/LOGIC.md), shown for the matching kind. +var _type_box: Control +var _card_box: Control +var _kind_problem: Label +var _choice := "pick" +var _choice_note: Label +var _prompt: LineEdit +var _save_as: LineEdit +var _min: LineEdit +var _max: LineEdit +var _minmax_row: Control +var _loop_mode := "times" +var _loop_expr: LineEdit +var _loop_note: Label +var _var_name: LineEdit +var _var_type := "number" +var _initial: LineEdit +var _template: TextEdit +var _template_preview: RichTextLabel + +const TITLES := { + RollTable.KIND_ROLL: "Table settings", + RollTable.KIND_CHOICE: "Choice settings", + RollTable.KIND_LOOP: "Loop settings", + RollTable.KIND_VARIABLE: "Variable settings", + RollTable.KIND_SHEET: "Sheet settings", +} +const CHOICE_LABELS := ["Which option", "How many", "Open ended"] +const LOOP_LABELS := ["Times", "While", "Until"] +const LOOP_NOTES := { + "times": "Runs Each time this many times (worked out once), then Afterwards. e.g. 3, @answer, 1d3", + "while": "Checks the condition before each pass and stops when it's false. e.g. @hp > 0", + "until": "Runs a pass, then stops once the condition is true (at least one pass). e.g. @gold >= 100", +} +const SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$" +const VAR_PATTERN := "^[a-z0-9_]+$" + func _init(p_table: RollTable = null) -> void: - super._init("Table settings", 560.0) + super._init(TITLES.get(p_table.kind, "Table settings") if p_table else "Table settings", 560.0) table = p_table _ranged = table.is_ranged() _card_mode = table.card_mode _deck_empty = table.deck_empty + _choice = table.choice + _loop_mode = table.loop_mode + _var_type = table.var_type _build() @@ -46,6 +86,7 @@ func _build() -> void: style_line_edit(_name) _name.text_changed.connect(func(_t: String) -> void: _refresh()) body.add_child(field("Name", _name)) + _build_kind() _details = TextEdit.new() _details.text = table.details @@ -114,6 +155,7 @@ func _build() -> void: _problem = note("", Style.WARN_INK) type_box.add_child(_problem) body.add_child(type_box) + _type_box = type_box var card_box := VBoxContainer.new() card_box.add_theme_constant_override("separation", 6) @@ -133,12 +175,19 @@ func _build() -> void: _deck_block = deck card_box.add_child(deck) body.add_child(card_box) + _card_box = card_box add_button("Close", "plain", close) add_button("Apply", "primary", _on_apply) _refresh() +func _ready() -> void: + super._ready() + # Now that the dialog sits in Main, the sheet preview can use its variables. + _refresh() + + func _tool_button(text: String, tip: String, on_press: Callable) -> Button: var b := make_button(text, "plain") b.tooltip_text = tip @@ -195,11 +244,179 @@ func _set_caret_at_offset(off: int) -> void: func settings() -> Dictionary: - return { + var s := { "name": _name.text, "details": _details.text, "tags": _tags.text, "ranged": _ranged, "dice": _dice.text.strip_edges(), "card_mode": _card_mode, "deck_empty": _deck_empty, } + match table.kind: + RollTable.KIND_CHOICE: + s["choice"] = _choice + s["prompt"] = _prompt.text + s["save_as"] = _save_as.text.strip_edges() + s["min"] = _min.text.strip_edges() + s["max"] = _max.text.strip_edges() + RollTable.KIND_LOOP: + s["loop_mode"] = _loop_mode + s["loop_expr"] = _loop_expr.text.strip_edges() + RollTable.KIND_VARIABLE: + s["var_name"] = _var_name.text.strip_edges().trim_prefix("@") + s["var_type"] = _var_type + s["initial"] = _initial.text.strip_edges() + RollTable.KIND_SHEET: + s["template"] = _template.text + return s + + +# ---------- Kind-specific fields ---------- + +func _build_kind() -> void: + var box := VBoxContainer.new() + box.add_theme_constant_override("separation", 10) + match table.kind: + RollTable.KIND_CHOICE: + box.add_child(section("Question type")) + box.add_child(segmented(CHOICE_LABELS, RollTable.CHOICES.find(_choice), func(i: int) -> void: + _choice = RollTable.CHOICES[i] + _refresh() + )) + _choice_note = note("") + box.add_child(_choice_note) + _prompt = LineEdit.new() + _prompt.text = table.prompt + _prompt.placeholder_text = "Which way out? You have {@gold} gold." + style_line_edit(_prompt) + _prompt.text_changed.connect(func(_t: String) -> void: _refresh()) + box.add_child(field("Question (BBCode, {@var} works)", _prompt)) + _save_as = LineEdit.new() + _save_as.text = table.save_as + _save_as.placeholder_text = "@name to keep, or a name for this roll" + style_line_edit(_save_as) + _save_as.text_changed.connect(func(_t: String) -> void: _refresh()) + box.add_child(field("Save the answer as (optional)", _save_as)) + var mm := HBoxContainer.new() + mm.add_theme_constant_override("separation", 12) + _min = LineEdit.new() + _min.text = table.min_expr + style_line_edit(_min) + _min.text_changed.connect(func(_t: String) -> void: _refresh()) + _max = LineEdit.new() + _max.text = table.max_expr + style_line_edit(_max) + _max.text_changed.connect(func(_t: String) -> void: _refresh()) + mm.add_child(field("Lowest", _min)) + mm.add_child(field("Highest", _max)) + for c in mm.get_children(): + (c as Control).size_flags_horizontal = SIZE_EXPAND_FILL + _minmax_row = mm + box.add_child(mm) + RollTable.KIND_LOOP: + box.add_child(section("Repeat")) + box.add_child(segmented(LOOP_LABELS, RollTable.LOOPS.find(_loop_mode), func(i: int) -> void: + _loop_mode = RollTable.LOOPS[i] + _refresh() + )) + _loop_expr = LineEdit.new() + _loop_expr.text = table.loop_expr + style_line_edit(_loop_expr) + _loop_expr.text_changed.connect(func(_t: String) -> void: _refresh()) + box.add_child(field("How many times / condition", _loop_expr)) + _loop_note = note("") + box.add_child(_loop_note) + RollTable.KIND_VARIABLE: + _var_name = LineEdit.new() + _var_name.text = table.var_name + _var_name.placeholder_text = "hp" + style_line_edit(_var_name) + _var_name.text_changed.connect(func(_t: String) -> void: _refresh()) + box.add_child(field("Variable name (used as @name)", _var_name)) + box.add_child(section("Type")) + box.add_child(segmented(["Number", "Text", "List"], RollTable.VAR_TYPES.find(_var_type), func(i: int) -> void: + _var_type = RollTable.VAR_TYPES[i] + _refresh() + )) + _initial = LineEdit.new() + _initial.text = table.initial + _initial.placeholder_text = "10, 2d6, or a word" + style_line_edit(_initial) + _initial.text_changed.connect(func(_t: String) -> void: _refresh()) + box.add_child(field("Starting value", _initial)) + box.add_child(note("reset @name, and Reset in the Variables tab, put it back to this.")) + RollTable.KIND_SHEET: + _template = TextEdit.new() + _template.text = table.entries[0].text if not table.entries.is_empty() else "" + _template.placeholder_text = "[b]{@name}[/b]\nHP {@hp} · Gold {@gold}\nSkills: {@skill_*}" + _template.custom_minimum_size.y = 120 + _template.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY + style_text_edit(_template) + _template.text_changed.connect(_refresh) + box.add_child(field("Template (BBCode with {@var}, {@prefix_*} and {= expr})", _template)) + _template_preview = RichTextLabel.new() + _template_preview.bbcode_enabled = true + _template_preview.fit_content = true + _template_preview.scroll_active = false + var pbox := PanelContainer.new() + pbox.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.05), 7, [10, 7, 10, 7])) + pbox.add_child(_template_preview) + box.add_child(pbox) + _: + return + _kind_problem = note("", Style.DANGER_INK) + box.add_child(_kind_problem) + body.add_child(box) + + +func _refresh_kind() -> void: + var s := settings() + var problems := kind_problems(table, s) + if _kind_problem: + _kind_problem.text = "\n".join(problems) + _kind_problem.visible = not problems.is_empty() + match table.kind: + RollTable.KIND_CHOICE: + _minmax_row.visible = _choice == "number" + var msg := "" + if _choice != table.choice and table.choice == "pick": + msg = "Only the first option is kept, as the Answer row (its effects and pipes stay)." + elif _choice != table.choice and _choice == "pick": + msg = "The Answer row becomes the first option; two more are added." + elif _choice == "pick": + msg = "The player picks one of the card's options, or Random." + else: + msg = "The answer goes in {answer}; the Answer row's effects and pipes run after it." + _choice_note.text = msg + _mark(_save_as, s["save_as"] == "" or _re(SAVE_PATTERN).search(s["save_as"]) != null) + _mark(_min, Expr.check(s["min"]) == "" and s["min"] != "") + _mark(_max, Expr.check(s["max"]) == "" and s["max"] != "") + RollTable.KIND_LOOP: + _loop_note.text = LOOP_NOTES.get(_loop_mode, "") + _mark(_loop_expr, s["loop_expr"] != "" and Expr.check(s["loop_expr"]) == "") + RollTable.KIND_VARIABLE: + _mark(_var_name, _re(VAR_PATTERN).search(s["var_name"]) != null) + _mark(_initial, _initial_error(s["initial"], _var_type) == "") + RollTable.KIND_SHEET: + var ctx := Roller.live_context(table_board(), _live_vars()) + _template_preview.text = RichText.decorate(TextExpander.render(_template.text, ctx)) if _template.text.strip_edges() != "" \ + else "[color=#69726b]Preview appears here.[/color]" + # The ranged/card-mode sections only apply to roll tables and pick choices. + var rolls := table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and _choice == "pick") + _type_box.visible = rolls + _card_box.visible = rolls + + +func _mark(le: LineEdit, ok: bool) -> void: + le.add_theme_color_override("font_color", Style.INK if ok else Style.DANGER_INK) + + +## The board and variables for the sheet preview, when the dialog sits in Main. +func table_board() -> TowerBoard: + var m := get_parent() as Main + return m.data if m else TowerBoard.new() + + +func _live_vars() -> Dictionary: + var m := get_parent() as Main + return m.persistent_vars if m else {} func _refresh() -> void: @@ -210,7 +427,7 @@ func _refresh() -> void: _dice_row.visible = _ranged _deck_block.visible = _card_mode var s := settings() - var dice_ok := not _ranged or Dice.is_valid_text(s["dice"]) + var dice_ok := not _ranged or dice_ok_text(s["dice"]) _dice.add_theme_color_override("font_color", Style.INK if dice_ok else Style.WARN_INK) var msgs := PackedStringArray() if _ranged and not table.is_ranged(): @@ -224,12 +441,14 @@ func _refresh() -> void: var problem := "" if not dice_ok: problem = "“%s” is not a valid dice expression." % s["dice"] - else: + elif _type_box == null or _type_box.visible: var clone := RollTable.from_dict(table.to_dict()) apply_settings(clone, s) problem = clone.range_problems() _problem.text = problem _problem.visible = problem != "" + if _type_box != null: + _refresh_kind() if is_inside_tree(): _fit() @@ -238,13 +457,117 @@ func _on_apply() -> void: var s := settings() var r := apply_settings(table, s) if not r["ok"]: - _problem.text = r["error"] - _problem.visible = true + if _kind_problem and not kind_problems(table, s).is_empty(): + _kind_problem.text = r["error"] + _kind_problem.visible = true + else: + _problem.text = r["error"] + _problem.visible = true return applied.emit(r) close() +## Problems with the kind-specific settings (empty when fine). +static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray: + var out := PackedStringArray() + match t.kind: + RollTable.KIND_CHOICE: + var save := str(s.get("save_as", t.save_as)).strip_edges() + if save != "" and _re(SAVE_PATTERN).search(save) == null: + out.append("Save as: use a name like career, or @career to keep it.") + if str(s.get("choice", t.choice)) == "number": + for k in [["min", "Lowest"], ["max", "Highest"]]: + var src := str(s.get(k[0], "")).strip_edges() + var err := Expr.check(src) if src != "" else "it's empty" + if err != "": + out.append("%s: %s" % [k[1], err]) + RollTable.KIND_LOOP: + var src := str(s.get("loop_expr", t.loop_expr)).strip_edges() + if src == "": + out.append("The loop needs a count or a condition.") + elif Expr.check(src) != "": + out.append("Loop rule: " + Expr.check(src)) + RollTable.KIND_VARIABLE: + var n := str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@") + if _re(VAR_PATTERN).search(n) == null: + out.append("Variable name: lowercase letters, digits and _ only.") + var err := _initial_error(str(s.get("initial", t.initial)), str(s.get("var_type", t.var_type))) + if err != "": + out.append("Starting value: " + err) + return out + + +static func _initial_error(src: String, type: String) -> String: + src = src.strip_edges() + if src == "": + return "" + if type != "number" and RollTable._looks_literal(src): + return "" + return Expr.check(src) + + +static func _re(pattern: String) -> RegEx: + return RegEx.create_from_string(pattern) + + +## Dice text for a ranged table: plain dice (2d6) or an expression that uses a +## variable, dice or a function ("2d6 + dm(@end)", "@terms"). A lone word +## such as "banana" is not accepted. +static func dice_ok_text(text: String) -> bool: + var s := text.strip_edges() + if Dice.is_valid_text(s): + return true + if s == "" or Expr.check(s) != "": + return false + return _re("^[A-Za-z_][A-Za-z0-9_]*$").search(s) == null + + +## 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. +static func _apply_kind(t: RollTable, s: Dictionary) -> void: + match t.kind: + RollTable.KIND_CHOICE: + var c := str(s.get("choice", t.choice)) + if RollTable.CHOICES.has(c) and c != t.choice: + if c == "pick": + if not t.entries.is_empty(): + t.entries[0].text = "Option 1" + for n in range(t.entries.size() + 1, 4): + t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Option %d" % n)) + else: + while t.entries.size() > 1: + t.entries.remove_at(t.entries.size() - 1) + if t.entries.is_empty(): + t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Answer")) + t.entries[0].text = "Answer" + t.entries[0].has_range = false + t.card_mode = false + t.choice = c + t.prompt = str(s.get("prompt", t.prompt)) + t.save_as = str(s.get("save_as", t.save_as)).strip_edges() + if t.choice == "number": + t.min_expr = str(s.get("min", t.min_expr)).strip_edges() + t.max_expr = str(s.get("max", t.max_expr)).strip_edges() + RollTable.KIND_LOOP: + var m := str(s.get("loop_mode", t.loop_mode)) + if RollTable.LOOPS.has(m): + t.loop_mode = m + t.loop_expr = str(s.get("loop_expr", t.loop_expr)).strip_edges() + RollTable.KIND_VARIABLE: + t.var_name = str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@") + var vt := str(s.get("var_type", t.var_type)) + if RollTable.VAR_TYPES.has(vt): + t.var_type = vt + t.initial = str(s.get("initial", t.initial)).strip_edges() + RollTable.KIND_SHEET: + if s.has("template"): + if t.entries.is_empty(): + t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "")) + t.entries[0].text = str(s["template"]) + + # ---------- Pure editing logic ---------- ## Wraps text[sel.x:sel.y] in open/close_tag. With an empty range, inserts the @@ -281,9 +604,17 @@ static func extra_pipe_count(t: RollTable) -> int: ## 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: + var problems := kind_problems(t, s) + if not problems.is_empty(): + return {"ok": false, "error": "\n".join(problems), "deck_reset": false} var ranged: bool = s.get("ranged", false) + # Only roll tables and pick choices can be ranged or dealt as cards. + var choice := str(s.get("choice", t.choice)) + var rolls := t.kind == RollTable.KIND_ROLL or (t.kind == RollTable.KIND_CHOICE and choice == "pick") + if not rolls: + ranged = false var dice := str(s.get("dice", t.dice)).strip_edges() - if ranged and not Dice.is_valid_text(dice): + if ranged and not dice_ok_text(dice): return {"ok": false, "error": "“%s” is not a valid dice expression." % dice, "deck_reset": false} var was_ranged := t.is_ranged() var old_dice := t.dice @@ -293,7 +624,7 @@ static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary: t.name = new_name t.details = str(s.get("details", t.details)) t.tags = parse_tags(str(s.get("tags", ""))) - t.card_mode = bool(s.get("card_mode", t.card_mode)) + t.card_mode = bool(s.get("card_mode", t.card_mode)) and rolls t.deck_empty = "stop" if str(s.get("deck_empty", t.deck_empty)) == "stop" else "reshuffle" if ranged: t.dice = dice @@ -301,6 +632,7 @@ static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary: assign_ranges(t) elif was_ranged: drop_ranges(t) + _apply_kind(t, s) var deck_reset := was_ranged != ranged or old_card != t.card_mode or (ranged and old_dice != t.dice) return {"ok": true, "error": "", "deck_reset": deck_reset} diff --git a/ui/variables_panel.gd b/ui/variables_panel.gd index 7b296d8..fb94874 100644 --- a/ui/variables_panel.gd +++ b/ui/variables_panel.gd @@ -1,20 +1,24 @@ class_name VariablesPanel extends VBoxContainer -## The Variables tab of the result tray: the collection's persistent variables -## ({@name}), each editable, re-rollable from the table that set it, or -## clearable, and below them the last roll's chain variables (read only). +## The Variables tab of the result tray: every board variable ({@name}) — the +## ones that are set and the ones variable cards declare — each editable, and +## clearable or resettable. Text a roll table gave can be re-rolled from that +## table. "Reset all…" puts everything back to its starting value after an +## in-app confirmation. Below them, the last roll's chain variables (read +## only). -const HEIGHT := 132.0 +const HEIGHT := 112.0 var main: Main var _list: VBoxContainer +var _reset_all: Button var _field: StyleBoxFlat var _field_focus: StyleBoxFlat func setup(p_main: Main) -> void: main = p_main - add_theme_constant_override("separation", 0) + add_theme_constant_override("separation", 6) _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() @@ -25,20 +29,40 @@ func setup(p_main: Main) -> void: _list.add_theme_constant_override("separation", 5) _list.size_flags_horizontal = SIZE_EXPAND_FILL scroll.add_child(_list) + var foot := HBoxContainer.new() + foot.alignment = BoxContainer.ALIGNMENT_END + add_child(foot) + _reset_all = Button.new() + _reset_all.text = "Reset all…" + _reset_all.tooltip_text = "Put every variable back to its starting value (variables without a card are cleared)" + _reset_all.add_theme_font_size_override("font_size", 13) + var n := Style.bordered(Style.box(Color(1, 1, 1, 0.04), 6, [10, 2, 10, 3]), 1, Color(1, 1, 1, 0.12)) + var h := Style.bordered(Style.box(Color(1, 1, 1, 0.1), 6, [10, 2, 10, 3]), 1, Color(Style.DANGER, 0.6)) + Style.skin_button(_reset_all, n, h, h, Style.ON_FELT_MUTED, Style.ON_FELT) + _reset_all.pressed.connect(confirm_reset_all) + foot.add_child(_reset_all) + + +## Opens the "Reset all variables?" confirmation. +func confirm_reset_all() -> ModalCard: + var msg := "Every variable goes back to its starting value, and variables without a variable card are cleared. This can't be undone." + var d := ModalCard.confirm("Reset all variables?", msg, "Reset all", main.reset_all_variables, true) + main.add_child(d) + return d func render() -> void: for c in _list.get_children(): _list.remove_child(c) c.queue_free() - var names: Array = main.persistent_vars.keys() - names.sort_custom(func(a: Variant, b: Variant) -> bool: return str(a).naturalnocasecmp_to(str(b)) < 0) + var names := main.variable_names() + _reset_all.disabled = names.is_empty() if names.is_empty(): - var empty := RichText.label("No saved variables yet. A pipe that saves as [color=#%s]@name[/color], or [lb][lb]Table -> @name]] in a result, keeps its value here." % Style.BRASS.to_html(false), + var empty := RichText.label("No saved variables yet. A pipe that saves as [color=#%s]@name[/color], an effect such as [color=#%s]@hp = 10[/color], or [lb][lb]Table -> @name]] in a result, keeps its value here." % [Style.BRASS.to_html(false), Style.BRASS.to_html(false)], 14, Style.ON_FELT_MUTED, false) _list.add_child(empty) for n in names: - _list.add_child(_var_row(str(n))) + _list.add_child(_var_row(n)) var chain: Dictionary = main.current.get("chain_vars", {}) if not chain.is_empty(): @@ -51,36 +75,49 @@ func render() -> void: var keys: Array = chain.keys() keys.sort() for k in keys: - var line := RichText.label("[color=#%s]{%s}[/color] %s" % [RichText.VAR_INK_FELT.to_html(false), k, str(chain[k])], + var line := RichText.label("[color=#%s]{%s}[/color] %s" % [RichText.VAR_INK_FELT.to_html(false), k, Expr.format_value(chain[k])], 14, Style.ON_FELT, false) _list.add_child(line) +## Shown text of a variable's value ("" when it isn't set). +func _value_text(name: String) -> String: + var raw: Variant = main.persistent_vars.get(name) + if raw == null: + return "" + var v: Variant = (raw as Dictionary).get("value", "") if raw is Dictionary else raw + return Expr.format_value(v) + + func _var_row(name: String) -> Control: - var v: Dictionary = main.persistent_vars[name] if main.persistent_vars[name] is Dictionary else {"value": str(main.persistent_vars[name])} + var is_set := main.persistent_vars.has(name) + var card := main.variable_card(name) var row := HBoxContainer.new() row.add_theme_constant_override("separation", 6) var label := Style.make_label("@" + name, Style.body_bold(), 14, RichText.VAR_INK_FELT) label.custom_minimum_size = Vector2(84, 0) label.clip_text = true label.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS - label.tooltip_text = "{@%s}" % name + label.tooltip_text = "{@%s}%s" % [name, (" · " + Formatter.strip_tags(card.name)) if card else ""] label.size_flags_vertical = SIZE_SHRINK_CENTER row.add_child(label) var edit := LineEdit.new() - edit.text = str(v.get("value", "")) + edit.text = _value_text(name) edit.size_flags_horizontal = SIZE_EXPAND_FILL edit.custom_minimum_size = Vector2(60, 0) edit.add_theme_font_size_override("font_size", 14) edit.add_theme_color_override("font_color", Style.ON_FELT) edit.add_theme_color_override("caret_color", Style.ON_FELT) edit.add_theme_color_override("selection_color", Color(Style.BRASS, 0.4)) + edit.add_theme_color_override("font_placeholder_color", Color(Style.ON_FELT_MUTED, 0.7)) edit.add_theme_stylebox_override("normal", _field) edit.add_theme_stylebox_override("focus", _field_focus) + if not is_set and card: + edit.placeholder_text = "not set · starts at %s" % (card.initial if card.initial != "" else "0") edit.tooltip_text = "Edit the value (BBCode ok); Enter to save" var commit := func() -> void: - if main.persistent_vars.has(name) and edit.text != str((main.persistent_vars[name] as Dictionary).get("value", "")): + if edit.text != _value_text(name) and (main.persistent_vars.has(name) or edit.text != ""): main.set_variable(name, edit.text) edit.text_submitted.connect(func(_t: String) -> void: commit.call() @@ -88,13 +125,21 @@ func _var_row(name: String) -> Control: edit.focus_exited.connect(commit) row.add_child(edit) - var source := str(v.get("source", "")) - var st := main.data.get_table(source) if source != "" else null - var again := _icon_button("↻", "Re-roll from %s" % Formatter.strip_tags(st.name) if st else "No table to re-roll from") - again.disabled = st == null - again.pressed.connect(func() -> void: main.reroll_variable(name)) - row.add_child(again) + if card: + var reset := _icon_button("↺", "Reset @%s to its starting value" % name) + reset.pressed.connect(func() -> void: main.reset_variable(name)) + row.add_child(reset) + else: + var v: Variant = main.persistent_vars.get(name) + var source := str(v.get("source", "")) if v is Dictionary else "" + var st := main.data.get_table(source) if source != "" else null + var can := main.can_reroll_variable(name) + var again := _icon_button("↻", ("Re-roll from %s" % Formatter.strip_tags(st.name)) if can else "Set by an effect or answer; no table to re-roll from") + again.disabled = not can + again.pressed.connect(func() -> void: main.reroll_variable(name)) + row.add_child(again) var clear := _icon_button("×", "Clear {@%s}" % name) + clear.disabled = not is_set clear.pressed.connect(func() -> void: main.clear_variable(name)) row.add_child(clear) return row