diff --git a/core/describe_cards.gd b/core/describe_cards.gd index b9b8a03..cb2b15e 100644 --- a/core/describe_cards.gd +++ b/core/describe_cards.gd @@ -68,10 +68,22 @@ static func pipe(entry: TableEntry, target_id: String, board: TowerBoard) -> Str parts.append("again on " + reroll_names(again, board.get_table(target_id) if board else null)) var sv := entry.save_for(target_id) if sv != "": - parts.append("saves " + Describe._label(sv, L)) + parts.append(("adds to " if _is_list(sv, board) else "saves ") + Describe._label(sv, L)) return " · ".join(parts) +## Whether `name` ("@features") is a value a list card declares, so saving +## into it adds an item (RollContext.save_result()). +static func _is_list(name: String, board: TowerBoard) -> bool: + if board == null or not name.strip_edges().begins_with("@"): + return false + var n := name.strip_edges().substr(1).to_lower() + for t in board.tables: + if t.kind == RollTable.KIND_VARIABLE and t.var_name == n: + return t.var_type == "list" + return false + + ## "Mixed, Binary": the names of the results a thread rolls again on (their ## numbers on a ranged card: "96–00"), in the card's order. static func reroll_names(ids: Array, t: RollTable) -> String: diff --git a/core/describe_why.gd b/core/describe_why.gd index d7e80cb..ae6559e 100644 --- a/core/describe_why.gd +++ b/core/describe_why.gd @@ -24,6 +24,15 @@ static func why(fact: Dictionary, board: TowerBoard, plain: bool = true) -> Stri s = ("Rolled again on " if plain else "reroll skipped ") + ", ".join(skipped) if plain and str(fact.get("column", "")) != "": s = "%s: %s" % [fact["column"], s] + "repeat": + var got := PackedStringArray() + for x: Dictionary in fact.get("rolls", []): + got.append("%s (%s)" % [x.get("text", ""), Expr.format_value(x.get("value"))]) + s = ("Rolled it %d times and combined them: " % got.size() if plain else "repeat ×%d: " % got.size()) + ", ".join(got) + if str(fact.get("column", "")) != "": + s = "%s: %s" % [fact["column"], s] + "only_option": + s = "Picked the only option there was" if plain else "only one option: picked it" "check": s = _why_check(fact, L, plain) "when": diff --git a/core/effects.gd b/core/effects.gd index f29a9c1..c1f5871 100644 --- a/core/effects.gd +++ b/core/effects.gd @@ -18,6 +18,24 @@ extends RefCounted const OPS := ["+=", "-=", "*=", "/=", "="] + +## A comma-separated list with `item` added at the end (unless it's there +## already, ignoring capitals) or, with `remove`, taken out. Returns the new +## list text. Used by += / -= on lists and by saving a result into a list +## value (RollContext.save_result()). +static func list_with(list: Variant, item: String, remove: bool = false) -> String: + var items := Expr.list_items(list if list != null else "") + var at := -1 + for k in items.size(): + if items[k].to_lower() == item.to_lower(): + at = k + break + if not remove and at < 0 and item != "": + items.append(item) + elif remove and at >= 0: + items.remove_at(at) + return ", ".join(items) + static var _stmt_re: RegEx = null static var _reset_re: RegEx = null @@ -211,18 +229,8 @@ static func _assign(st: Dictionary, ctx: RollContext, source_id: String, facts: line = "%s = %s" % [label, _shown(value)] "+=", "-=": if as_list: - var items := Expr.list_items(cur if cur != null else "") var item := Expr.format_value(rhs).strip_edges() - var at := -1 - for k in items.size(): - if items[k].to_lower() == item.to_lower(): - at = k - break - if op == "+=" and at < 0 and item != "": - items.append(item) - elif op == "-=" and at >= 0: - items.remove_at(at) - value = ", ".join(items) + value = list_with(cur, item, op == "-=") line = "%s %s %s → %s" % [label, "+" if op == "+=" else "−", item, _shown(value)] else: var a: Variant = Expr.to_value(cur) if cur != null and str(cur).strip_edges() != "" else 0 diff --git a/core/roll_choice.gd b/core/roll_choice.gd index 11fa1cb..eac4f42 100644 --- a/core/roll_choice.gd +++ b/core/roll_choice.gd @@ -173,7 +173,10 @@ static func run(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> Roller._why(none, req["why"]) Roller._attach(f, none, ctx) return - var reply: Variant = await ask(ctx, req) + # A pick with only one option it could take doesn't ask: that option is + # picked, as if the player had chosen it. + var only := _only_option(req) if t.choice == "pick" else -1 + var reply: Variant = only if only >= 0 else await ask(ctx, req) if reply == null: Roller._attach(f, Roller._stop(t, Roller.CANCELLED, {"kind": RollTable.KIND_CHOICE, "cancelled": true}), ctx) ctx.halted = Roller.CANCELLED @@ -201,6 +204,9 @@ static func run(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> if not opt.is_empty(): node = _option_node(t, opt, ctx) node["picked"] = true + if only >= 0: + node["only_option"] = true + Roller._why(node, [{"type": "only_option"}]) elif not t.is_dynamic() and int(req["hidden"]) == 0 and not opts.any(func(o: Dictionary) -> bool: return o.has("cost")): # A plain fixed list: Random rolls the card the usual way # (weights, ranges, card mode). @@ -244,6 +250,19 @@ static func _option_node(t: RollTable, o: Dictionary, ctx: RollContext) -> Dicti return node +## The index of a pick request's one available option (not greyed out), or +## -1 when there are several. +static func _only_option(req: Dictionary) -> int: + var found := -1 + for o: Dictionary in req["options"]: + if o.has("disabled"): + continue + if found >= 0: + return -1 + found = int(o["index"]) + return found + + ## Random among a request's options by their "weight" (each dynamic option ## weighs as much as the Chosen entry; fixed ones their own weight, or span ## on a ranged card). Position in `opts`, or -1 when every weight is 0. @@ -264,7 +283,7 @@ static func _pick_option(opts: Array, rng: RandomNumberGenerator) -> int: static func _answered(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array, value: Variant, summary: String) -> void: ctx.chain_vars["answer"] = value if t.save_as != "": - ctx.save(t.save_as, value, t.id) + ctx.save_result(t.save_as, value, t.id) var node := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": summary, "kind": RollTable.KIND_CHOICE, "answer": value} Roller._attach(f, node, ctx) diff --git a/core/roll_columns.gd b/core/roll_columns.gd index 9cfc4a5..cb0b8a7 100644 --- a/core/roll_columns.gd +++ b/core/roll_columns.gd @@ -10,18 +10,28 @@ extends RefCounted ## first column is the card's own roll, so its result's changes and threads ## happen as usual. ## +## A "roll twice and combine" row (TableEntry.repeat) that comes up in a +## column rolls that column again `count` times and combines the texts with +## REPEAT_JOIN ("Ash & Black"); a repeat row that comes up on those rolls adds +## its own count (so "roll twice" again means one more), up to MAX_REPEATS. +## ## Columns are worked out left to right. A column with "save_as" saves its ## text before the next one starts, so a later column's "when" (only roll it ## if …) can read it. A skipped column saves nothing. ## ## The node gets "columns": [{name, text, index, value?, skipped?}] and its -## summary becomes "Resources: Rich · Water: Plentiful". +## summary becomes "Resources: Rich · Water: Plentiful", or with column_join +## the texts joined ("Ash Canyons"). + +const REPEAT_JOIN := " & " +const MAX_REPEATS := 50 static func fill(node: Dictionary, f: Dictionary, ctx: RollContext, depth: int) -> void: var t: RollTable = node["table"] var rows: Array = [] var parts := PackedStringArray() + var texts := PackedStringArray() var log: Array = [] var why: Array = [] for k in t.columns.size(): @@ -39,43 +49,86 @@ static func fill(node: Dictionary, f: Dictionary, ctx: RollContext, depth: int) rows.append(row) continue var text := "" - if k == 0: - text = str(node["summary"]) - row["value"] = node.get("value") + var pick := node + if k > 0 and t.column_rolls == RollTable.COLUMNS_EACH: + pick = RollCards.pick_for(t, ctx, f) + _add_why(why, pick, nm) + if pick.has("stop"): + text = str(pick["summary"]) else: - var pick := node - if t.column_rolls == RollTable.COLUMNS_EACH: - pick = RollCards.pick_for(t, ctx, f) - if pick.has("why"): - for fact: Dictionary in pick["why"]: - var c := fact.duplicate() - c["column"] = nm - why.append(c) - if pick.has("stop"): - text = str(pick["summary"]) + row["index"] = int(pick["index"]) + row["value"] = pick.get("value") + var e: TableEntry = pick["entry"] + if not e.repeat.is_empty(): + text = await _repeat(node, t, k, e, f, ctx, depth, why) + elif k == 0: + text = str(node["summary"]) else: - row["index"] = int(pick["index"]) - row["value"] = pick.get("value") - ctx.depth = depth + 1 - var ex: Dictionary = await TextExpander.expand_async(RollTable.cell_text(pick["entry"], k), ctx) - ctx.depth = depth - text = str(ex["text"]) - for c2: Dictionary in ex["children"]: - c2["inline"] = true - (node["children"] as Array).append(c2) + text = await _cell(node, e, k, ctx, depth) row["text"] = text rows.append(row) var save := str(col.get("save_as", "")).strip_edges() if save != "": - ctx.save(save, plain(text), t.id) + ctx.save_result(save, plain(text), t.id) if Formatter.strip_tags(text).strip_edges() != "": parts.append("%s: %s" % [Formatter.escape_literal(nm), text]) + texts.append(text) node["columns"] = rows - node["summary"] = " · ".join(parts) + node["summary"] = t.column_join.join(texts) if t.column_join != "" else " · ".join(parts) Roller._log(node, log) Roller._why(node, why) +## Column `k`'s text on entry `e`, expanded; inline rolls become children. +static func _cell(node: Dictionary, e: TableEntry, k: int, ctx: RollContext, depth: int) -> String: + ctx.depth = depth + 1 + var ex: Dictionary = await TextExpander.expand_async(RollTable.cell_text(e, k), ctx) + ctx.depth = depth + for c: Dictionary in ex["children"]: + c["inline"] = true + (node["children"] as Array).append(c) + return str(ex["text"]) + + +## A repeat row came up in column `k`: rolls the column `e.repeat.count` times +## (skipping the repeat's reroll ids) and combines the texts. Works through a +## queue, not recursion; stops after MAX_REPEATS rolls. +static func _repeat(node: Dictionary, t: RollTable, k: int, e: TableEntry, f: Dictionary, ctx: RollContext, depth: int, why: Array) -> String: + var nm := str(t.columns[k].get("name", "")) + var queue: Array = [] + for _n in int(e.repeat.get("count", 2)): + queue.append(e.repeat.get("reroll", [])) + var got := PackedStringArray() + var facts: Array = [] + var rolls := 0 + while not queue.is_empty() and rolls < MAX_REPEATS: + rolls += 1 + var skip: Array = queue.pop_front() + var p := RollCards.pick_for(t, ctx, {"dice": str(f.get("dice", "")), "reroll": skip}) + _add_why(why, p, nm) + if p.has("stop"): + got.append(str(p["summary"])) + continue + var pe: TableEntry = p["entry"] + if not pe.repeat.is_empty(): + for _n in int(pe.repeat.get("count", 2)): + queue.append(pe.repeat.get("reroll", [])) + continue + var s := await _cell(node, pe, k, ctx, depth) + got.append(s) + facts.append({"value": p.get("value"), "text": plain(s)}) + why.append({"type": "repeat", "column": nm, "rolls": facts}) + return REPEAT_JOIN.join(got) + + +static func _add_why(why: Array, pick: Dictionary, column: String) -> void: + if pick.has("why"): + for fact: Dictionary in pick["why"]: + var c := fact.duplicate() + c["column"] = column + why.append(c) + + ## A column's text as a value: no formatting, no internal markers. static func plain(text: String) -> String: return Formatter.strip_tags(Formatter.to_export_bbcode(text)).strip_edges() diff --git a/core/roll_combine.gd b/core/roll_combine.gd index 5098cd7..34fbedf 100644 --- a/core/roll_combine.gd +++ b/core/roll_combine.gd @@ -88,7 +88,7 @@ static func _ask(kids: Array, ctx: RollContext) -> Dictionary: static func _save(f: Dictionary, ctx: RollContext, v: Variant, t: RollTable) -> void: var save := str(f.get("save", "")) if save != "": - ctx.save(save, v, t.id) + ctx.save_result(save, v, t.id) static func _fmt(x: float) -> String: diff --git a/core/roll_context.gd b/core/roll_context.gd index 5b260e6..f0ad980 100644 --- a/core/roll_context.gd +++ b/core/roll_context.gd @@ -117,6 +117,21 @@ func save(name: String, value: Variant, source_id: String = "") -> void: chain_vars[n] = value +## Saves a result (a thread's or column's "save as", a choice's answer, an +## inline [[Table -> @x]]): like save(), except that a variable declared as a +## list keeps its items and gains the new ones, so repeated rolls collect. +func save_result(name: String, value: Variant, source_id: String = "") -> void: + var n := name.strip_edges() + var card := declared(n) if n.begins_with("@") else null + if card == null or card.var_type != "list": + save(n, value, source_id) + return + var list: Variant = get_value(n) + for item in Expr.list_items(Formatter.strip_tags(Expr.format_value(value))): + list = Effects.list_with(list, item) + save(n, list if list != null else "", source_id) + + ## Returns the saved value as display text (numbers without ".0"), or null ## when the variable isn't set. "@name" reads a persistent variable, "name" a ## chain variable. diff --git a/core/roll_lint_book.gd b/core/roll_lint_book.gd index e7a9773..8ef7e55 100644 --- a/core/roll_lint_book.gd +++ b/core/roll_lint_book.gd @@ -1,7 +1,8 @@ class_name RollLintBook extends RefCounted ## Board checks for the book-table features: threads that roll with other dice -## or roll again on some results, cards with columns, and scale values. +## or roll again on some results, cards with columns (and their "roll twice and +## combine" rows), and scale values. ## Items are {table_id, entry_id, message, kind: "book", level: "error"|"hint"}. @@ -30,6 +31,13 @@ static func lint(board: TowerBoard, t: RollTable) -> Array[Dictionary]: out.append(_item(t, e.id, "The thread to %s rolls again on every result, so it can never finish." % _n(to), "error")) if not missing.is_empty(): out.append(_item(t, e.id, "The thread to %s rolls again on results that aren't on that card any more." % _n(to), "hint")) + for e in t.entries: + if e.repeat.is_empty(): + continue + if not t.has_columns(): + out.append(_item(t, e.id, "%s rolls its column again, but this card has no columns, so it does nothing. Use a thread back to the card instead." % _q(e), "hint")) + elif t.entries.all(func(x: TableEntry) -> bool: return not x.repeat.is_empty() or (e.repeat.get("reroll", []) as Array).has(x.id)): + out.append(_item(t, e.id, "%s rolls its column again, but every result rolls again too, so it can never finish." % _q(e), "error")) if t.has_columns(): for c: Dictionary in t.columns: var w := str(c.get("when", "")) @@ -40,6 +48,10 @@ static func lint(board: TowerBoard, t: RollTable) -> Array[Dictionary]: return out +static func _q(e: TableEntry) -> String: + return "“%s”" % Formatter.strip_tags(e.text).strip_edges() + + static func _n(t: RollTable) -> String: return Formatter.strip_tags(t.name).strip_edges() diff --git a/core/roll_table.gd b/core/roll_table.gd index 7403955..880cf02 100644 --- a/core/roll_table.gd +++ b/core/roll_table.gd @@ -85,6 +85,10 @@ var entries: Array[TableEntry] = [] var columns: Array = [] ## COLUMNS_ROW or COLUMNS_EACH. var column_rolls: String = COLUMNS_ROW +## Cards with columns: when not "", the result reads as the column texts joined +## with this ("Ash" + " " + "Canyons" = "Ash Canyons") instead of "1st Part: +## Ash · 2nd Part: Canyons", and that phrase is what a thread saves. +var column_join: String = "" ## One of KINDS. var kind: String = KIND_ROLL diff --git a/core/roll_table_io.gd b/core/roll_table_io.gd index d972e1d..be5a84a 100644 --- a/core/roll_table_io.gd +++ b/core/roll_table_io.gd @@ -41,6 +41,8 @@ static func to_dict(t: RollTable) -> Dictionary: d["columns"] = clean_columns(t.columns) if t.column_rolls != RollTable.COLUMNS_ROW: d["column_rolls"] = t.column_rolls + if t.column_join != "": + d["column_join"] = t.column_join if t.kind == RollTable.KIND_CHOICE: if t.choice != "pick": d["choice"] = t.choice @@ -113,6 +115,7 @@ static func from_dict(d: Dictionary) -> RollTable: t.deck_empty = "stop" if str(d.get("deck_empty", "reshuffle")) == "stop" else "reshuffle" t.deck_empty_text = str(d.get("deck_empty_text", "")) t.columns = clean_columns(d.get("columns", [])) + t.column_join = str(d.get("column_join", "")) if d.get("column_join") != null else "" t.column_rolls = RollTable.COLUMNS_EACH if str(d.get("column_rolls", "")) == RollTable.COLUMNS_EACH else RollTable.COLUMNS_ROW var k := str(d.get("kind", RollTable.KIND_ROLL)) t.kind = k if RollTable.KINDS.has(k) else RollTable.KIND_ROLL diff --git a/core/roll_tree.gd b/core/roll_tree.gd index 2b28a35..9870370 100644 --- a/core/roll_tree.gd +++ b/core/roll_tree.gd @@ -36,7 +36,7 @@ static func step_of(n: Dictionary, depth: int = 0) -> Dictionary: step["kind"] = n["kind"] if n.has("effects"): step["effects"] = (n["effects"] as Array).duplicate(true) - for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled", "deck_empty", "dropped", "kept", "combined", "stopped_before", "case", "option", "check", "inputs", "columns"]: + for k in ["answer", "passes", "pass", "after", "picked", "only_option", "random", "limit", "cancelled", "deck_empty", "dropped", "kept", "combined", "stopped_before", "case", "option", "check", "inputs", "columns"]: if n.has(k): step[k] = n[k] if n.has("why"): diff --git a/core/roller.gd b/core/roller.gd index 44f01fc..f4a8675 100644 --- a/core/roller.gd +++ b/core/roller.gd @@ -317,14 +317,14 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr var save := str(f.get("save", "")) if save != "": var v: Variant = node["answer"] if node.has("answer") else Formatter.to_export_bbcode(str(node["summary"])) - ctx.save(save, v, t.id) + ctx.save_result(save, v, t.id) # A picked option is saved under the choice's save_as before the pipe # snapshot, so its own pipe conditions can read it. if t.kind == RollTable.KIND_CHOICE and t.save_as != "" and not node.has("answer"): if node.has("option"): - ctx.save(t.save_as, str(node["option"]), t.id) + ctx.save_result(t.save_as, str(node["option"]), t.id) else: - ctx.save(t.save_as, Formatter.strip_tags(str(node["summary"])).strip_edges(), t.id) + ctx.save_result(t.save_as, Formatter.strip_tags(str(node["summary"])).strip_edges(), t.id) if e.pipes.is_empty(): return # A roll that is being combined with others (RollCombine) waits: only the diff --git a/core/table_entry.gd b/core/table_entry.gd index 78db0fc..aa32172 100644 --- a/core/table_entry.gd +++ b/core/table_entry.gd @@ -53,6 +53,11 @@ var pipe_dice: Dictionary = {} var pipe_reroll: Dictionary = {} ## Cards with columns: this result's text in columns 1.. (column 0 is `text`). var cells: Array[String] = [] +## Cards with columns: a "roll twice and combine" row. When this result comes +## up in a column, that column is rolled `count` more times and the results are +## combined (RollColumns). {} = off; else {"count": int >= 1, "reroll": +## [result ids skipped on those rolls]?}. +var repeat: Dictionary = {} ## Choice options: what picking this costs (RollCosts): a value name and an ## amount (an expression). "" = free. var cost_value: String = "" @@ -330,6 +335,8 @@ func to_dict() -> Dictionary: d["range"] = [range_lo, range_hi] if not cells.is_empty(): d["cells"] = cells.duplicate() + if not repeat.is_empty(): + d["repeat"] = repeat.duplicate(true) if page != "": d["page"] = page if image != "": @@ -339,6 +346,24 @@ func to_dict() -> Dictionary: return d +## A "repeat" value from JSON or the UI: {count >= 1, reroll?: [ids]}, or {}. +static func clean_repeat(v: Variant) -> Dictionary: + if not (v is Dictionary): + return {} + var n := int(JsonIO._num((v as Dictionary).get("count", 2), 2)) + if n < 1: + return {} + var out := {"count": n} + var ids: Array[String] = [] + if (v as Dictionary).get("reroll") is Array: + for x: Variant in v["reroll"]: + if str(x) != "" and not ids.has(str(x)): + ids.append(str(x)) + if not ids.is_empty(): + out["reroll"] = ids + return out + + static func from_dict(d: Dictionary) -> TableEntry: var e := TableEntry.new(str(d.get("id", "")), str(d.get("text", ""))) e.details = str(d.get("details", "")) @@ -376,6 +401,7 @@ static func from_dict(d: Dictionary) -> TableEntry: if d.get("cells") is Array: for c: Variant in d["cells"]: e.cells.append(str(c) if c != null else "") + e.repeat = clean_repeat(d.get("repeat")) var r: Variant = d.get("range") if r is Array and r.size() == 2: e.has_range = true diff --git a/core/text_expander.gd b/core/text_expander.gd index cd6bfd1..2f33eea 100644 --- a/core/text_expander.gd +++ b/core/text_expander.gd @@ -332,7 +332,7 @@ static func _expand_ref(ref: Dictionary, ctx: RollContext, children: Array) -> S plain.append(piece["value"]) var save_as: String = ref["save"] if save_as != "" and ctx.halted == "": - ctx.save(save_as, ", ".join(plain), id) + ctx.save_result(save_as, ", ".join(plain), id) return ", ".join(pieces) @@ -350,7 +350,7 @@ static func _expand_var(name: String, table: String, ctx: RollContext, children: var piece: Dictionary = await _roll_one(id, ctx, children) if not piece["rolled"]: return piece["text"] - ctx.save(name, piece["value"], id) + ctx.save_result(name, piece["value"], id) return "[url=var:%s]%s[/url]" % [name, piece["value"]] diff --git a/docs/LOGIC.md b/docs/LOGIC.md index a57a5a7..08dc0f1 100644 --- a/docs/LOGIC.md +++ b/docs/LOGIC.md @@ -42,6 +42,11 @@ after the player answers, so `@terms += @answer` style bookkeeping and "go on to step" pipes live there. Random on a `pick` card rolls the card normally, honouring weights or ranges. +A `pick` card with only one option it can take (after `show_if`, `options_where`, and +options greyed out by a cost) doesn't ask: that option is picked as if the player had chosen +it. The node has `only_option` and a why fact `{type: "only_option"}`. So a "which of your +world types?" pick only asks a Mixed world. + The pop-up also has **Cancel**, which stops the whole roll with a visible "Cancelled" marker. Fast roll (Shift-click) still asks questions, because they are the player's decisions. @@ -295,6 +300,19 @@ result's own `text`; the other columns are the result's `cells` (Strings, full t - The node gets `columns: [{name, text, index, value?, skipped?}]` and the summary "Resources: Rich · Water: Plentiful". Extra column rolls add `roll` why facts with a `column` key. Code: `core/roll_columns.gd`. +- **One phrase** (`column_join`, "Read as one phrase" in the inspector): many books print + "1st Part | 2nd Part" tables whose columns make one name ("Ash" + "Canyons"). With + `column_join` set (a space, `", "`, `" – "` or any text; not trimmed), the summary is the + non-empty column texts joined with it ("Ash Canyons"), and that is what a thread's save gets. +- **Roll twice and combine** (entry `repeat: {count, reroll?}`, on the result's inspector + section): when that result comes up in a column, the column is rolled `count` more times + (with the thread's dice) and the texts are joined with " & " ("Ash & Black Canyons"). A + repeat result that comes up on those rolls adds its own count (so "roll twice" again + means one more roll), unless it is in `reroll`, which rolls again instead ("re-rolling any + result of 93+"). At most 50 rolls. The node gets a `repeat` why fact `{column, rolls: + [{value, text}]}`. Changes and threads still belong to the card's own roll only. A repeat + on a card without columns does nothing (a lint hint: use a thread back to the card); a + card where every result repeats is a lint error. ## 3f. Threads that roll with other dice or roll again @@ -360,6 +378,12 @@ when the expression has modifiers. label members by the rest of their name ("Gun Combat") and the group by the card's name. `RollTable.create("variable", id, "Skills", "collection")` gives the stem `skill` (the name's slug without a final "s"). Its live display lists the set members. +- **Results saved into a list.** A thread's or column's "save as", a choice's `save_as` and + an inline `[[Table -> @x]]` normally replace the value. When a list card (`var_type: + "list"`) declares it, the saved text is **added** as an item instead (each item once, + ignoring capitals, like `+=`), so "roll 5 times and keep every result" collects them. Set + it empty first (`@found = ""`, or `reset @found`) to start over. The thread's label reads + "adds to Found". Effects (`=`) still replace. Code: `RollContext.save_result()`. - `reset @name` sets a declared variable back to its starting value, or deletes an undeclared one. `reset @skill_*` resets every variable with that prefix. - Chain variables (no `@`, e.g. `answer`, `i`, `-> hero`) last for one top-level roll, as @@ -463,10 +487,12 @@ Table keys: - `inputs`: `[{"name": "tier", "label": "Tier", "default": "1"}]` (any card; `label` and `default` left out when empty) -- `steps` (scale variable cards, Array of Strings), `columns` and `column_rolls` (§3e) +- `steps` (scale variable cards, Array of Strings), `columns`, `column_rolls` and + `column_join` (§3e) Entry keys: - `cells` (Array of Strings, columns 1.. of a card with columns) +- `repeat` (`{count, reroll?}`, a "roll twice and combine" result, §3e) - `effects` (String) - `when` (String, router cases; empty or missing is Otherwise) - `show_if` (String, pick options; empty or missing is always shown) @@ -495,6 +521,8 @@ so history keeps them. The key is left out when a node has no facts. Each fact h | `when` | the node whose entry has the pipe, one per conditional pipe | `to` (table id), `expr`, `values`, `result`, `error`? | | `otherwise` | likewise, one per otherwise pipe | `to`, `result` | | `reroll` | a node a thread rolled again (§3f) | `skipped: [{value, text}]`; `column` on an extra column's roll | +| `repeat` | a column whose result said "roll twice and combine" (§3e) | `column`, `rolls: [{value, text}]` | +| `only_option` | a pick that had one option (§2) | (none) | `values` maps each variable the expression reads (`"@luck"`, or a chain name such as `"tier"`) to its value when it was evaluated (null when unset); indirect `@[…]` names aren't listed. The diff --git a/io/json_canon.gd b/io/json_canon.gd index 9f2bcca..f350ab7 100644 --- a/io/json_canon.gd +++ b/io/json_canon.gd @@ -130,6 +130,9 @@ static func _canon_table(td: Dictionary) -> Dictionary: entries.append(_canon_entry(e)) t["entries"] = entries _keep(td, t, ["color", "w", "list_h", "roll_floor", "roll_ceiling", "deck_empty_text", "columns", "column_rolls", "steps"]) + # A separator may be just a space, so it isn't trimmed. + if td.get("column_join") is String and td["column_join"] != "": + t["column_join"] = td["column_join"] return t @@ -184,7 +187,7 @@ static func _canon_entry(ev: Variant) -> Dictionary: pipes.append(np) if not pipes.is_empty(): e["pipes"] = pipes - _keep(ed, e, ["page", "image", "cells"]) + _keep(ed, e, ["page", "image", "cells", "repeat"]) if ed.get("cost") is Dictionary: e["cost"] = ed["cost"] return e diff --git a/tests/test_book_collect.gd b/tests/test_book_collect.gd new file mode 100644 index 0000000..b324777 --- /dev/null +++ b/tests/test_book_collect.gd @@ -0,0 +1,161 @@ +extends TestBase +## Book-table features for multi-part and repeated rolls: columns read as one +## phrase (column_join), "roll twice and combine" rows (TableEntry.repeat), +## saving results into a list value, and a pick with one option answering +## itself. +## Run: godot --headless --path . -s res://tests/test_book_collect.gd -- --sample + + +func _init() -> void: + await _test_join_and_repeat() + await _test_repeat_reroll() + await _test_list_save() + await _test_only_option() + _test_save_load() + _test_lint() + finish() + + +func _ctx(b: TowerBoard, seed_value: int = 1) -> RollContext: + var rng := RandomNumberGenerator.new() + rng.seed = seed_value + return Roller.new_context(b, rng, {}, {}) + + +func _ranged(t: RollTable, eid: String, lo: int, hi: int, text: String, cells: Array = []) -> TableEntry: + var e := TableEntry.new(eid, text) + e.has_range = true + e.range_lo = lo + e.range_hi = hi + e.cells.assign(cells) + t.entries.append(e) + return e + + +func _list_card(name: String) -> RollTable: + var v := RollTable.create("variable", "v_" + name, name.capitalize(), "list") + v.var_name = name + return v + + +## "Surface": 1d4, 1st Part | 2nd Part read as one phrase; 3–4 roll twice and +## combine. "Start" rolls it 3 times into the list @surface. +func _surface_board() -> TowerBoard: + var b := TowerBoard.new() + var t := RollTable.new("surface", "Surface") + t.dice = "1d4" + t.column_rolls = RollTable.COLUMNS_EACH + t.column_join = " " + t.columns = [{"name": "1st Part"}, {"name": "2nd Part"}] + _ranged(t, "a", 1, 1, "Ash", ["Basins"]) + _ranged(t, "b", 2, 2, "Black", ["Canyons"]) + _ranged(t, "r", 3, 4, "Roll twice and combine", ["Roll twice and combine"]).repeat = {"count": 2} + var start := RollTable.new("start", "Start") + var e := TableEntry.new("s", "Go") + e.add_pipe("surface", 3, "@surface") + start.entries.append(e) + b.tables.append_array([start, t, _list_card("surface")]) + return b + + +func _test_join_and_repeat() -> void: + var b := _surface_board() + var combined := false + for s in 40: + var ctx := _ctx(b, s) + var tree := await Roller.roll_async(b, "start", ctx) + for kid: Dictionary in tree["children"]: + var text := Formatter.strip_tags(str(kid["summary"])) + _check(not text.contains(":") and not text.contains("Roll twice"), "a joined result reads as one phrase: %s" % text) + if text.contains(" & "): + combined = true + _check((kid["why"] as Array).any(func(f: Dictionary) -> bool: return f["type"] == "repeat"), "a repeat leaves a why fact") + var items := Expr.list_items(ctx.get_value("@surface")) + _check(items.size() >= 1 and items.size() <= 3, "the thread's saves collect in the list: %s" % str(items)) + _check(combined, "a roll-twice row combines two rolls of its column") + var fact := {"type": "repeat", "column": "1st Part", "rolls": [{"value": 1, "text": "Ash"}, {"value": 2, "text": "Black"}]} + _eq(Describe.why(fact, b), "1st Part: Rolled it 2 times and combined them: Ash (1), Black (2)", "the repeat fact as a sentence") + + +func _test_repeat_reroll() -> void: + var b := _surface_board() + var r := b.get_table("surface").find_entry("r") + r.repeat = {"count": 2, "reroll": ["r"]} + for s in 40: + var tree := await Roller.roll_async(b, "start", _ctx(b, s)) + for kid: Dictionary in tree["children"]: + for col: Dictionary in kid["columns"]: + _check(str(col["text"]).count(" & ") <= 1, "rolling again on the repeat row keeps it to two: %s" % col["text"]) + + +func _test_list_save() -> void: + var b := TowerBoard.new() + var res := RollTable.new("res", "Resource") + for k in 3: + res.entries.append(TableEntry.new("e%d" % k, ["Silicates", "Water ice", "Helium-3"][k])) + var start := RollTable.new("start", "Start") + var e := TableEntry.new("s", "Go") + e.effects = "@found = \"\"" + e.add_pipe("res", 10, "@found") + e.add_pipe("res2", 3, "@last") + start.entries.append(e) + var res2 := RollTable.new("res2", "Other") + for k in 3: + res2.entries.append(TableEntry.new("o%d" % k, "Item %d" % k)) + b.tables.append_array([start, res, res2, _list_card("found")]) + var ctx := _ctx(b) + await Roller.roll_async(b, "start", ctx) + var items := Expr.list_items(ctx.get_value("@found")) + _check(items.size() >= 2 and items.size() <= 3, "ten rolls into a list keep each result once: %s" % str(items)) + _check(not str(ctx.get_value("@last")).contains(","), "an undeclared value is still replaced: %s" % ctx.get_value("@last")) + await Roller.roll_async(b, "start", ctx) + _check(Expr.list_items(ctx.get_value("@found")).size() <= 3, "an effect that sets the list empties it first") + _eq(DescribeCards.pipe(e, "res", b), "×10 · adds to Found", "the thread label says it adds to the list") + + +func _test_only_option() -> void: + var b := TowerBoard.new() + var pick := RollTable.create("choice", "which", "Which type?") + pick.choice = "pick" + pick.options_from = "@types" + pick.save_as = "@page" + pick.entries.assign([TableEntry.new("c", RollChoice.CHOSEN)]) + b.tables.append_array([pick, _list_card("types")]) + var asked := [0] + var ctx := _ctx(b) + ctx.prompt = func(_req: Dictionary) -> Variant: + asked[0] += 1 + return -1 + ctx.save("@types", "Barren") + var node := await Roller.roll_async(b, "which", ctx) + _eq(asked[0], 0, "one option: no question") + _eq(ctx.get_value("@page"), "Barren", "and it's picked") + _check(bool(node.get("only_option", false)), "the node says so") + ctx.save("@types", "Barren, Frozen") + await Roller.roll_async(b, "which", ctx) + _eq(asked[0], 1, "two options: the player is asked") + + +func _test_save_load() -> void: + var b := _surface_board() + b.get_table("surface").find_entry("r").repeat = {"count": 3, "reroll": ["r"]} + var text := JSON.stringify(b.to_dict()) + for d: Dictionary in [JSON.parse_string(text), JsonIO.canonical(JSON.parse_string(text))]: + var back := TowerBoard.new() + back.load_dict(d) + var t := back.get_table("surface") + _eq(t.column_join, " ", "column_join round-trips (a space)") + _eq(t.find_entry("r").repeat, {"count": 3, "reroll": ["r"]}, "repeat round-trips") + _eq(t.find_entry("a").repeat, {}, "other rows have none") + + +func _test_lint() -> void: + var b := _surface_board() + var t := b.get_table("surface") + for e in t.entries: + e.repeat = {"count": 2} + var msgs := Roller.lint_pipes(b).map(func(i: Dictionary) -> String: return str(i["message"])) + _check(msgs.any(func(m: String) -> bool: return m.contains("can never finish")), "lint: every row repeats") + t.columns = [] + msgs = Roller.lint_pipes(b).map(func(i: Dictionary) -> String: return str(i["message"])) + _check(msgs.any(func(m: String) -> bool: return m.contains("no columns")), "lint: repeat without columns") diff --git a/tests/test_ui_columns.gd b/tests/test_ui_columns.gd index ee47b8a..87f08a9 100644 --- a/tests/test_ui_columns.gd +++ b/tests/test_ui_columns.gd @@ -1,8 +1,8 @@ extends TestBase ## Cards with columns on the spread and in the inspector: the header and the ## cells, the lit cells after a roll, inline cell editing, and the inspector's -## Columns section (add, rename, move, remove, roll mode, save as, only if) -## with the result's cell fields, all undoable. +## Columns section (add, rename, move, remove, roll mode, one phrase, save as, +## only if) with the result's cell fields and roll twice and combine, all undoable. ## Run: godot --headless --path . -s res://tests/test_ui_columns.gd -- --sample var insp: Inspector @@ -21,6 +21,7 @@ func _init() -> void: await _test_build_cells() await _test_inspector_columns() await _test_result_cells() + await _test_join_and_repeat() finish() @@ -214,6 +215,23 @@ func _test_result_cells() -> void: _eq(_t("world").find_entry("e2").cells[1], "Plentiful", "undo") +func _test_join_and_repeat() -> void: + print("One phrase, roll twice and combine") + main.select_card("world") + await _frames(2) + (insp.fields["column_join"] as OptionButton).item_selected.emit(1) + _eq(_t("world").column_join, " ", "Read as one phrase joins with spaces") + main.select_result("world", "e3") + await _frames(2) + (insp.fields["repeat"] as CheckBox).toggled.emit(true) + await _frames(2) + _eq(_t("world").find_entry("e3").repeat, {"count": 2}, "Roll twice and combine turns on") + (insp.fields["repeat_count"] as LineEdit).text_changed.emit("3") + (insp.fields["repeat_skip"] as CheckBox).toggled.emit(true) + _eq(_t("world").find_entry("e3").repeat, {"count": 3, "reroll": ["e3"]}, "count and roll again on it") + main.undo_redo._commit_edits() + + func _press(label: String) -> void: for b in insp.find_children("*", "Button", true, false): if (b as Button).text == label: diff --git a/ui/inspector_columns.gd b/ui/inspector_columns.gd index 9cdd4fb..b72f232 100644 --- a/ui/inspector_columns.gd +++ b/ui/inspector_columns.gd @@ -4,8 +4,10 @@ extends RefCounted ## multi-column table): "Add columns" turns them on (Result plus one more); ## then one roll for the whole row or each column rolled separately, and a box ## per column with its name, move and remove, "Save as [value ▾]" and (after -## the first) "Only roll this column if …". The result section's cell fields -## come from result_cells(). Writes go through Inspector.wrote, so undo works +## the first) "Only roll this column if …", and how the result reads (each +## column by name, or one phrase: column_join). The result section's cell fields +## come from result_cells(), with the result's "roll twice and combine" +## option (TableEntry.repeat). Writes go through Inspector.wrote, so undo works ## as for any card edit. The editing helpers keep every result's cells in step ## with the columns. @@ -15,6 +17,8 @@ const ROLL_NOTES := [ "One roll picks a row, and you get every column of that row.", "The first column is the card's own roll. Each other column is rolled on its own, like “roll 1d10 for each”.", ] +const JOIN_LABELS := ["Show each column by name", "Read as one phrase (spaces)", "Read as one phrase (commas)", "Read as one phrase (dashes)"] +const JOIN_VALUES := ["", " ", ", ", " – "] static func build(insp: Inspector, box: VBoxContainer, t: RollTable) -> void: @@ -38,6 +42,7 @@ static func build(insp: Inspector, box: VBoxContainer, t: RollTable) -> void: insp.wrote(t, false, true)) v.add_child(mode) v.add_child(InspectorKit.note(ROLL_NOTES[maxi(0, ROLL_MODES.find(t.column_rolls))], Style.MUTED, 13)) + v.add_child(_join_picker(insp, t)) for k in t.columns.size(): v.add_child(_column_box(insp, t, k)) var row := InspectorKit.hbox(12) @@ -56,6 +61,25 @@ static func build(insp: Inspector, box: VBoxContainer, t: RollTable) -> void: box.add_child(InspectorKit.field("Columns", v)) +## How the result reads: "1st Part: Ash · 2nd Part: Canyons", or the columns +## as one phrase ("Ash Canyons"), which is also what a thread saves. +static func _join_picker(insp: Inspector, t: RollTable) -> Control: + var labels := JOIN_LABELS.duplicate() + var values := JOIN_VALUES.duplicate() + if not values.has(t.column_join): + labels.append("Read as one phrase (joined with “%s”)" % t.column_join) + values.append(t.column_join) + var join := InspectorKit.dropdown(labels, values.find(t.column_join)) + join.tooltip_text = "Whether the result lists each column by name, or reads the columns together as one phrase, like “Ash Canyons”" + InspectorKit.tag(join, "card.column_join") + insp.fields["column_join"] = join + join.item_selected.connect(func(i: int) -> void: + if t.column_join != values[i]: + t.column_join = values[i] + insp.wrote(t, false, true)) + return join + + static func _column_box(insp: Inspector, t: RollTable, k: int) -> Control: var col: Dictionary = t.columns[k] var panel := PanelContainer.new() @@ -150,6 +174,46 @@ static func result_cells(insp: Inspector, t: RollTable, e: TableEntry) -> void: TableCardColumns.set_cell(e, k, s) insp.wrote(t)) insp._content.add_child(InspectorKit.field(nm if nm.strip_edges() != "" else "Column %d" % (k + 1), le)) + insp._content.add_child(InspectorKit.field("Roll twice and combine", _repeat_row(insp, t, e))) + + +## "When this comes up in a column, roll that column [2] times and combine", +## plus "skip this result on those rolls" (TableEntry.repeat). +static func _repeat_row(insp: Inspector, t: RollTable, e: TableEntry) -> Control: + var v := InspectorKit.vbox(4) + var on := InspectorKit.check_box("When this comes up in a column, roll that column again", not e.repeat.is_empty()) + InspectorKit.tag(on, "res.repeat") + insp.fields["repeat"] = on + on.toggled.connect(func(b: bool) -> void: + e.repeat = {"count": 2} if b else {} + insp.wrote(t, false, true)) + v.add_child(on) + if e.repeat.is_empty(): + return v + var row := InspectorKit.flow() + row.add_child(InspectorKit.word("Roll it")) + var n := InspectorKit.amount(str(e.repeat.get("count", 2)), "2") + InspectorKit.tag(n, "res.repeat.count") + insp.fields["repeat_count"] = n + n.text_changed.connect(func(s: String) -> void: + if s.strip_edges().is_valid_int() and int(s) >= 1 and int(s) != int(e.repeat.get("count", 2)): + e.repeat["count"] = int(s) + insp.wrote(t)) + row.add_child(n) + row.add_child(InspectorKit.word("times and combine the results")) + v.add_child(row) + var skip := InspectorKit.check_box("Roll again if this comes up on those rolls", (e.repeat.get("reroll", []) as Array).has(e.id)) + InspectorKit.tag(skip, "res.repeat.skip") + insp.fields["repeat_skip"] = skip + skip.toggled.connect(func(b: bool) -> void: + if b: + e.repeat["reroll"] = [e.id] + else: + e.repeat.erase("reroll") + insp.wrote(t)) + v.add_child(skip) + v.add_child(InspectorKit.note("Otherwise it adds another roll each time it comes up.", Style.MUTED, 12)) + return v # ---------- Editing (keeps every result's cells in step) ---------- @@ -189,8 +253,10 @@ static func remove_column(t: RollTable, k: int) -> void: static func remove_columns(t: RollTable) -> void: t.columns = [] t.column_rolls = RollTable.COLUMNS_ROW + t.column_join = "" for e in t.entries: e.cells.clear() + e.repeat = {} ## Moves column `k` left (-1) or right (+1); the first column stays put.