diff --git a/core/builder.gd b/core/builder.gd index 251541e..7cf0810 100644 --- a/core/builder.gd +++ b/core/builder.gd @@ -10,7 +10,9 @@ extends RefCounted ## ## Effect model: {"ok": true, "op", "var", "amount"} ## op "set" (=), "add" (+=), "subtract" (-=), "multiply" (*=), -## "divide" (/=), "reset", "append" (+= "text"), "remove" (-= "text") +## "divide" (/=), "reset", "append" (+= "text"), "remove" (-= "text"), +## and for scale values "step_up", "step_down", "toward", +## "at_least", "at_most" (BuilderScales; step_up/down need `board`) ## var "@name", a chain name ("name"), "@prefix_*" (reset only) or ## "@[expr]" (indirect, e.g. "@[option]") ## amount String: the expression as written ("1", "2d6", "\"Aslan\"", @@ -42,7 +44,13 @@ static var _num_re: RegEx = null ## Parses one effect statement into a model, or {"ok": false, "error"} when ## it doesn't fit (a parse error, or an amount that isn't an expression). -static func parse_effect(stmt: String) -> Dictionary: +## With `board`, += / -= on a scale value read as step_up / step_down. +static func parse_effect(stmt: String, board: TowerBoard = null) -> Dictionary: + var m := _parse_effect(stmt) + return BuilderScales.refine(m, m.get("ok", false) and BuilderScales.is_scale(str(m["var"]), board)) + + +static func _parse_effect(stmt: String) -> Dictionary: var src := stmt.strip_edges() if src == "": return {"ok": false, "error": "Empty statement"} @@ -85,6 +93,8 @@ static func effect_text(m: Dictionary) -> String: var amount := str(m.get("amount", "")).strip_edges() if m.get("amount") != null else "" if v == "": return "" + if BuilderScales.OPS.has(op): + return BuilderScales.text(op, v, amount) match op: "reset": return "reset " + v @@ -98,10 +108,10 @@ static func effect_text(m: Dictionary) -> String: ## Every statement of an effects field as a model (ok or not), in order. -static func parse_effects(text: String) -> Array[Dictionary]: +static func parse_effects(text: String, board: TowerBoard = null) -> Array[Dictionary]: var out: Array[Dictionary] = [] for s in Effects.split(text): - var m := parse_effect(s) + var m := parse_effect(s, board) m["src"] = s out.append(m) return out @@ -365,7 +375,7 @@ static func quote(s: String) -> String: ## name (the first source wins). ## name "@luck" (board value), "@skill_*" (a collection), "tier" (chain) ## label Describe.label(name, board) -## kind "number", "text", "list" or "collection" +## kind "number", "text", "list", "collection" or "scale" ## source "variable" (a variable card), "collection", "effect" (an effect ## target), "save_as" (a pipe's or choice's save_as, or ## [[Table -> name]]), "input" (a card input), "read" (only read by diff --git a/core/builder_scales.gd b/core/builder_scales.gd new file mode 100644 index 0000000..be2b9f4 --- /dev/null +++ b/core/builder_scales.gd @@ -0,0 +1,64 @@ +class_name BuilderScales +extends RefCounted +## The scale forms of Builder's effect model (Scales, docs/PLAIN.md §2): +## step_up @climate += 1 (amount "1") +## step_down @climate -= 2 (amount "2") +## toward @climate = toward(@climate, "Temperate") (amount "Temperate") +## at_least @atmo = max(@atmo, "Medium") (amount "Medium") +## at_most @atmo = min(@atmo, "Thin") (amount "Thin") +## step_up/step_down are += / -= on a value a scale card declares, so they +## need the board (or the caller's word) to tell them apart from add/subtract; +## the other three are read from the text alone. Their amount is the step's +## name without quotes, like append/remove. + +const OPS: Array[String] = ["step_up", "step_down", "toward", "at_least", "at_most"] +const _FNS := {"toward": "toward", "at_least": "max", "at_most": "min"} +const _OP_OF := {"toward": "toward", "max": "at_least", "min": "at_most"} + + +## True when `v` ("@climate") is declared by a scale card on `board`. +static func is_scale(v: String, board: TowerBoard) -> bool: + return card_for(v, board) != null + + +## The scale card that declares `v` ("@climate"), or null. +static func card_for(v: String, board: TowerBoard) -> RollTable: + if board == null or not v.begins_with("@"): + return null + var n := v.substr(1).to_lower() + for t in board.tables: + if t.is_scale() and t.var_name == n: + return t + return null + + +## A model with its scale form read: a "set" of toward/max/min(, "Step") becomes toward/at_least/at_most, and add/subtract on a +## scale (`scale` true) becomes step_up/step_down. Anything else as it is. +static func refine(m: Dictionary, scale: bool) -> Dictionary: + if not m.get("ok", false): + return m + var op := str(m["op"]) + var v := str(m["var"]) + if op == "set": + var t := Builder.tokens(str(m["amount"])) + if t.size() == 6 and t[0]["t"] == "name" and _OP_OF.has(t[0]["s"]) and t[1]["s"] == "(" and t[2]["t"] == "var" \ + and t[2]["s"] == v and t[3]["s"] == "," and t[4]["t"] == "str" and t[5]["s"] == ")": + return {"ok": true, "op": _OP_OF[t[0]["s"]], "var": v, "amount": Builder.unquote(str(t[4]["s"]))} + elif scale and (op == "add" or op == "subtract"): + return {"ok": true, "op": "step_up" if op == "add" else "step_down", "var": v, "amount": str(m["amount"])} + return m + + +## The statement for a scale model, or "" when it isn't one (or not filled in). +static func text(op: String, v: String, amount: String) -> String: + if amount == "": + return "" + match op: + "step_up": + return "%s += %s" % [v, amount] + "step_down": + return "%s -= %s" % [v, amount] + "toward", "at_least", "at_most": + return "%s = %s(%s, %s)" % [v, _FNS[op], v, Builder.quote(amount)] + return "" diff --git a/core/builder_scales.gd.uid b/core/builder_scales.gd.uid new file mode 100644 index 0000000..621ce90 --- /dev/null +++ b/core/builder_scales.gd.uid @@ -0,0 +1 @@ +uid://1opb4bav6ao2 diff --git a/core/describe.gd b/core/describe.gd index fc83295..d499e05 100644 --- a/core/describe.gd +++ b/core/describe.gd @@ -55,9 +55,10 @@ static func label(name: String, board: TowerBoard) -> String: ## Label table for a board: {"vars": {name: label}, "stems": [[stem, label]] -## longest first, "inputs": {name: label}}. +## longest first, "inputs": {name: label}, "scales": {name: steps}}. static func _labels(board: TowerBoard) -> Dictionary: var vars := {} + var scales := {} var stems: Array = [] var inputs := {} if board != null: @@ -68,12 +69,14 @@ static func _labels(board: TowerBoard) -> Dictionary: stems.append([t.var_name, lab if lab != "" else RollContext.pretty_name(t.var_name)]) elif lab != "" and not vars.has(t.var_name): vars[t.var_name] = lab + if t.is_scale() and not scales.has(t.var_name): + scales[t.var_name] = t.steps for inp: Dictionary in t.inputs: var il := str(inp.get("label", "")).strip_edges() if il != "" and not inputs.has(str(inp.get("name", ""))): inputs[str(inp.get("name", ""))] = il stems.sort_custom(func(a: Array, b: Array) -> bool: return str(a[0]).length() > str(b[0]).length()) - return {"vars": vars, "stems": stems, "inputs": inputs} + return {"vars": vars, "stems": stems, "inputs": inputs, "scales": scales} static func _label(name: String, L: Dictionary) -> String: @@ -139,6 +142,11 @@ static func _effect(stmt: String, L: Dictionary, table: RollTable) -> String: return src var v := str(m["var"]) var subj := _chosen(table, L) if v.begins_with("@[") else _label(v, L) + var steps: Variant = _steps(v, L) + if steps != null: + var sc := DescribeScales.effect(BuilderScales.refine(m, true), subj, steps, func(a: String) -> String: return _expr(a, L)) + if sc != "": + return _short(sc, src) var amount := str(m["amount"]) var out := "" match str(m["op"]): @@ -229,7 +237,16 @@ static func _clause(c: Dictionary, L: Dictionary) -> String: return subj + " is not set" "has": return "%s include %s" % [subj, _value(str(c["value"]), L)] - return "%s %s" % [subj, _tail(cmp, str(c["value"]), L)] + var value := str(c["value"]) + var steps: Variant = _steps(str(c["var"]), L) + if steps != null and value.is_valid_int(): + value = Builder.quote(Scales.label_at(steps, int(value))) + return "%s %s" % [subj, _tail(cmp, value, L)] + + +## The steps of a scale value ("@climate"), or null when it isn't one. +static func _steps(v: String, L: Dictionary) -> Variant: + return L.get("scales", {}).get(v.trim_prefix("@").to_lower()) if v.begins_with("@") else null ## The comparison after a value name: "is 8 or more", "is at most 3", "is @@ -356,10 +373,6 @@ static func _expr(expr: String, L: Dictionary) -> String: return _short(out, src) - - - - # ---------------------------------------------------------------- helpers ## `s`, or when it's too long the original text (if that's shorter) or a cut. diff --git a/core/describe_scales.gd b/core/describe_scales.gd new file mode 100644 index 0000000..4c8f80f --- /dev/null +++ b/core/describe_scales.gd @@ -0,0 +1,42 @@ +class_name DescribeScales +extends RefCounted +## Scale values in plain words (Describe, Scales): "Climate 1 step up", +## "Climate 2 steps down", "Climate = Hot", "Climate 1 step toward +## Temperate", "Atmosphere at least Medium", "Atmosphere at most Thin". A +## step's number in a rule reads as its name ("@climate = 2" -> "Climate = +## Cold"). + + +## The phrase for a scale model (BuilderScales.refine'd), or "" when the op +## isn't a scale one. `steps` are the value's steps; `expr` turns an amount +## expression into words (Describe._expr). +static func effect(m: Dictionary, subj: String, steps: Array, expr: Callable) -> String: + var amount := str(m["amount"]) + match str(m["op"]): + "step_up", "step_down": + var up: bool = m["op"] == "step_up" + if amount.is_valid_int(): + var n := int(amount) + if n < 0: + up = not up + n = -n + return "%s %d %s %s" % [subj, n, "step" if n == 1 else "steps", "up" if up else "down"] + return "%s %s steps %s" % [subj, expr.call(amount), "up" if up else "down"] + "set": + return "%s = %s" % [subj, step_word(amount, steps, expr)] + "toward": + return "%s 1 step toward %s" % [subj, amount] + "at_least": + return "%s at least %s" % [subj, amount] + "at_most": + return "%s at most %s" % [subj, amount] + return "" + + +## A value token beside a scale in words: a whole number reads as the step at +## that position ("2" -> "Cold"), anything else through `expr`. +static func step_word(tok: String, steps: Array, expr: Callable) -> String: + var s := tok.strip_edges() + if s.is_valid_int() and not steps.is_empty(): + return Scales.label_at(steps, int(s)) + return str(expr.call(s)) diff --git a/core/describe_scales.gd.uid b/core/describe_scales.gd.uid new file mode 100644 index 0000000..40332a6 --- /dev/null +++ b/core/describe_scales.gd.uid @@ -0,0 +1 @@ +uid://coan7bjrmhx7n diff --git a/core/roll_table.gd b/core/roll_table.gd index f472399..7403955 100644 --- a/core/roll_table.gd +++ b/core/roll_table.gd @@ -178,6 +178,7 @@ static func create(p_kind: String, p_id: String, p_name: String, sub: String = " if t.var_type == VAR_COLLECTION and t.var_name.length() > 3 and t.var_name.ends_with("s") and not t.var_name.ends_with("ss"): t.var_name = t.var_name.substr(0, t.var_name.length() - 1) t.initial = "0" if t.var_type == "number" else "" + if t.var_type == VAR_SCALE: t.steps.assign(["Low", "Medium", "High"]); t.initial = "Low" KIND_SHEET: t.entries.append(TableEntry.new("e1", "[b]%s[/b]" % p_name)) KIND_ROUTER: diff --git a/help/topics.txt b/help/topics.txt index 967a9f8..eb28e13 100644 --- a/help/topics.txt +++ b/help/topics.txt @@ -139,6 +139,18 @@ A spread can remember [b]values[/b] between rolls, such as Luck, Gold or the cur ## Conditions Conditions are used by Only if threads, branches, repeats and Show only if. In plain words they read "Luck is at least 2". As text: `@luck >= 2`, `@town = "Saltmere"`, `@gold > 0 and @luck < 3`. +# Scales +A [b]Scale[/b] is a value that moves along steps in order, lowest first, such as a Climate that runs [b]Supercold, Cold, Temperate, Hot, Superhot[/b]. Add one with [b]+ Card ▾ → Scale (ordered steps)[/b], then list its steps, one per line, and pick the step it starts at. The card shows the current step, and the row of steps under it shows where that sits. +- Changes move it a step at a time and stop at the ends, so a result such as [i]Unexpectedly warmer[/i] can say [b]Climate 1 step up[/b]. Other changes: [b]Climate 2 steps down[/b], [b]Set Climate to Hot[/b], [b]Climate 1 step toward Temperate[/b], [b]Atmosphere at least Medium[/b] (raises it if it's lower) and [b]Atmosphere at most Thin[/b] (lowers it if it's higher). +- Conditions compare steps by their order: a thread can go [b]only if Atmosphere is at least Thin[/b], which is true for Thin and every step above it. +- Text shows the step's name: `{@climate}` reads "Cold". + +## Writing scales as text +- `@climate += 1` and `@climate -= 1` move it, `@climate = "Hot"` sets it. +- `@climate = toward(@climate, "Temperate")` moves it one step toward Temperate. +- `@atmo = max(@atmo, "Medium")` raises it to at least Medium; `min` lowers it to at most. +- `@atmo >= "Thin"` is a condition. + # Logic cards Besides roll tables and choices, [b]+ Card ▾[/b] adds: - [b]Check card[/b]: rolls dice plus a modifier against a target, such as 2d6 + Skill against 8, and follows its Success or Failure result. diff --git a/tests/test_builder.gd b/tests/test_builder.gd index 5016723..6dd0577 100644 --- a/tests/test_builder.gd +++ b/tests/test_builder.gd @@ -13,6 +13,7 @@ func _init() -> void: _test_condition_round_trips() _test_condition_not_ok() _test_known_values() + _test_scales() finish() @@ -204,3 +205,46 @@ func _test_known_values() -> void: _check(not by.has("i") and not by.has("option"), "no loop, no dynamic pick") _check(not by.has("@[option]") and not by.has("@x_*"), "no indirect or prefix targets") _eq(Builder.known_values(null), [] as Array[Dictionary], "null spread") + + +# ---------------------------------------------------------------- scales + +func _scale_board() -> TowerBoard: + var b := TowerBoard.new() + var c := RollTable.create(RollTable.KIND_VARIABLE, "v_climate", "Climate", RollTable.VAR_SCALE) + c.steps.assign(["Supercold", "Cold", "Temperate", "Hot", "Superhot"]) + b.tables.append(c) + return b + + +func _test_scales() -> void: + var b := _scale_board() + _eq(Builder.parse_effect("@climate += 1", b), {"ok": true, "op": "step_up", "var": "@climate", "amount": "1"}, "step up on a scale") + _eq(Builder.parse_effect("@climate -= 2", b), {"ok": true, "op": "step_down", "var": "@climate", "amount": "2"}, "step down") + _eq(Builder.parse_effect("@climate += 1"), {"ok": true, "op": "add", "var": "@climate", "amount": "1"}, "without the board it's add") + _eq(Builder.parse_effect("@luck += 1", b), {"ok": true, "op": "add", "var": "@luck", "amount": "1"}, "not a scale: add") + _eq(Builder.parse_effect("@climate = \"Hot\"", b), {"ok": true, "op": "set", "var": "@climate", "amount": "\"Hot\""}, "set a step") + _eq(Builder.parse_effect("@climate = toward(@climate, \"Temperate\")"), + {"ok": true, "op": "toward", "var": "@climate", "amount": "Temperate"}, "toward") + _eq(Builder.parse_effect("@atmo = max(@atmo, \"Medium\")"), {"ok": true, "op": "at_least", "var": "@atmo", "amount": "Medium"}, "at least") + _eq(Builder.parse_effect("@atmo = min(@atmo, 'Thin')"), {"ok": true, "op": "at_most", "var": "@atmo", "amount": "Thin"}, "at most") + _eq(Builder.parse_effect("@atmo = max(@other, \"Medium\")")["op"], "set", "max of another value stays set") + _eq(Builder.parse_effect("@atmo = max(@atmo, 0)")["op"], "set", "max with a number stays set") + _eq(Builder.effect_text({"op": "toward", "var": "@climate", "amount": "Temperate"}), "@climate = toward(@climate, \"Temperate\")", "toward text") + _eq(Builder.effect_text({"op": "step_down", "var": "@climate", "amount": "1"}), "@climate -= 1", "step down text") + _eq(Builder.effect_text({"op": "at_most", "var": "@climate", "amount": ""}), "", "no step: no text") + for m: Dictionary in [ + {"ok": true, "op": "step_up", "var": "@climate", "amount": "1"}, + {"ok": true, "op": "step_down", "var": "@climate", "amount": "3"}, + {"ok": true, "op": "toward", "var": "@climate", "amount": "Temperate"}, + {"ok": true, "op": "at_least", "var": "@climate", "amount": "Cold"}, + {"ok": true, "op": "at_most", "var": "@climate", "amount": "Semi-arid"}, + {"ok": true, "op": "set", "var": "@climate", "amount": "\"Hot\""}]: + _eq(Builder.parse_effect(Builder.effect_text(m), b), m, "scale round trip " + str(m["op"])) + var kinds := {} + for k: Dictionary in Builder.known_values(b): + kinds[k["name"]] = k["kind"] + _eq(kinds.get("@climate"), "scale", "known_values: a scale card's kind is scale") + var fresh := RollTable.create(RollTable.KIND_VARIABLE, "s", "Mood", RollTable.VAR_SCALE) + _eq(fresh.steps, ["Low", "Medium", "High"], "a new scale gets default steps") + _eq(fresh.initial, "Low", "and starts at the first") diff --git a/tests/test_describe.gd b/tests/test_describe.gd index ee4d86a..ddcdb18 100644 --- a/tests/test_describe.gd +++ b/tests/test_describe.gd @@ -18,6 +18,7 @@ func _init() -> void: _test_why_from_rolls() _test_fallbacks() _test_rules_view() + _test_scales() finish() @@ -341,3 +342,26 @@ func _test_rules_view() -> void: _eq(StateStore.new(dir).rules_view(), "text", "kept in the state file") st.set_rules_view("plain") st.save() + + +# ---------------------------------------------------------------- scales + +func _test_scales() -> void: + var b := _board() + var c := _var_card("v_climate", "Climate", "climate", RollTable.VAR_SCALE) + c.steps.assign(["Supercold", "Cold", "Temperate", "Hot", "Superhot"]) + b.tables.append(c) + var a := _var_card("v_atmo", "Atmosphere", "atmo", RollTable.VAR_SCALE) + a.steps.assign(["None", "Thin", "Medium", "Dense"]) + b.tables.append(a) + _eq(Describe.effect("@climate += 1", b), "Climate 1 step up", "step up") + _eq(Describe.effect("@climate -= 2", b), "Climate 2 steps down", "steps down") + _eq(Describe.effect("@climate += -1", b), "Climate 1 step down", "a negative step up") + _eq(Describe.effect("@climate = \"Hot\"", b), "Climate = Hot", "set a step") + _eq(Describe.effect("@climate = 2", b), "Climate = Cold", "a step's number reads as its name") + _eq(Describe.effect("@climate = toward(@climate, \"Temperate\")", b), "Climate 1 step toward Temperate", "toward") + _eq(Describe.effect("@atmo = max(@atmo, \"Medium\")", b), "Atmosphere at least Medium", "at least") + _eq(Describe.effect("@atmo = min(@atmo, \"Thin\")", b), "Atmosphere at most Thin", "at most") + _eq(Describe.effect("@luck += 1", b), "Luck +1", "not a scale: as before") + _eq(Describe.condition("@atmo >= \"Thin\"", b), "Atmosphere is at least Thin", "condition at least a step") + _eq(Describe.condition("@atmo = 3", b), "Atmosphere is Medium", "a number in a condition reads as the step") diff --git a/tests/test_ui_scales.gd b/tests/test_ui_scales.gd new file mode 100644 index 0000000..ab1b06c --- /dev/null +++ b/tests/test_ui_scales.gd @@ -0,0 +1,191 @@ +extends TestBase +## Scale values in the UI (Scales): making one (+ Card, the inspector's steps +## and starting step, switching type), showing one (the card's value and row +## of steps, the Variables tab), the effect and condition rows for a scale, +## and the help topic. +## Run: godot --headless --path . -s res://tests/test_ui_scales.gd -- --sample + +const CLIMATE := ["Supercold", "Cold", "Temperate", "Hot", "Superhot"] + +var insp: Inspector + + +func _init() -> void: + if not await start_main(): + return + main.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT) + main.size = Vector2(1440, 900) + main.set_mode(Main.Mode.BUILD) + insp = main.inspector + await _load() + await _test_add_card() + await _test_inspector_fields() + await _test_settings_dialog() + await _test_card_shows_steps() + await _test_effect_rows() + await _test_condition_rows() + _test_help() + finish() + + +func _load() -> void: + main.data.load_dict({"format_version": 2, "id": "scales-test", "name": "Scales test", "tables": [ + {"id": "climate", "name": "Climate", "kind": "variable", "var_name": "climate", "var_type": "scale", + "steps": CLIMATE, "initial": "Temperate", "x": 40, "y": 40, "entries": []}, + {"id": "luck", "name": "Luck", "kind": "variable", "var_name": "luck", "var_type": "number", "initial": "2", + "x": 40, "y": 300, "entries": []}, + {"id": "weather", "name": "Weather", "x": 340, "y": 40, "entries": [ + {"id": "e1", "text": "Unexpectedly warmer", "effects": "@climate += 1", "pipes": [{"table": "luck_t", "when": "@climate >= \"Cold\""}]}, + {"id": "e2", "text": "Calm"}]}, + {"id": "luck_t", "name": "Lucky", "x": 700, "y": 40, "entries": [{"id": "e1", "text": "Yes"}]}, + ]}) + main.persistent_vars.clear() + main._rebuild_cards() + main.clear_inspector() + await _frames(4) + + +func _t(id: String) -> RollTable: + return main.data.get_table(id) + + +func _test_add_card() -> void: + var found := false + for k: Array in MainEditing.ADD_KINDS: + found = found or (k[1] == RollTable.KIND_VARIABLE and k[2] == RollTable.VAR_SCALE and str(k[0]).begins_with("Scale")) + _check(found, "+ Card lists Scale (ordered steps)") + var t := main.editing.add_table(RollTable.KIND_VARIABLE, RollTable.VAR_SCALE) + _check(t.is_scale() and t.steps == (["Low", "Medium", "High"] as Array[String]) and t.initial == "Low", "a new scale has Low, Medium, High and starts Low") + main.data.remove_table(t.id) + main._rebuild_cards() + await _frames(2) + + +func _test_inspector_fields() -> void: + main.select_card("climate") + await _frames(2) + var te := insp.fields.get("steps") as TextEdit + _check(te != null and te.text == "\n".join(CLIMATE), "the inspector lists the steps, one per line") + var start := insp.fields.get("initial") as OptionButton + _check(start != null and start.item_count == 5 and start.selected == 2, "the starting value is a dropdown of the steps, on Temperate") + start.item_selected.emit(3) + _eq(_t("climate").initial, "Hot", "picking a step sets the starting value") + _eq(insp.apply_settings({"steps": "Only one"}), "A scale needs at least two steps, one per line.", "one step isn't a scale") + te.text = "Cold\nMild\nWarm" + te.text_changed.emit() + _eq(_t("climate").steps, ["Cold", "Mild", "Warm"] as Array[String], "editing the lines sets the steps") + _eq(_t("climate").initial, "Cold", "a starting step that's gone falls back to the first") + _eq((insp.fields.get("initial") as OptionButton).item_count, 3, "the starting dropdown follows the steps") + insp.apply_settings({"steps": "Semi-arid\nWet"}) + _eq(_t("climate").initial, "\"Semi-arid\"", "a step with a dash starts as quoted text") + _eq(Roller.variable_display(main.data, main.persistent_vars, _t("climate"))["text"], "Semi-arid", "and still shows as the step") + # Switching types. + main.select_card("luck") + await _frames(2) + insp.apply_settings({"var_type": "scale"}, true) + _check(_t("luck").is_scale() and _t("luck").steps.size() == 3 and _t("luck").initial == "Low", "a number turned into a scale gets the default steps") + insp.apply_settings({"var_type": "number", "initial": ""}, true) + _eq(_t("luck").var_type, "number", "and back") + insp.apply_settings({"initial": "2"}) + _t("climate").steps.assign(CLIMATE) + _t("climate").initial = "Temperate" + main.mark_dirty() + await _frames(2) + + +func _test_settings_dialog() -> void: + var d := TableSettingsDialog.new(_t("climate")) + main.add_child(d) + await _frames(1) + _check(d._kind._steps_field.visible and d._kind._steps.text == "\n".join(CLIMATE), "the settings dialog shows the steps for a scale") + _eq(d.settings()["steps"], "\n".join(CLIMATE), "and passes them on") + d.queue_free() + d = TableSettingsDialog.new(_t("luck")) + main.add_child(d) + await _frames(1) + _check(not d._kind._steps_field.visible and not d.settings().has("steps"), "but not for a number") + d.queue_free() + await _frames(1) + + +func _test_card_shows_steps() -> void: + main.set_variable("climate", "4") + await _frames(2) + _eq(main.persistent_vars["climate"]["value"], "Hot", "typing a step number in the Variables tab stores the step") + main.set_variable("climate", "cold") + _eq(main.persistent_vars["climate"]["value"], "Cold", "a name is matched without caring about capitals") + main._rebuild_cards() + await _frames(2) + var ui := main.card_for("climate").value_ui + _eq(ui.var_value.text, "Cold", "the card shows the current step") + _eq(ui.steps_row.get_child_count(), 5, "and every step in a row") + var lit := [] + for chip in ui.steps_row.get_children(): + var l := chip.get_child(0) as Label + if (chip as PanelContainer).get_theme_stylebox("panel").bg_color.a > 0.0: + lit.append(l.text) + _eq(lit, ["Cold"], "with the current one marked") + main.clear_variable("climate") + await _frames(2) + + +func _test_effect_rows() -> void: + main.select_result("weather", "e1") + await _frames(2) + var fx := insp.effects + var e := _t("weather").find_entry("e1") + _eq([fx.rows[0]["op"], fx.rows[0]["amount"]], ["step_up", "1"], "@climate += 1 is a Move up row") + _check(InspectorKit.find_tagged(fx, "res.fx.0.amount") != null, "with a count of steps") + fx.set_row_amount(0, "2") + _eq(e.effects, "@climate += 2", "Move up 2 steps") + fx.set_row_op(0, "step_down") + _eq(e.effects, "@climate -= 2", "Move down") + fx.set_row_op(0, "toward") + _eq(e.effects, "@climate = toward(@climate, \"Supercold\")", "Move toward starts at the first step") + _check(InspectorKit.find_tagged(fx, "res.fx.0.step") is OptionButton, "and picks the step from a dropdown") + fx.set_row_step(0, "Temperate") + _eq(e.effects, "@climate = toward(@climate, \"Temperate\")", "picking a step writes it") + fx.set_row_op(0, "at_least") + _eq(e.effects, "@climate = max(@climate, \"Temperate\")", "Raise to at least keeps the step") + fx.set_row_op(0, "at_most") + _eq(e.effects, "@climate = min(@climate, \"Temperate\")", "Lower to at most") + fx.set_row_op(0, "set") + _eq(e.effects, "@climate = \"Temperate\"", "Set to a step") + _eq(Describe.effect(e.effects, main.data), "Climate = Temperate", "reads in plain words") + fx.add_row() + fx.set_row_var(1, "@climate") + _eq(e.effects, "@climate = \"Temperate\"\n@climate += 1", "a new row on a scale is Move up 1") + fx.set_row_var(1, "@luck") + _eq(e.effects, "@climate = \"Temperate\"\n@luck += 1", "on a number it's Add again") + fx.remove_row(1) + e.effects = "@climate += 1" + main.mark_dirty() + await _frames(2) + + +func _test_condition_rows() -> void: + main.select_result("weather", "e1") + await _frames(2) + var cond: ConditionBuilder = insp.pipe_parts["luck_t"]["when"] + var e := _t("weather").find_entry("e1") + _check(InspectorKit.find_tagged(cond, "cond.0.step") is OptionButton or _has_step_dropdown(cond), "a scale clause picks its step from a dropdown") + _eq(Describe.condition(e.when_for("luck_t"), main.data), "Climate is at least Cold", "reads in plain words") + cond.set_clause_step(0, "Hot") + _eq(e.when_for("luck_t"), "@climate >= \"Hot\"", "picking a step writes it") + cond.add_clause() + cond.set_clause_var(1, "@climate") + _eq(cond.clauses[1]["value"], "\"Supercold\"", "a new scale clause starts at the first step") + + +func _has_step_dropdown(n: Node) -> bool: + for c in n.get_children(): + if (c is OptionButton and (c as OptionButton).item_count == CLIMATE.size()) or _has_step_dropdown(c): + return true + return false + + +func _test_help() -> void: + var help := FileAccess.get_file_as_string("res://help/topics.txt") + var a := help.find("# Values and changes") + var b := help.find("# Scales") + _check(a >= 0 and b > a and help.find("\n# ", a + 1) == b - 1, "the Scales topic follows Values and changes") diff --git a/tests/test_ui_scales.gd.uid b/tests/test_ui_scales.gd.uid new file mode 100644 index 0000000..67207d3 --- /dev/null +++ b/tests/test_ui_scales.gd.uid @@ -0,0 +1 @@ +uid://bdt4nnkybokmu diff --git a/ui/inspector_card.gd b/ui/inspector_card.gd index bb86cf4..4824597 100644 --- a/ui/inspector_card.gd +++ b/ui/inspector_card.gd @@ -470,13 +470,15 @@ static func _variable(insp: Inspector, box: VBoxContainer, t: RollTable) -> void var vn := _setting_line(insp, "var_name", t.var_name, "luck", err) InspectorKit.code(vn) box.add_child(InspectorKit.field("Name in rules (@name)", vn)) - var types := ["number", "text", "list"] - var seg := ModalCard.segmented(["Number", "Text", "List"], maxi(0, types.find(t.var_type)), func(i: int) -> void: - InspectorKit.show_error(err, insp.apply_settings({"var_type": types[i]}, true)) + var types := ["number", "text", "list", RollTable.VAR_SCALE] + var seg := ModalCard.segmented(["Number", "Text", "List", "Scale"], maxi(0, types.find(t.var_type)), func(i: int) -> void: + InspectorKit.show_error(err, insp.apply_settings({"var_type": types[i], "initial": "" if t.is_scale() else t.initial}, true)) ) box.add_child(InspectorKit.field("Type", seg)) - var init := _setting_line(insp, "initial", t.initial, "0" if t.var_type == "number" else "nothing", err) - box.add_child(InspectorKit.field("Starting value", init)) + if t.is_scale(): + InspectorScale.build(insp, box, t, err) + else: + box.add_child(InspectorKit.field("Starting value", _setting_line(insp, "initial", t.initial, "0" if t.var_type == "number" else "nothing", err))) box.add_child(err) diff --git a/ui/inspector_condition.gd b/ui/inspector_condition.gd index d773719..b6d265b 100644 --- a/ui/inspector_condition.gd +++ b/ui/inspector_condition.gd @@ -2,8 +2,10 @@ class_name ConditionBuilder extends VBoxContainer ## A condition editor: clauses `[value ▾] [comparison ▾] [amount] ×`, an ## and/or switch once there are two, and "+ Add condition" -## (Builder.parse_condition / condition_text). A condition the builder can't -## show (mixed and/or, dice, functions…) is a text field with its problem; +## (Builder.parse_condition / condition_text). For a scale value the amount +## is a dropdown of its steps ("Atmosphere is at least [Thin ▾]"). A condition +## the builder can't show (mixed and/or, dice, functions…) is a text field +## with its problem; ## "Edit as text" and "Use the builder" switch between the two. ## Emits `changed(text)`; clauses not filled in yet are left out. @@ -94,6 +96,10 @@ func set_join(j: String) -> void: func set_clause_var(i: int, n: String) -> void: clauses[i]["var"] = n + var steps := ScaleFields.steps_of(main, n) + var cur := Builder.unquote(str(clauses[i]["value"])) + if not steps.is_empty() and Scales.position_of(steps, cur) == 0 and not ["set", "unset"].has(str(clauses[i]["cmp"])): + clauses[i]["value"] = Builder.quote(steps[0]) _render() _emit() @@ -112,6 +118,13 @@ func set_clause_value(i: int, typed: String) -> void: _emit() +## A scale clause's step. +func set_clause_step(i: int, step: String) -> void: + clauses[i]["value"] = Builder.quote(step) + _render() + _emit() + + func set_text_mode(on: bool) -> void: if on == text_mode: return @@ -204,7 +217,14 @@ func _clause_row(i: int) -> Control: f.add_child(dd) var err := InspectorKit.error_label() var le: LineEdit = null - if cmp != "set" and cmp != "unset": + var steps := ScaleFields.steps_of(main, str(c["var"])) + if not steps.is_empty() and cmp != "set" and cmp != "unset" and cmp != "has": + var cur := str(c["value"]) + cur = Builder.unquote(cur) if Builder.is_text_literal(cur) else (Scales.label_at(steps, int(cur)) if cur.is_valid_int() else cur) + var sd := ScaleFields.step_dropdown(steps, cur, func(st: String) -> void: set_clause_step(i, st)) + InspectorKit.tag(sd, "%s.%d.step" % [_key, i]) + f.add_child(sd) + elif cmp != "set" and cmp != "unset": le = InspectorKit.amount(InspectorKit.shown_token(str(c["value"])), "8") le.tooltip_text = "A number, a word, or a value such as @soc" InspectorKit.tag(le, "%s.%d.value" % [_key, i]) diff --git a/ui/inspector_effects.gd b/ui/inspector_effects.gd index fef37a9..9a85666 100644 --- a/ui/inspector_effects.gd +++ b/ui/inspector_effects.gd @@ -2,7 +2,7 @@ class_name EffectsBuilder extends VBoxContainer ## The inspector's "When this comes up" editor: one row per effect statement ## (Builder.parse_effects), each `[op ▾] [amount] to/from [value ▾] ×`, plus -## "+ Add a change". A statement the builder can't show stays a text field +## "+ Add a change". A scale value's row is EffectsScaleRow. A statement the builder can't show stays a text field ## with its problem. "Edit as text" switches to the whole effects text, and ## "Use the builder" switches back when every statement parses. ## Emits `changed(text)` with the statements (Builder.effect_text) joined by @@ -30,7 +30,7 @@ func setup(p_main: Main, text: String, p_table: RollTable, as_text: bool, key: S add_theme_constant_override("separation", 6) size_flags_horizontal = Control.SIZE_EXPAND_FILL rows.clear() - for m in Builder.parse_effects(text): + for m in Builder.parse_effects(text, _board()): rows.append(m) # One unreadable statement doesn't turn the whole field into text: it # shows as a text row among the others. Text mode starts as text. @@ -38,6 +38,10 @@ func setup(p_main: Main, text: String, p_table: RollTable, as_text: bool, key: S _render() +func _board() -> TowerBoard: + return main.data if main else null + + static func _all_ok(text: String) -> bool: for m in Builder.parse_effects(text): if not m["ok"]: @@ -94,7 +98,13 @@ func remove_row(i: int) -> void: func set_row_op(i: int, op: String) -> void: var m := rows[i] - if not m["ok"] or not OPS.has(op): + if not m["ok"] or not (OPS.has(op) or BuilderScales.OPS.has(op)): + return + var steps := ScaleFields.steps_of(main, str(m["var"])) + if BuilderScales.OPS.has(op) or (not steps.is_empty() and (op == "set" or op == "reset")) or BuilderScales.OPS.has(str(m["op"])): + EffectsScaleRow.set_op(m, op, steps) + _render() + _emit() return var was := str(m["op"]) m["op"] = op @@ -109,6 +119,8 @@ func set_row_op(i: int, op: String) -> void: m["amount"] = InspectorKit.amount_expr(amt, _known_names()) if amt != "" else "" elif amt == "" and was == "reset": m["amount"] = "1" + if not steps.is_empty(): + EffectsScaleRow.on_var(m, steps) _render() _emit() @@ -118,7 +130,7 @@ func set_row_amount(i: int, typed: String, render: bool = false) -> void: var m := rows[i] if not m["ok"]: return - var listy := str(m["op"]) == "append" or str(m["op"]) == "remove" + var listy := ["append", "remove", "toward", "at_least", "at_most"].has(str(m["op"])) m["amount"] = typed.strip_edges() if listy else InspectorKit.amount_expr(typed, _known_names()) if render: _render() @@ -130,6 +142,18 @@ func set_row_var(i: int, n: String) -> void: if not m["ok"]: return m["var"] = n + EffectsScaleRow.on_var(m, ScaleFields.steps_of(main, n)) + _render() + _emit() + + +## A scale row's step (Set writes it quoted; Move toward, Raise and Lower as +## the name). +func set_row_step(i: int, step: String) -> void: + var m := rows[i] + if not m["ok"]: + return + m["amount"] = Builder.quote(step) if str(m["op"]) == "set" else step _render() _emit() @@ -138,7 +162,7 @@ func set_row_var(i: int, n: String) -> void: func set_row_src(i: int, src: String) -> void: var m := rows[i] m["src"] = src - var p := Builder.parse_effect(src) + var p := Builder.parse_effect(src, _board()) m["error"] = str(p.get("error", "")) _emit() @@ -153,7 +177,7 @@ func set_text_mode(on: bool) -> void: if not _all_ok(_raw): return rows.clear() - for m in Builder.parse_effects(_raw): + for m in Builder.parse_effects(_raw, _board()): rows.append(m) text_mode = false _render() @@ -245,6 +269,13 @@ func _row(i: int) -> Control: check.call() return v var op := str(m["op"]) + if EffectsScaleRow.shows(m, ScaleFields.steps_of(main, str(m["var"]))): + var sp := ValuePicker.new(main, str(m["var"])) + sp.value_chosen.connect(func(n: String) -> void: set_row_var(i, n)) + var serr := InspectorKit.error_label() + EffectsScaleRow.fill(self, i, f, sp, x, serr) + v.add_child(serr) + return v var dd := InspectorKit.dropdown(OP_LABELS, OPS.find(op)) dd.tooltip_text = "What to do" dd.item_selected.connect(func(k: int) -> void: set_row_op(i, OPS[k])) diff --git a/ui/inspector_effects_scale.gd b/ui/inspector_effects_scale.gd new file mode 100644 index 0000000..5604464 --- /dev/null +++ b/ui/inspector_effects_scale.gd @@ -0,0 +1,134 @@ +class_name EffectsScaleRow +extends RefCounted +## The effects builder's row for a scale value (BuilderScales): `[Move up ▾] +## [Climate ▾] by [1] step`, `[Set ▾] [Climate ▾] to [Hot ▾]`, `[Move toward ▾] +## [Climate ▾] one step toward [Temperate ▾]`, `[Raise ▾] [Atmosphere ▾] to at +## least [Medium ▾]`, `[Lower ▾] … to at most [Thin ▾]`, `[Reset ▾] [Climate ▾]`. +## Step pickers list the value's steps. Edits go through EffectsBuilder. + +const OPS := ["step_up", "step_down", "set", "toward", "at_least", "at_most", "reset"] +const OP_LABELS := ["Move up", "Move down", "Set", "Move toward", "Raise", "Lower", "Reset"] +const _WORDS := {"set": "to", "toward": "one step toward", "at_least": "to at least", "at_most": "to at most"} + + +## True when row model `m` shows as a scale row: a scale op, or Set/Reset of a +## scale value to one of its steps (Set to an expression stays a plain row). +static func shows(m: Dictionary, steps: Array) -> bool: + var op := str(m["op"]) + if BuilderScales.OPS.has(op): + return true + if steps.is_empty(): + return false + if op == "reset": + return true + var a := str(m["amount"]) + return op == "set" and (a == "" or (Builder.is_text_literal(a) and Scales.position_of(steps, Builder.unquote(a)) > 0)) + + +## Switches row model `m` to `op`, keeping its step where it can: a count of +## steps for Move up/down, a step's name for the others (quoted for Set). +static func set_op(m: Dictionary, op: String, steps: Array) -> void: + var was := str(m["op"]) + var step := current_step(m, steps) + if step == "" and not steps.is_empty(): + step = str(steps[0]) + m["op"] = op + match op: + "step_up", "step_down": + if was != "step_up" and was != "step_down": + m["amount"] = "1" + "set": + m["amount"] = Builder.quote(step) if step != "" else "" + "toward", "at_least", "at_most": + m["amount"] = step + "reset": + m["amount"] = "" + + +## After the row's value changed: a scale value turns Add/Subtract into Move +## up/down (and anything that can't apply into Move up 1); a value that isn't +## a scale turns the scale ops back into ordinary ones. +static func on_var(m: Dictionary, steps: Array) -> void: + var op := str(m["op"]) + if not steps.is_empty(): + match op: + "add": + m["op"] = "step_up" + "subtract": + m["op"] = "step_down" + "multiply", "divide", "append", "remove": + m["op"] = "step_up" + m["amount"] = "1" + "set": + if not shows(m, steps): + m["amount"] = Builder.quote(str(steps[0])) + return + match op: + "step_up": + m["op"] = "add" + "step_down": + m["op"] = "subtract" + "toward", "at_least", "at_most": + m["op"] = "set" + m["amount"] = Builder.quote(str(m["amount"])) if str(m["amount"]) != "" else "" + + +## The step a row names ("" for none or a count of steps). +static func current_step(m: Dictionary, steps: Array) -> String: + var a := str(m.get("amount", "")) + match str(m["op"]): + "set": + return Builder.unquote(a) if Builder.is_text_literal(a) else "" + "toward", "at_least", "at_most": + return a + return "" + + +## Fills flow `f` with row `i` of `eb` (the op dropdown, the value picker and +## the step or count), then `x`, and shows the row's problem in `err`. +static func fill(eb: EffectsBuilder, i: int, f: Container, picker: ValuePicker, x: Button, err: Label) -> void: + var m := eb.rows[i] + var op := str(m["op"]) + var steps := ScaleFields.steps_of(eb.main, str(m["var"])) + var dd := InspectorKit.dropdown(OP_LABELS, OPS.find(op)) + dd.tooltip_text = "What to do" + dd.item_selected.connect(func(k: int) -> void: eb.set_row_op(i, OPS[k])) + f.add_child(dd) + picker.kinds = ["scale"] + f.add_child(picker) + var msg := "" if str(m["var"]) != "" else "Pick the value to change." + match op: + "step_up", "step_down": + f.add_child(InspectorKit.word("by")) + var le := InspectorKit.amount(str(m["amount"]), "1") + le.tooltip_text = "How many steps: a number, or dice such as 1d3" + InspectorKit.tag(le, "%s.%d.amount" % [eb._key, i]) + var unit := InspectorKit.word("step" if str(m["amount"]) == "1" else "steps") + le.text_changed.connect(func(s: String) -> void: + eb.set_row_amount(i, s) + unit.text = "step" if s.strip_edges() == "1" else "steps" + _check_count(m, le, err) + ) + f.add_child(le) + f.add_child(unit) + f.add_child(x) + _check_count(m, le, err) + return + "set", "toward", "at_least", "at_most": + f.add_child(InspectorKit.word(_WORDS[op])) + var sd := ScaleFields.step_dropdown(steps, current_step(m, steps), func(s: String) -> void: eb.set_row_step(i, s)) + InspectorKit.tag(sd, "%s.%d.step" % [eb._key, i]) + f.add_child(sd) + if msg == "" and current_step(m, steps) == "": + msg = "Pick a step." + f.add_child(x) + InspectorKit.show_error(err, msg) + + +static func _check_count(m: Dictionary, le: LineEdit, err: Label) -> void: + var a := str(m["amount"]).strip_edges() + var msg := "Pick the value to change." if str(m["var"]) == "" else "" + if msg == "": + msg = "Fill in how many steps." if a == "" else InspectorKit.expr_error(a, "The number of steps") + InspectorKit.show_error(err, msg) + InspectorKit.mark(le, msg == "" or str(m["var"]) == "") diff --git a/ui/inspector_effects_scale.gd.uid b/ui/inspector_effects_scale.gd.uid new file mode 100644 index 0000000..12465e6 --- /dev/null +++ b/ui/inspector_effects_scale.gd.uid @@ -0,0 +1 @@ +uid://cu5nxp6j4ouh8 diff --git a/ui/inspector_scale.gd b/ui/inspector_scale.gd new file mode 100644 index 0000000..8fccab5 --- /dev/null +++ b/ui/inspector_scale.gd @@ -0,0 +1,35 @@ +class_name InspectorScale +extends RefCounted +## A scale variable card's fields in the inspector (Scales): its steps, one +## per line, lowest first, and a starting value picked from them. Writes go +## through Inspector.apply_settings (TableSettingsRules keeps the starting +## value one of the steps). + + +static func build(insp: Inspector, box: VBoxContainer, t: RollTable, err: Label) -> void: + var te := InspectorKit.text_box("\n".join(t.steps), "Low\nMedium\nHigh", 96.0) + InspectorKit.tag(te, "card.steps") + insp.fields["steps"] = te + box.add_child(InspectorKit.field("Steps, one per line, lowest first", te)) + var start := HBoxContainer.new() + box.add_child(InspectorKit.field("Starting value", start)) + _fill_start(insp, start, t, err) + te.text_changed.connect(func() -> void: + var msg := insp.apply_settings({"steps": te.text}) + InspectorKit.mark(te, msg == "") + InspectorKit.show_error(err, msg) + if msg == "": + _fill_start(insp, start, t, err) + ) + + +## The starting value's step dropdown in `holder` (refilled when the steps change). +static func _fill_start(insp: Inspector, holder: Container, t: RollTable, err: Label) -> void: + InspectorKit.clear(holder) + var dd := ScaleFields.step_dropdown(t.steps, Builder.unquote(t.initial), func(step: String) -> void: + InspectorKit.show_error(err, insp.apply_settings({"initial": ScaleFields.initial_text(step)})) + ) + dd.tooltip_text = "The step it starts at, and goes back to on Reset" + InspectorKit.tag(dd, "card.initial") + insp.fields["initial"] = dd + holder.add_child(dd) diff --git a/ui/inspector_scale.gd.uid b/ui/inspector_scale.gd.uid new file mode 100644 index 0000000..fe28965 --- /dev/null +++ b/ui/inspector_scale.gd.uid @@ -0,0 +1 @@ +uid://kslylsh1fsy6 diff --git a/ui/main_editing.gd b/ui/main_editing.gd index de2239d..e9c98f8 100644 --- a/ui/main_editing.gd +++ b/ui/main_editing.gd @@ -22,6 +22,7 @@ const ADD_KINDS := [ ["Branch: if / else if / otherwise", RollTable.KIND_ROUTER, "", "Branch"], ["Variable", RollTable.KIND_VARIABLE, "number", "New variable"], ["Collection (Skills, Contacts…)", RollTable.KIND_VARIABLE, RollTable.VAR_COLLECTION, "Skills"], + ["Scale (ordered steps)", RollTable.KIND_VARIABLE, RollTable.VAR_SCALE, "New scale"], ["Sheet", RollTable.KIND_SHEET, "", "Sheet"], ] const MENU_FROM_TEMPLATE := 100 diff --git a/ui/main_state.gd b/ui/main_state.gd index a5c6361..cb90bf7 100644 --- a/ui/main_state.gd +++ b/ui/main_state.gd @@ -158,6 +158,8 @@ func set_variable(name: String, value: String) -> void: 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 + if card != null and card.is_scale(): + typed = Scales.store(card.steps, value) m.persistent_vars[name] = {"value": typed, "source": source} _variables_changed() diff --git a/ui/scale_fields.gd b/ui/scale_fields.gd new file mode 100644 index 0000000..5faaaea --- /dev/null +++ b/ui/scale_fields.gd @@ -0,0 +1,40 @@ +class_name ScaleFields +extends RefCounted +## Small shared pieces for scale values (Scales) in the inspector: a value's +## steps, a dropdown of steps, and a step written as a rule literal. + + +## The steps of board value `v` ("@climate") when a scale card declares it, +## else []. +static func steps_of(main: Main, v: String) -> Array[String]: + var card := BuilderScales.card_for(v, main.data if main else null) + return card.steps if card else ([] as Array[String]) + + +## A dropdown of `steps` with `current` selected (matched without caring about +## capitals). A `current` that isn't one of the steps is listed last, marked, +## so nothing is lost. `on_pick` gets the chosen step's name. +static func step_dropdown(steps: Array, current: String, on_pick: Callable) -> OptionButton: + var items: Array = steps.duplicate() + var at := Scales.position_of(steps, current) - 1 if current != "" else -1 + if at < 0 and current != "": + items.append("%s (not a step)" % current) + at = items.size() - 1 + var dd := InspectorKit.dropdown(items, at) + dd.tooltip_text = "Pick a step" + dd.item_selected.connect(func(k: int) -> void: + if k < steps.size(): + on_pick.call(str(steps[k])) + ) + return dd + + +## The steps a new scale card gets (RollTable.create's). +static func default_steps() -> Array[String]: + return RollTable.create(RollTable.KIND_VARIABLE, "", "", RollTable.VAR_SCALE).steps + + +## A step as a starting value: the name as it is when it reads as plain words, +## else quoted ("Semi-arid" has a dash, so it is "\"Semi-arid\""). +static func initial_text(step: String) -> String: + return step if RollTable._looks_literal(step) else Builder.quote(step) diff --git a/ui/scale_fields.gd.uid b/ui/scale_fields.gd.uid new file mode 100644 index 0000000..7319777 --- /dev/null +++ b/ui/scale_fields.gd.uid @@ -0,0 +1 @@ +uid://c85l8i1dfedno diff --git a/ui/settings_kind_fields.gd b/ui/settings_kind_fields.gd index 6351b62..4b019ac 100644 --- a/ui/settings_kind_fields.gd +++ b/ui/settings_kind_fields.gd @@ -32,6 +32,9 @@ var _loop_note: Label var _var_name: LineEdit var _var_type := "number" var _initial: LineEdit +## Scale variables: the steps, one per line (shown only for the Scale type). +var _steps: TextEdit +var _steps_field: Control var _template: TextEdit var _template_preview: RichTextLabel ## Router cards: one condition field per case, in order. @@ -71,6 +74,8 @@ func add_settings(s: Dictionary) -> void: s["var_name"] = _var_name.text.strip_edges().trim_prefix("@") s["var_type"] = _var_type s["initial"] = _initial.text.strip_edges() + if _var_type == RollTable.VAR_SCALE: + s["steps"] = _steps.text RollTable.KIND_SHEET: s["template"] = _template.text RollTable.KIND_ROUTER: @@ -142,10 +147,17 @@ func build() -> void: _var_name.text_changed.connect(func(_t: String) -> void: d._refresh()) box.add_child(ModalCard.field("Variable name (used as @name)", _var_name)) box.add_child(ModalCard.section("Type")) - box.add_child(ModalCard.segmented(["Number", "Text", "List", "Collection"], RollTable.VAR_TYPES.find(_var_type), func(i: int) -> void: + box.add_child(ModalCard.segmented(["Number", "Text", "List", "Collection", "Scale"], RollTable.VAR_TYPES.find(_var_type), func(i: int) -> void: _var_type = RollTable.VAR_TYPES[i] d._refresh() )) + _steps = TextEdit.new() + _steps.text = "\n".join(table.steps if not table.steps.is_empty() else ScaleFields.default_steps()) + _steps.custom_minimum_size.y = 96 + ModalCard.style_text_edit(_steps) + _steps.text_changed.connect(d._refresh) + _steps_field = ModalCard.field("Steps, one per line, lowest first", _steps) + box.add_child(_steps_field) _initial = LineEdit.new() _initial.text = table.initial _initial.placeholder_text = "10, 2d6, or a word" @@ -295,6 +307,8 @@ func refresh() -> void: RollTable.KIND_VARIABLE: _mark(_var_name, TableSettingsRules._re(TableSettingsRules.VAR_PATTERN).search(TemplateKit.probe(s["var_name"])) != null) _mark(_initial, TableSettingsRules._initial_error(s["initial"], _var_type) == "") + _steps_field.visible = _var_type == RollTable.VAR_SCALE + _initial.placeholder_text = "one of the steps" if _var_type == RollTable.VAR_SCALE else "10, 2d6, or a word" 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() != "" \ diff --git a/ui/table_card_value.gd b/ui/table_card_value.gd index 3389683..025788d 100644 --- a/ui/table_card_value.gd +++ b/ui/table_card_value.gd @@ -2,10 +2,14 @@ class_name TableCardValue extends RefCounted ## The body of a variable card (its live value, big) or a collection card (its ## members with live values), re-rendered by refresh() after rolls and edits. +## A scale card also shows its steps in a row with the current one marked. var card: TableCard var var_value: Label var var_hint: Label +## Scale cards: the steps in a row, refilled when the current step changes. +var steps_row: HFlowContainer +var steps_cache := "" ## Collection cards: the member list, refilled by refresh(). var members_box: VBoxContainer var members_cache := "" @@ -19,6 +23,8 @@ func _init(p_card: TableCard) -> void: func clear() -> void: var_value = null var_hint = null + steps_row = null + steps_cache = "" members_box = null members_cache = "" @@ -40,6 +46,12 @@ func make_variable_body(build: bool) -> Control: var_value.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART var_value.mouse_filter = Control.MOUSE_FILTER_PASS v.add_child(var_value) + if table.is_scale(): + steps_row = HFlowContainer.new() + steps_row.add_theme_constant_override("h_separation", 3) + steps_row.add_theme_constant_override("v_separation", 3) + steps_row.mouse_filter = Control.MOUSE_FILTER_IGNORE + v.add_child(steps_row) var_hint = Style.make_label("", Style.body(true), 12, Style.MUTED) var_hint.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART var_hint.mouse_filter = Control.MOUSE_FILTER_IGNORE @@ -174,3 +186,26 @@ func refresh() -> void: 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(steps_row): + _refresh_steps(str(d["text"])) + + +## The steps as small chips, the one named `current` filled in. +func _refresh_steps(current: String) -> void: + var steps := card.table.steps + var key := "%s|%s" % [current, "\n".join(steps)] + if key == steps_cache: + return + steps_cache = key + InspectorKit.clear(steps_row) + var at := Scales.position_of(steps, current) - 1 + for k in steps.size(): + var on := k == at + var chip := PanelContainer.new() + chip.mouse_filter = Control.MOUSE_FILTER_IGNORE + var bg := Style.box(Style.VALUE_BG if on else Color(0, 0, 0, 0), 4, [5, 1, 5, 1]) + chip.add_theme_stylebox_override("panel", Style.bordered(bg, 1, Style.VALUE_BORDER if on else Style.RULE)) + var l := Style.make_label(str(steps[k]), Style.body_bold(true) if on else Style.body(true), 11, Style.VALUE_INK if on else Style.MUTED) + l.mouse_filter = Control.MOUSE_FILTER_IGNORE + chip.add_child(l) + steps_row.add_child(chip) diff --git a/ui/table_settings_rules.gd b/ui/table_settings_rules.gd index f9cb48b..5ccc5fc 100644 --- a/ui/table_settings_rules.gd +++ b/ui/table_settings_rules.gd @@ -57,6 +57,8 @@ static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray: 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) + if str(s.get("var_type", t.var_type)) == RollTable.VAR_SCALE and s.has("steps") and Scales.clean(s["steps"]).size() < 2: + out.append("A scale needs at least two steps, one per line.") return out @@ -163,6 +165,7 @@ static func _apply_kind(t: RollTable, s: Dictionary) -> void: if RollTable.VAR_TYPES.has(vt): t.var_type = vt t.initial = str(s.get("initial", t.initial)).strip_edges() + _apply_scale(t, s) RollTable.KIND_ROUTER: var cases: Array = s.get("cases", []) for i in mini(cases.size(), t.entries.size()): @@ -174,6 +177,19 @@ static func _apply_kind(t: RollTable, s: Dictionary) -> void: t.entries[0].text = str(s["template"]) +## A scale card's steps (from `s`, else the defaults when it has none) and a +## starting value that is one of them (else the first step). +static func _apply_scale(t: RollTable, s: Dictionary) -> void: + if not t.is_scale(): + return + if s.has("steps"): + t.steps = Scales.clean(s["steps"]) + if t.steps.is_empty(): + t.steps = ScaleFields.default_steps() + if Scales.position_of(t.steps, Builder.unquote(t.initial)) == 0: + t.initial = ScaleFields.initial_text(t.steps[0]) + + ## Switches a pick card between a fixed list and options from variables. ## Turning variables on adds a Chosen entry first (untouched default ## "Option N" entries go; anything else stays as a fixed extra). Turning them diff --git a/ui/value_picker.gd b/ui/value_picker.gd index ce9276d..94744f1 100644 --- a/ui/value_picker.gd +++ b/ui/value_picker.gd @@ -9,12 +9,12 @@ extends Button signal value_chosen(name: String) const GROUPS := ["", "Variables", "Collections", "Other values", "Roll values"] -const KIND_WORDS := {"number": "number", "text": "text", "list": "list", "collection": "collection"} +const KIND_WORDS := {"number": "number", "text": "text", "list": "list", "collection": "collection", "scale": "scale"} var main: Main ## The chosen value's name ("@luck", "@skill_*", "tier"), or "". var value := "" -## Kinds offered ([] for all): "number", "text", "list", "collection". +## Kinds offered ([] for all): "number", "text", "list", "collection", "scale". var kinds: Array = [] ## Extra items listed first: Array of {name, label, kind?}. var extras: Array = []