diff --git a/core/describe_cards.gd b/core/describe_cards.gd index 4fd454a..b9b8a03 100644 --- a/core/describe_cards.gd +++ b/core/describe_cards.gd @@ -61,12 +61,31 @@ static func pipe(entry: TableEntry, target_id: String, board: TowerBoard) -> Str parts.append("×" + Describe._expr(ce, L)) elif entry.count_for(target_id) != 1: parts.append("×%d" % entry.count_for(target_id)) + if entry.dice_for(target_id) != "": + parts.append("with " + entry.dice_for(target_id)) + var again := entry.reroll_for(target_id) + if not again.is_empty(): + 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)) return " · ".join(parts) +## "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: + if t == null: + return ", ".join(ids) + var out := PackedStringArray() + for i in t.entries.size(): + var e := t.entries[i] + if ids.has(e.id): + var label := Formatter.strip_tags(e.text).strip_edges() + out.append(t.num_label(e, i) if e.has_range or label == "" else label) + return ", ".join(out) + + ## A check card: "Roll 2d6 + Strength modifier, need 8 or more" ("need 5 or ## less" for a roll-under check). "" for other kinds. static func check(table: RollTable, board: TowerBoard) -> String: diff --git a/core/describe_why.gd b/core/describe_why.gd index 869e49f..d7e80cb 100644 --- a/core/describe_why.gd +++ b/core/describe_why.gd @@ -15,6 +15,15 @@ static func why(fact: Dictionary, board: TowerBoard, plain: bool = true) -> Stri match str(fact.get("type", "")): "roll": s = _why_roll(fact, L, plain) + if str(fact.get("column", "")) != "": + s = "%s: %s" % [fact["column"], s] + "reroll": + var skipped := PackedStringArray() + for x: Dictionary in fact.get("skipped", []): + skipped.append("%s (%s)" % [Expr.format_value(x.get("value")), x.get("text", "")]) + s = ("Rolled again on " if plain else "reroll skipped ") + ", ".join(skipped) + if plain and str(fact.get("column", "")) != "": + s = "%s: %s" % [fact["column"], s] "check": s = _why_check(fact, L, plain) "when": diff --git a/core/effects.gd b/core/effects.gd index 914db46..f29a9c1 100644 --- a/core/effects.gd +++ b/core/effects.gd @@ -191,6 +191,8 @@ static func _assign(st: Dictionary, ctx: RollContext, source_id: String, facts: var card := ctx.declared(target) if card != null: type = card.var_type + if type == RollTable.VAR_SCALE: + return _assign_scale(st, ctx, source_id, facts, rhs, cur, label) var as_list := false if op == "+=" or op == "-=": if type == "text" or type == "list": @@ -249,6 +251,32 @@ static func _assign(st: Dictionary, ctx: RollContext, source_id: String, facts: return {"text": line} +## A scale value (Scales): "=" takes a step name or position, "+=" and "-=" +## move it that many steps, stopping at the ends. +static func _assign_scale(st: Dictionary, ctx: RollContext, source_id: String, facts: Variant, rhs: Variant, cur: Variant, label: String) -> Dictionary: + var target: String = st["target"] + var op: String = st["op"] + var steps := ctx.scale_steps(target.trim_prefix("@")) + var value: Variant = rhs + var line := "" + if op == "+=" or op == "-=": + var b: Variant = Expr.to_value(rhs) + if not Expr.is_number(b): + return {"text": "%s: %s moves by a number of steps" % [st["src"], label], "error": true} + var delta := int(b) if op == "+=" else -int(b) + value = Scales.position_of(steps, cur) + delta if cur != null else delta + ctx.save(target, value, source_id) + line = "%s %s %s → %s" % [label, _signed(delta), "step" if absi(delta) == 1 else "steps", _shown(ctx.get_value(target))] + elif op == "=": + ctx.save(target, value, source_id) + line = "%s = %s" % [label, _shown(ctx.get_value(target))] + else: + return {"text": "%s: %s can only move up or down" % [st["src"], label], "error": true} + if facts != null: + (facts as Array).append({"type": "effect", "var": target, "op": op, "before": cur, "after": ctx.get_value(target)}) + return {"text": line} + + static func _reset(target: String, ctx: RollContext, facts: Variant = null) -> Dictionary: if target.ends_with("*"): var prefix := target.trim_prefix("@").trim_suffix("*") diff --git a/core/expr.gd b/core/expr.gd index 80ea402..7086033 100644 --- a/core/expr.gd +++ b/core/expr.gd @@ -47,14 +47,21 @@ static func evaluate(src: String, ctx: RollContext) -> Dictionary: var v: Variant = null if ctx != null: v = ctx.get_value(("@" if pair[0] == "@" else "") + str(pair[1])) + # A scale value reads as its step's number (unset: 0). + var steps: Array[String] = [] + if pair[0] == "@": + steps = ctx.scale_steps(str(pair[1])) + if not steps.is_empty(): + v = Scales.position_of(steps, v) if v != null else 0 if v == null: unset.append(k) v = "" if text_side[k] else 0 else: v = to_value(v) values.append(v) - var base := _Base.new() + var base := ExprBase.new() base.ctx = ctx + base.var_names = kinds var e: Expression = p["expr"] var out: Variant = e.execute(values, base, false) if e.has_execute_failed() and not unset.is_empty(): @@ -317,6 +324,7 @@ static func _rewrite(src: String) -> Dictionary: var n_ind := 0 # Tokens as [kind, text]: kind "str", "var", "op", "other" (for text_side). var toks: Array = [] + var lits: Array[String] = [] var i := 0 var n := src.length() while i < n: @@ -330,8 +338,11 @@ static func _rewrite(src: String) -> Dictionary: if j >= n: return {"text": "", "inputs": [], "vars": [], "text_side": [], "error": "A text value is missing its closing quote"} var lit := src.substr(i, j - i + 1) - out += lit - toks.append(["str", lit]) + # A placeholder: a step name beside a scale value becomes its number + # (ExprBase._lit), worked out below once the variables are known. + out += "\u0002%d\u0002" % lits.size() + toks.append(["str", lit, lits.size()]) + lits.append(lit) i = j + 1 continue if c == "@" and i + 1 < n and src[i + 1] == "[": @@ -471,6 +482,21 @@ static func _rewrite(src: String) -> Dictionary: continue if toks[u][0] == "str" or (toks[u][0] == "op" and toks[u][1] == "in"): text_side[toks[t][1]] = true + # Each text literal goes beside the nearest @variable (left first), so a + # step name can read as its number when that variable is a scale. + for t in toks.size(): + if toks[t][0] != "str" or (toks[t] as Array).size() < 3: + continue + var near := -1 + for d in range(1, toks.size()): + for u: int in [t - d, t + d]: + if near < 0 and u >= 0 and u < toks.size() and toks[u][0] == "var" and vars[toks[u][1]][0] == "@": + near = toks[u][1] + if near >= 0: + break + var lit_s: String = toks[t][1] + var put := lit_s if near < 0 else "_lit(%d, %s)" % [near, lit_s] + out = out.replace("\u0002%d\u0002" % toks[t][2], put) return {"text": out, "inputs": inputs, "vars": vars, "text_side": text_side, "error": ""} @@ -494,51 +520,3 @@ static func _is_word(c: String) -> bool: static func _is_word_start(c: String) -> bool: return c == "_" or (c.to_lower() != c.to_upper()) - - -## The base instance Expression calls helper functions on. -class _Base: - extends RefCounted - var ctx: RollContext = null - var error: String = "" - - func _d(n: int, sides: int) -> int: - if ctx != null and ctx.faces != null: - var total := 0 - for k in n: - var f := ctx.rng.randi_range(1, sides) - (ctx.faces as Array).append(f) - total += f - return total - return Expr.roll_dice(n, sides, ctx.rng if ctx != null else null) - - func dm(x: Variant) -> int: - return Expr.dm(x) - - func _if(cond: Variant, then_value: Variant, else_value: Variant) -> Variant: - return then_value if Expr.truthy(cond) else else_value - - func has(list: Variant, item: Variant) -> bool: - return Expr.has_item(list, item) - - func _iv(name: Variant) -> Variant: - return _indirect(name, 0) - - func _ivt(name: Variant) -> Variant: - return _indirect(name, "") - - func _indirect(name: Variant, unset: Variant) -> Variant: - var r := Expr.indirect_name(name) - if r["error"] != "": - if error == "": - error = r["error"] - return unset - if ctx == null: - return unset - var v: Variant = ctx.get_value("@" + str(r["name"])) - return unset if v == null else Expr.to_value(v) - - func count(prefix: Variant) -> int: - if ctx == null: - return 0 - return ctx.count_vars(str(prefix)) diff --git a/core/expr_base.gd b/core/expr_base.gd new file mode 100644 index 0000000..6c10255 --- /dev/null +++ b/core/expr_base.gd @@ -0,0 +1,82 @@ +class_name ExprBase +extends RefCounted +## The base instance Godot's Expression calls helper functions on, for Expr: +## dice, dm(), if(), has(), count(), toward(), indirect @[…] names, and step +## names beside scale values (_lit). + +var ctx: RollContext = null +var error: String = "" +## The expression's variables, in input order: [kind ("@" or ""), name]. +var var_names: Array = [] + + +func _d(n: int, sides: int) -> int: + if ctx != null and ctx.faces != null: + var total := 0 + for k in n: + var f := ctx.rng.randi_range(1, sides) + (ctx.faces as Array).append(f) + total += f + return total + return Expr.roll_dice(n, sides, ctx.rng if ctx != null else null) + + +func dm(x: Variant) -> int: + return Expr.dm(x) + + +func _if(cond: Variant, then_value: Variant, else_value: Variant) -> Variant: + return then_value if Expr.truthy(cond) else else_value + + +func has(list: Variant, item: Variant) -> bool: + return Expr.has_item(list, item) + + +## One step from `a` toward `b` (scale positions or plain numbers). +func toward(a: Variant, b: Variant) -> int: + return Scales.toward(a, b) + + +## A text literal beside variable `slot`: when that variable is a scale and +## the text is one of its steps, the step's number; otherwise the text. +func _lit(slot: int, text: String) -> Variant: + if ctx == null or slot < 0 or slot >= var_names.size(): + return text + var pair: Array = var_names[slot] + if pair[0] != "@": + return text + var steps := ctx.scale_steps(str(pair[1])) + if steps.is_empty(): + return text + var k := Scales.position_of(steps, text) + return k if k > 0 else text + + +func _iv(name: Variant) -> Variant: + return _indirect(name, 0) + + +func _ivt(name: Variant) -> Variant: + return _indirect(name, "") + + +func _indirect(name: Variant, unset: Variant) -> Variant: + var r := Expr.indirect_name(name) + if r["error"] != "": + if error == "": + error = r["error"] + return unset + if ctx == null: + return unset + var v: Variant = ctx.get_value("@" + str(r["name"])) + var steps := ctx.scale_steps(str(r["name"])) + if not steps.is_empty(): + return Scales.position_of(steps, v) if v != null else 0 + return unset if v == null else Expr.to_value(v) + + +func count(prefix: Variant) -> int: + if ctx == null: + return 0 + return ctx.count_vars(str(prefix)) diff --git a/core/expr_base.gd.uid b/core/expr_base.gd.uid new file mode 100644 index 0000000..e56a507 --- /dev/null +++ b/core/expr_base.gd.uid @@ -0,0 +1 @@ +uid://brkou4jguw0rb diff --git a/core/roll_cards.gd b/core/roll_cards.gd index 06fa7a8..4b4b397 100644 --- a/core/roll_cards.gd +++ b/core/roll_cards.gd @@ -5,9 +5,42 @@ extends RefCounted ## build nodes with Roller's node helpers and push frames on its work stack. +## Most times a thread rolls again on the results it skips before giving up. +const MAX_REROLLS := 100 +const ALL_REROLLED := "This thread rolls again on every result" + + +## pick_node() for the frame `f` that reached the card: its thread may roll +## with other dice (f.dice) and roll again on some results (f.reroll, result +## ids). Skipped rolls go in a {"type": "reroll", "skipped": [{value, text}]} +## why fact on the kept node. +static func pick_for(t: RollTable, ctx: RollContext, f: Dictionary) -> Dictionary: + var dice := str(f.get("dice", "")) + var skip: Array = f.get("reroll", []) + if skip.is_empty(): + return pick_node(t, ctx, dice) + var left := false + for e in t.entries: + if not skip.has(e.id) and t.can_come_up(e): + left = true + if not left: + return Roller._stop(t, ALL_REROLLED) + var skipped: Array = [] + for n in MAX_REROLLS: + var node := pick_node(t, ctx, dice) + if node.has("stop") or not skip.has((node["entry"] as TableEntry).id): + if not skipped.is_empty(): + Roller._why(node, [{"type": "reroll", "skipped": skipped}]) + return node + skipped.append({"value": node["value"], "text": Formatter.strip_tags((node["entry"] as TableEntry).text).strip_edges()}) + return Roller._stop(t, ALL_REROLLED) + + ## Rolls an entry the normal way (card mode, ranges or weights). Returns a node -## with no children yet, or a stop node. -static func pick_node(t: RollTable, ctx: RollContext) -> Dictionary: +## with no children yet, or a stop node. `dice` (a thread's "roll with … +## instead") replaces a ranged card's own dice; past the ends then counts as +## the end result. +static func pick_node(t: RollTable, ctx: RollContext, dice: String = "") -> Dictionary: var rng := ctx.rng var index: int var value: int @@ -33,21 +66,21 @@ static func pick_node(t: RollTable, ctx: RollContext) -> Dictionary: elif t.is_ranged(): var was: Variant = ctx.faces ctx.faces = [] - var rv := t.roll_value(ctx) + var rv := RollRange.roll_value(t, ctx, dice) var faces: Array = ctx.faces ctx.faces = was if was != null: (was as Array).append_array(faces) if rv["error"] != "": - return Roller._stop(t, "Can't roll %s: %s" % [t.roll_text(), rv["error"]]) + return Roller._stop(t, "Can't roll %s: %s" % [RollRange.join(dice, t.dice_mod) if dice != "" else t.roll_text(), rv["error"]]) value = int(rv["value"]) - fact = {"type": "roll", "pick": "dice", "dice": t.roll_text(), "faces": faces, "total": value} + fact = {"type": "roll", "pick": "dice", "dice": RollRange.join(dice, t.dice_mod) if dice != "" else t.roll_text(), "faces": faces, "total": value} if rv.has("limited"): fact["limited"] = rv["limited"] fact["limit_expr"] = rv["limit_expr"] fact["raw"] = rv["raw"] # The Why line names the modifier ("+3 for Luck") when it's all of the change. - if t.has_mod() and not t.is_expr_dice() and t.dice_obj().bonus == 0: + if dice == "" and t.has_mod() and not t.is_expr_dice() and t.dice_obj().bonus == 0: fact["mod_expr"] = t.dice_mod.strip_edges() if not faces.is_empty(): var nat := 0 @@ -55,8 +88,8 @@ static func pick_node(t: RollTable, ctx: RollContext) -> Dictionary: nat += x fact["nat"] = nat fact["mod"] = int(fact.get("raw", value)) - nat - index = t.entry_index_clamped(value) - if t.clamps(): + index = RollRange.index_for(t, value, dice != "") + if t.clamps() or dice != "": var span := RollRange.span(t) if value < span.x or value > span.y: fact["counts_as"] = clampi(value, span.x, span.y) diff --git a/core/roll_columns.gd b/core/roll_columns.gd new file mode 100644 index 0000000..9cfc4a5 --- /dev/null +++ b/core/roll_columns.gd @@ -0,0 +1,81 @@ +class_name RollColumns +extends RefCounted +## Cards with columns (a multi-column table, RollTable.columns): after a roll +## card with columns picks its result and expands its text, fill() works out +## the other columns. +## +## - "row" (RollTable.COLUMNS_ROW): every column reads the same result's cells. +## - "each" (COLUMNS_EACH): each column after the first is rolled on its own, +## the same way the card was (the thread's dice and rerolls included). The +## first column is the card's own roll, so its result's changes and threads +## happen as usual. +## +## 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". + + +static func fill(node: Dictionary, f: Dictionary, ctx: RollContext, depth: int) -> void: + var t: RollTable = node["table"] + var rows: Array = [] + var parts := PackedStringArray() + var log: Array = [] + var why: Array = [] + for k in t.columns.size(): + var col: Dictionary = t.columns[k] + var nm := str(col.get("name", "")) + var row := {"name": nm, "text": "", "index": int(node.get("index", -1))} + if k > 0: + var w := str(col.get("when", "")).strip_edges() + if w != "": + var r := Expr.evaluate(w, ctx) + if r["error"] != "": + log.append({"text": "Column %s, only if %s: %s" % [nm, w, r["error"]], "error": true}) + if r["error"] != "" or not Expr.truthy(r["value"]): + row["skipped"] = true + rows.append(row) + continue + var text := "" + if k == 0: + text = str(node["summary"]) + row["value"] = node.get("value") + 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"]) + 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) + row["text"] = text + rows.append(row) + var save := str(col.get("save_as", "")).strip_edges() + if save != "": + ctx.save(save, plain(text), t.id) + if Formatter.strip_tags(text).strip_edges() != "": + parts.append("%s: %s" % [Formatter.escape_literal(nm), text]) + node["columns"] = rows + node["summary"] = " · ".join(parts) + Roller._log(node, log) + Roller._why(node, why) + + +## 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_columns.gd.uid b/core/roll_columns.gd.uid new file mode 100644 index 0000000..1a2c263 --- /dev/null +++ b/core/roll_columns.gd.uid @@ -0,0 +1 @@ +uid://6xxec1n2jspg diff --git a/core/roll_context.gd b/core/roll_context.gd index f701c46..5b260e6 100644 --- a/core/roll_context.gd +++ b/core/roll_context.gd @@ -108,6 +108,9 @@ func save(name: String, value: Variant, source_id: String = "") -> void: n = n.substr(1) if n == "": return + var steps := scale_steps(n) + if not steps.is_empty(): + value = Scales.store(steps, value) persistent_vars[n] = {"value": value, "source": source_id} persistent_changed = true elif n != "": @@ -221,6 +224,15 @@ func declared(name: String) -> RollTable: return _decl.get(name.strip_edges().trim_prefix("@")) +## The steps of board variable `name` (no "@") when a scale card declares it, +## else [] (Scales). +func scale_steps(name: String) -> Array[String]: + var card := declared(name) + if card == null or not card.is_scale(): + return [] + return card.steps + + ## Every declared variable name (no "@"). func declared_names() -> Array[String]: declared("") diff --git a/core/roll_lint.gd b/core/roll_lint.gd index df84d48..c0fd16d 100644 --- a/core/roll_lint.gd +++ b/core/roll_lint.gd @@ -74,6 +74,7 @@ static func lint_pipes(board: TowerBoard) -> Array[Dictionary]: out.append_array(lint_options(t)) out.append_array(lint_check(t)) out.append_array(lint_inputs(board, t)) + out.append_array(RollLintBook.lint(board, t)) for i in t.entries.size(): var e := t.entries[i] var first_other := "" diff --git a/core/roll_lint_book.gd b/core/roll_lint_book.gd new file mode 100644 index 0000000..60c07ae --- /dev/null +++ b/core/roll_lint_book.gd @@ -0,0 +1,48 @@ +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. +## Items are {table_id, entry_id, message, kind: "book", level: "error"|"hint"}. + + +static func lint(board: TowerBoard, t: RollTable) -> Array[Dictionary]: + var out: Array[Dictionary] = [] + for e in t.entries: + for p in e.pipes: + var to := board.get_table(p) + if to == null: + continue + var dice := e.dice_for(p) + if dice != "": + if not to.is_ranged() or to.kind != RollTable.KIND_ROLL: + out.append(_item(t, e.id, "The thread to %s rolls with %s, but only a card with numbered ranges can use other dice." % [_n(to), dice], "hint")) + elif not Dice.parse(dice).valid and Expr.check(dice) != "": + out.append(_item(t, e.id, "The thread to %s rolls with %s: %s" % [_n(to), dice, Expr.check(dice)], "error")) + var again := e.reroll_for(p) + if not again.is_empty(): + var left := 0 + for x in to.entries: + if again.has(x.id): + continue + left += 1 + var missing := again.filter(func(id: String) -> bool: return to.find_entry(id) == null) + if left == 0: + 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")) + if t.has_columns(): + for c: Dictionary in t.columns: + var w := str(c.get("when", "")) + if w != "" and Expr.check(w) != "": + out.append(_item(t, "", "Column %s, only if %s: %s" % [c.get("name", ""), w, Expr.check(w)], "error")) + if t.is_scale() and t.steps.size() < 2: + out.append(_item(t, "", "The scale %s needs at least two steps." % _n(t), "error")) + return out + + +static func _n(t: RollTable) -> String: + return Formatter.strip_tags(t.name).strip_edges() + + +static func _item(t: RollTable, entry_id: String, msg: String, level: String) -> Dictionary: + return {"table_id": t.id, "entry_id": entry_id, "message": msg, "kind": "book", "level": level} diff --git a/core/roll_lint_book.gd.uid b/core/roll_lint_book.gd.uid new file mode 100644 index 0000000..20b397d --- /dev/null +++ b/core/roll_lint_book.gd.uid @@ -0,0 +1 @@ +uid://7ht6b0osgunt diff --git a/core/roll_range.gd b/core/roll_range.gd index bc356e4..7af2b35 100644 --- a/core/roll_range.gd +++ b/core/roll_range.gd @@ -191,11 +191,17 @@ static func live_mod(t: RollTable, ctx: RollContext) -> Dictionary: ## Rolls the dice and adds the modifier. Returns {"value": int, "error": -## String}; dice faces go to ctx.faces when it's collecting them. -static func roll_value(t: RollTable, ctx: RollContext) -> Dictionary: +## String}; dice faces go to ctx.faces when it's collecting them. `dice_text` +## (a thread's "roll with … instead") replaces the card's own dice. +static func roll_value(t: RollTable, ctx: RollContext, dice_text: String = "") -> Dictionary: var total := 0 - if not t.is_expr_dice(): - var d := t.dice_obj() + var src := dice_text.strip_edges() + var d := t.dice_obj() + var plain := not t.is_expr_dice() + if src != "": + d = Dice.parse(src) + plain = d.valid + if plain: if ctx.faces != null: total = d.bonus for k in d.count: @@ -207,7 +213,7 @@ static func roll_value(t: RollTable, ctx: RollContext) -> Dictionary: else: total = d.roll(ctx.rng) else: - var r := Expr.evaluate(t.dice, ctx) + var r := Expr.evaluate(src if src != "" else t.dice, ctx) if r["error"] != "": return {"value": 0, "error": r["error"]} total = Expr.as_int(r, 0) @@ -240,9 +246,10 @@ static func limit(t: RollTable, v: int, ctx: RollContext) -> Dictionary: ## The result index for a rolled total: past the ends counts as the end -## result on a table that clamps; otherwise -1 when no range holds it. -static func index_for(t: RollTable, value: int) -> int: - if clamps(t): +## result on a table that clamps (or always, with `force_clamp`); otherwise -1 +## when no range holds it. +static func index_for(t: RollTable, value: int, force_clamp: bool = false) -> int: + if force_clamp or clamps(t): var s := span(t) value = clampi(value, s.x, s.y) for i in t.entries.size(): diff --git a/core/roll_table.gd b/core/roll_table.gd index 9239f34..f472399 100644 --- a/core/roll_table.gd +++ b/core/roll_table.gd @@ -35,7 +35,13 @@ const LOOPS: Array[String] = ["times", "while", "until"] ## A variable card with var_type "collection" declares a group of board ## values @_ (docs/PLAIN.md §3); its name labels the group. const VAR_COLLECTION := "collection" -const VAR_TYPES: Array[String] = ["number", "text", "list", VAR_COLLECTION] +## A variable card with var_type "scale" lists ordered steps (Scales). +const VAR_SCALE := "scale" +const VAR_TYPES: Array[String] = ["number", "text", "list", VAR_COLLECTION, VAR_SCALE] +## Cards with columns: one roll picks the row for every column ("row"), or +## each column is rolled on its own ("each"; RollColumns). +const COLUMNS_ROW := "row" +const COLUMNS_EACH := "each" ## Check cards (docs/PLAIN.md §4.1): success when the total is >= ("ge") or ## <= ("le") the target. const CHECK_CMPS: Array[String] = ["ge", "le"] @@ -72,6 +78,13 @@ var deck_empty: String = "reshuffle" ## What a Deck-mode card that waits for Shuffle gives once it's empty ("" = "Empty"). var deck_empty_text: String = "" var entries: Array[TableEntry] = [] +## Roll cards with columns (a multi-column table): Array of {"name": String, +## "save_as": value name (optional), "when": condition (optional)}. Column 0 +## is each result's own text; the others are TableEntry.cells. Empty = a +## plain one-column card. +var columns: Array = [] +## COLUMNS_ROW or COLUMNS_EACH. +var column_rolls: String = COLUMNS_ROW ## One of KINDS. var kind: String = KIND_ROLL @@ -101,6 +114,8 @@ var loop_expr: String = "" var var_name: String = "" var var_type: String = "number" var initial: String = "" +## Scale variables: the ordered steps, lowest first. +var steps: Array[String] = [] ## Check cards: the dice, the modifier and the target (expressions) and the ## comparison ("ge" or "le"). entries[0] is Success, entries[1] Failure. var check_dice: String = CHECK_DEFAULT_DICE @@ -176,6 +191,31 @@ static func create(p_kind: String, p_id: String, p_name: String, sub: String = " return t +## True for a roll card with columns. +func has_columns() -> bool: + return kind == KIND_ROLL and not columns.is_empty() + + +## The column names, in order. +func column_names() -> Array[String]: + var out: Array[String] = [] + for c: Dictionary in columns: + out.append(str(c.get("name", ""))) + return out + + +## Column `k`'s text on a result: its own text for column 0, else its cell. +static func cell_text(e: TableEntry, k: int) -> String: + if k == 0: + return e.text + return e.cells[k - 1] if k - 1 < e.cells.size() else "" + + +## True for a scale variable card. +func is_scale() -> bool: + return kind == KIND_VARIABLE and var_type == VAR_SCALE + + ## True for a collection variable card. func is_collection() -> bool: return kind == KIND_VARIABLE and var_type == VAR_COLLECTION @@ -426,138 +466,11 @@ static func _looks_literal(src: String) -> bool: func to_dict() -> Dictionary: - var list: Array = [] - for e in entries: - list.append(e.to_dict()) - var d := {"id": id, "name": name, "x": roundi(position.x), "y": roundi(position.y), "entries": list} - if kind != KIND_ROLL: - d["kind"] = kind - if collapsed: - d["collapsed"] = true - if details != "": - d["details"] = details - if not tags.is_empty(): - d["tags"] = tags.duplicate() - if color != "": - d["color"] = color - if roll_floor.strip_edges() != "": - d["roll_floor"] = roll_floor.strip_edges() - if roll_ceiling.strip_edges() != "": - d["roll_ceiling"] = roll_ceiling.strip_edges() - if width > 0.0: - d["w"] = roundi(width) - if list_height > 0.0: - d["list_h"] = roundi(list_height) - if is_ranged(): - d["dice"] = dice - if has_mod(): - d["dice_mod"] = dice_mod.strip_edges() - if card_mode: - d["card_mode"] = true - if deck_empty != "reshuffle": - d["deck_empty"] = deck_empty - if deck_empty_text != "": - d["deck_empty_text"] = deck_empty_text - if kind == KIND_CHOICE: - if choice != "pick": - d["choice"] = choice - if prompt != "": - d["prompt"] = prompt - if save_as != "": - d["save_as"] = save_as - if options_from.strip_edges() != "": - d["options_from"] = options_from.strip_edges() - if options_where.strip_edges() != "": - d["options_where"] = options_where.strip_edges() - if min_expr != "0": - d["min"] = min_expr - if max_expr != "99": - d["max"] = max_expr - elif kind == KIND_LOOP: - if loop_mode != "times": - d["loop"] = loop_mode - if loop_expr != "": - d["loop_expr"] = loop_expr - elif kind == KIND_VARIABLE: - if var_name != "": - d["var_name"] = var_name - if var_type != "number": - d["var_type"] = var_type - if initial != "": - d["initial"] = initial - elif kind == KIND_CHECK: - if check_dice != CHECK_DEFAULT_DICE: - d["check_dice"] = check_dice - if check_mod != "": - d["check_mod"] = check_mod - if check_cmp != "ge": - d["check_cmp"] = check_cmp - if check_target != CHECK_DEFAULT_TARGET: - d["check_target"] = check_target - if not inputs.is_empty(): - var list2: Array = [] - for inp: Dictionary in inputs: - var o := {"name": str(inp.get("name", ""))} - if str(inp.get("label", "")) != "": - o["label"] = str(inp["label"]) - if str(inp.get("default", "")) != "": - o["default"] = str(inp["default"]) - list2.append(o) - d["inputs"] = list2 - return d + return RollTableIO.to_dict(self) static func from_dict(d: Dictionary) -> RollTable: - var t := RollTable.new(str(d.get("id", "")), str(d.get("name", ""))) - t.position = Vector2(float(d.get("x", 0)), float(d.get("y", 0))) - t.collapsed = bool(d.get("collapsed", false)) - t.details = str(d.get("details", "")) - for tag: Variant in d.get("tags", []): - t.tags.append(str(tag)) - t.color = str(d.get("color", "")) - t.roll_floor = str(d.get("roll_floor", "")) - t.roll_ceiling = str(d.get("roll_ceiling", "")) - t.width = maxf(0.0, float(d.get("w", 0))) - t.list_height = maxf(0.0, float(d.get("list_h", 0))) - if d.has("dice"): - t.dice = str(d["dice"]) - elif int(d.get("die", 0)) > 1: - t.dice = "1d%d" % int(d["die"]) - t.dice_mod = expr_text(d.get("dice_mod", ""), "").strip_edges() - t.card_mode = bool(d.get("card_mode", false)) - t.deck_empty = "stop" if str(d.get("deck_empty", "reshuffle")) == "stop" else "reshuffle" - t.deck_empty_text = str(d.get("deck_empty_text", "")) - var k := str(d.get("kind", KIND_ROLL)) - t.kind = k if KINDS.has(k) else KIND_ROLL - var c := str(d.get("choice", "pick")) - t.choice = c if CHOICES.has(c) else "pick" - t.prompt = str(d.get("prompt", "")) - t.save_as = str(d.get("save_as", "")) - t.options_from = str(d.get("options_from", "")).strip_edges() if d.get("options_from") != null else "" - t.options_where = expr_text(d.get("options_where", ""), "").strip_edges() - t.min_expr = expr_text(d.get("min", "0"), "0") - t.max_expr = expr_text(d.get("max", "99"), "99") - var lm := str(d.get("loop", "times")) - t.loop_mode = lm if LOOPS.has(lm) else "times" - t.loop_expr = expr_text(d.get("loop_expr", ""), "") - t.var_name = str(d.get("var_name", "")).strip_edges().trim_prefix("@") - var vt := str(d.get("var_type", "number")) - t.var_type = vt if VAR_TYPES.has(vt) else "number" - t.initial = expr_text(d.get("initial", ""), "") - t.check_dice = expr_text(d.get("check_dice", CHECK_DEFAULT_DICE), CHECK_DEFAULT_DICE).strip_edges() - if t.check_dice == "": - t.check_dice = CHECK_DEFAULT_DICE - t.check_mod = expr_text(d.get("check_mod", ""), "").strip_edges() - var cc := str(d.get("check_cmp", "ge")) - t.check_cmp = cc if CHECK_CMPS.has(cc) else "ge" - t.check_target = expr_text(d.get("check_target", CHECK_DEFAULT_TARGET), CHECK_DEFAULT_TARGET).strip_edges() - if t.check_target == "": - t.check_target = CHECK_DEFAULT_TARGET - t.inputs = clean_inputs(d.get("inputs", [])) - for ed: Variant in d.get("entries", []): - if ed is Dictionary: - t.entries.append(TableEntry.from_dict(ed)) - return t + return RollTableIO.from_dict(d) ## Expression fields may arrive as JSON numbers: 3.0 -> "3". diff --git a/core/roll_table_io.gd b/core/roll_table_io.gd new file mode 100644 index 0000000..d972e1d --- /dev/null +++ b/core/roll_table_io.gd @@ -0,0 +1,176 @@ +class_name RollTableIO +extends RefCounted +## RollTable to and from its JSON Dictionary (RollTable.to_dict/from_dict +## delegate here). Keys at their defaults are left out. + + +static func to_dict(t: RollTable) -> Dictionary: + var list: Array = [] + for e in t.entries: + list.append(e.to_dict()) + var d := {"id": t.id, "name": t.name, "x": roundi(t.position.x), "y": roundi(t.position.y), "entries": list} + if t.kind != RollTable.KIND_ROLL: + d["kind"] = t.kind + if t.collapsed: + d["collapsed"] = true + if t.details != "": + d["details"] = t.details + if not t.tags.is_empty(): + d["tags"] = t.tags.duplicate() + if t.color != "": + d["color"] = t.color + if t.roll_floor.strip_edges() != "": + d["roll_floor"] = t.roll_floor.strip_edges() + if t.roll_ceiling.strip_edges() != "": + d["roll_ceiling"] = t.roll_ceiling.strip_edges() + if t.width > 0.0: + d["w"] = roundi(t.width) + if t.list_height > 0.0: + d["list_h"] = roundi(t.list_height) + if t.is_ranged(): + d["dice"] = t.dice + if t.has_mod(): + d["dice_mod"] = t.dice_mod.strip_edges() + if t.card_mode: + d["card_mode"] = true + if t.deck_empty != "reshuffle": + d["deck_empty"] = t.deck_empty + if t.deck_empty_text != "": + d["deck_empty_text"] = t.deck_empty_text + if not t.columns.is_empty(): + d["columns"] = clean_columns(t.columns) + if t.column_rolls != RollTable.COLUMNS_ROW: + d["column_rolls"] = t.column_rolls + if t.kind == RollTable.KIND_CHOICE: + if t.choice != "pick": + d["choice"] = t.choice + if t.prompt != "": + d["prompt"] = t.prompt + if t.save_as != "": + d["save_as"] = t.save_as + if t.options_from.strip_edges() != "": + d["options_from"] = t.options_from.strip_edges() + if t.options_where.strip_edges() != "": + d["options_where"] = t.options_where.strip_edges() + if t.min_expr != "0": + d["min"] = t.min_expr + if t.max_expr != "99": + d["max"] = t.max_expr + elif t.kind == RollTable.KIND_LOOP: + if t.loop_mode != "times": + d["loop"] = t.loop_mode + if t.loop_expr != "": + d["loop_expr"] = t.loop_expr + elif t.kind == RollTable.KIND_VARIABLE: + if t.var_name != "": + d["var_name"] = t.var_name + if t.var_type != "number": + d["var_type"] = t.var_type + if t.initial != "": + d["initial"] = t.initial + if t.var_type == RollTable.VAR_SCALE and not t.steps.is_empty(): + d["steps"] = t.steps.duplicate() + elif t.kind == RollTable.KIND_CHECK: + if t.check_dice != RollTable.CHECK_DEFAULT_DICE: + d["check_dice"] = t.check_dice + if t.check_mod != "": + d["check_mod"] = t.check_mod + if t.check_cmp != "ge": + d["check_cmp"] = t.check_cmp + if t.check_target != RollTable.CHECK_DEFAULT_TARGET: + d["check_target"] = t.check_target + if not t.inputs.is_empty(): + var list2: Array = [] + for inp: Dictionary in t.inputs: + var o := {"name": str(inp.get("name", ""))} + if str(inp.get("label", "")) != "": + o["label"] = str(inp["label"]) + if str(inp.get("default", "")) != "": + o["default"] = str(inp["default"]) + list2.append(o) + d["inputs"] = list2 + return d + + +static func from_dict(d: Dictionary) -> RollTable: + var t := RollTable.new(str(d.get("id", "")), str(d.get("name", ""))) + t.position = Vector2(float(d.get("x", 0)), float(d.get("y", 0))) + t.collapsed = bool(d.get("collapsed", false)) + t.details = str(d.get("details", "")) + for tag: Variant in d.get("tags", []): + t.tags.append(str(tag)) + t.color = str(d.get("color", "")) + t.roll_floor = str(d.get("roll_floor", "")) + t.roll_ceiling = str(d.get("roll_ceiling", "")) + t.width = maxf(0.0, float(d.get("w", 0))) + t.list_height = maxf(0.0, float(d.get("list_h", 0))) + if d.has("dice"): + t.dice = str(d["dice"]) + elif int(d.get("die", 0)) > 1: + t.dice = "1d%d" % int(d["die"]) + t.dice_mod = RollTable.expr_text(d.get("dice_mod", ""), "").strip_edges() + t.card_mode = bool(d.get("card_mode", false)) + t.deck_empty = "stop" if str(d.get("deck_empty", "reshuffle")) == "stop" else "reshuffle" + t.deck_empty_text = str(d.get("deck_empty_text", "")) + t.columns = clean_columns(d.get("columns", [])) + 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 + var c := str(d.get("choice", "pick")) + t.choice = c if RollTable.CHOICES.has(c) else "pick" + t.prompt = str(d.get("prompt", "")) + t.save_as = str(d.get("save_as", "")) + t.options_from = str(d.get("options_from", "")).strip_edges() if d.get("options_from") != null else "" + t.options_where = RollTable.expr_text(d.get("options_where", ""), "").strip_edges() + t.min_expr = RollTable.expr_text(d.get("min", "0"), "0") + t.max_expr = RollTable.expr_text(d.get("max", "99"), "99") + var lm := str(d.get("loop", "times")) + t.loop_mode = lm if RollTable.LOOPS.has(lm) else "times" + t.loop_expr = RollTable.expr_text(d.get("loop_expr", ""), "") + t.var_name = str(d.get("var_name", "")).strip_edges().trim_prefix("@") + var vt := str(d.get("var_type", "number")) + t.var_type = vt if RollTable.VAR_TYPES.has(vt) else "number" + t.initial = RollTable.expr_text(d.get("initial", ""), "") + t.steps = Scales.clean(d.get("steps", [])) + t.check_dice = RollTable.expr_text(d.get("check_dice", RollTable.CHECK_DEFAULT_DICE), RollTable.CHECK_DEFAULT_DICE).strip_edges() + if t.check_dice == "": + t.check_dice = RollTable.CHECK_DEFAULT_DICE + t.check_mod = RollTable.expr_text(d.get("check_mod", ""), "").strip_edges() + var cc := str(d.get("check_cmp", "ge")) + t.check_cmp = cc if RollTable.CHECK_CMPS.has(cc) else "ge" + t.check_target = RollTable.expr_text(d.get("check_target", RollTable.CHECK_DEFAULT_TARGET), RollTable.CHECK_DEFAULT_TARGET).strip_edges() + if t.check_target == "": + t.check_target = RollTable.CHECK_DEFAULT_TARGET + t.inputs = RollTable.clean_inputs(d.get("inputs", [])) + for ed: Variant in d.get("entries", []): + if ed is Dictionary: + t.entries.append(TableEntry.from_dict(ed)) + return t + + +## Cleans a "columns" value from JSON or the UI: Array of {name, save_as?, +## when?} with blank names dropped and empty keys left out. +static func clean_columns(v: Variant) -> Array: + var out: Array = [] + if not (v is Array): + return out + for item: Variant in v: + var nm := "" + var save := "" + var when := "" + if item is Dictionary: + nm = str(item.get("name", "")) if item.get("name") != null else "" + save = str(item.get("save_as", "")) if item.get("save_as") != null else "" + when = str(item.get("when", "")) if item.get("when") != null else "" + elif item is String: + nm = item + nm = nm.strip_edges() + if nm == "": + continue + var o := {"name": nm} + if save.strip_edges() != "": + o["save_as"] = save.strip_edges() + if when.strip_edges() != "": + o["when"] = when.strip_edges() + out.append(o) + return out diff --git a/core/roll_table_io.gd.uid b/core/roll_table_io.gd.uid new file mode 100644 index 0000000..bdbc777 --- /dev/null +++ b/core/roll_table_io.gd.uid @@ -0,0 +1 @@ +uid://cd7dqkehsn2ct diff --git a/core/roller.gd b/core/roller.gd index 575ca55..44f01fc 100644 --- a/core/roller.gd +++ b/core/roller.gd @@ -270,7 +270,7 @@ static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: _attach(f, sheet, ctx) await _enter(sheet, f, ctx, stack, true, true) _: - var node := RollCards.pick_node(t, ctx) + var node := RollCards.pick_for(t, ctx, f) if node.has("nat"): ctx.chain_vars["nat"] = node["nat"] node.erase("nat") @@ -303,6 +303,9 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr c["inline"] = true kids.append(c) node["summary"] = ex["text"] + if t.has_columns() and not node.has("kind"): + await RollColumns.fill(node, f, ctx, depth) + ctx.depth = depth # The Chosen entry of a dynamic pick reads as the option's label unless # it has text of its own. if node.has("option"): @@ -348,6 +351,10 @@ static func _queue_pipes(node: Dictionary, ctx: RollContext, stack: Array, depth var fr := {"op": OP_PIPE, "node": node, "entry": e, "to": p, "left": int(item["count"]), "save": e.save_for(p), "depth": depth} if item.has("with"): fr["with"] = item["with"] + if e.dice_for(p) != "": + fr["dice"] = e.dice_for(p) + if not e.reroll_for(p).is_empty(): + fr["reroll"] = e.reroll_for(p) var mode := e.combine_for(p) if mode != "all" and int(item["count"]) > 1: # Runs after every repeat: combines them (RollCombine). @@ -405,8 +412,9 @@ static func _do_pipe(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: f["left"] = int(f["left"]) - 1 stack.append(f) var fr := {"op": OP_ROLL, "id": f["to"], "parent": f["node"], "save": f["save"], "depth": f["depth"]} - if f.has("with"): - fr["with"] = f["with"] + for key in ["with", "dice", "reroll"]: + if f.has(key): + fr[key] = f[key] if f.get("no_follow", false): fr["no_follow"] = true stack.append(fr) diff --git a/core/scales.gd b/core/scales.gd new file mode 100644 index 0000000..8614eb5 --- /dev/null +++ b/core/scales.gd @@ -0,0 +1,65 @@ +class_name Scales +extends RefCounted +## Scale values (docs/LOGIC.md §5.4): a variable card with var_type "scale" +## lists ordered steps ("Supercold", "Cold", "Temperate", "Hot", "Superhot"). +## +## - The value is stored as the step's name, so {@climate} shows "Cold". +## - In rules it reads as the step's number (1 = the first step), and a quoted +## step name next to it reads as that step's number too, so +## @atmosphere >= "Thin" and @climate = toward(@climate, "Temperate") work. +## - Saving a number picks that step, stopping at the ends; saving a name +## matches the steps without caring about capitals. + + +## The step whose position (1-based) is `n`, kept within the ends. "" when +## there are no steps. +static func label_at(steps: Array, n: int) -> String: + if steps.is_empty(): + return "" + return str(steps[clampi(n, 1, steps.size()) - 1]) + + +## The position (1-based) of a step name, or 0 when it isn't one. Numbers are +## taken as positions as they are. +static func position_of(steps: Array, v: Variant) -> int: + if v is int or v is float: + return int(v) + var s := str(v).strip_edges().to_lower() + for k in steps.size(): + if str(steps[k]).to_lower() == s: + return k + 1 + return 0 + + +## What a scale variable stores for `v`: a number becomes the step at that +## position (kept within the ends), a step name its canonical spelling, and +## anything else is kept as it is. +static func store(steps: Array, v: Variant) -> Variant: + if steps.is_empty(): + return v + if v is int or v is float or (v is String and (v as String).is_valid_float()): + return label_at(steps, roundi(float(v))) + var k := position_of(steps, v) + return str(steps[k - 1]) if k > 0 else v + + +## Moves position `a` one step toward position `b`. +static func toward(a: Variant, b: Variant) -> int: + var x := int(Expr.to_value(a)) if Expr.is_number(Expr.to_value(a)) else 0 + var y := int(Expr.to_value(b)) if Expr.is_number(Expr.to_value(b)) else 0 + return x + signi(y - x) + + +## Cleans a "steps" value from JSON or the UI: trimmed names, blanks dropped. +static func clean(v: Variant) -> Array[String]: + var out: Array[String] = [] + var items: Array = [] + if v is Array: + items = v + elif v is String: + items = Array((v as String).split("\n")) + for item: Variant in items: + var s := str(item).strip_edges() + if s != "": + out.append(s) + return out diff --git a/core/scales.gd.uid b/core/scales.gd.uid new file mode 100644 index 0000000..6dcdf34 --- /dev/null +++ b/core/scales.gd.uid @@ -0,0 +1 @@ +uid://cw3pao4a4cybt diff --git a/core/table_entry.gd b/core/table_entry.gd index b4bbaad..78db0fc 100644 --- a/core/table_entry.gd +++ b/core/table_entry.gd @@ -45,6 +45,14 @@ var pipe_combine: Dictionary = {} ## target table id -> true: the roll waits before following this thread until ## the player continues (Roller.OP_PAUSE). Missing = no pause. var pipe_pause: Dictionary = {} +## target table id -> dice to roll the target with instead of its own +## ("3d10+70"; a ranged target only). Missing = the card's own dice. +var pipe_dice: Dictionary = {} +## target table id -> Array of the target's result ids to roll again on +## ("re-roll any result of 96+"). Missing = keep whatever comes up. +var pipe_reroll: Dictionary = {} +## Cards with columns: this result's text in columns 1.. (column 0 is `text`). +var cells: Array[String] = [] ## Choice options: what picking this costs (RollCosts): a value name and an ## amount (an expression). "" = free. var cost_value: String = "" @@ -215,6 +223,40 @@ func combine_for(target: String) -> String: return str(pipe_combine.get(target, "all")) +## The dice the thread rolls its card with instead of the card's own, or "". +func dice_for(target: String) -> String: + return str(pipe_dice.get(target, "")).strip_edges() + + +## The target's result ids the thread rolls again on (a copy; [] for none). +func reroll_for(target: String) -> Array[String]: + var out: Array[String] = [] + var v: Variant = pipe_reroll.get(target) + if v is Array: + for x: Variant in v: + if str(x) != "" and not out.has(str(x)): + out.append(str(x)) + return out + + +func set_pipe_dice(target: String, dice: String) -> void: + if dice.strip_edges() == "": + pipe_dice.erase(target) + else: + pipe_dice[target] = dice.strip_edges() + + +func set_pipe_reroll(target: String, ids: Array) -> void: + var clean: Array[String] = [] + for x: Variant in ids: + if str(x) != "" and not clean.has(str(x)): + clean.append(str(x)) + if clean.is_empty(): + pipe_reroll.erase(target) + else: + pipe_reroll[target] = clean + + ## Removes a pipe along with its options. func remove_pipe(target: String) -> void: pipes.erase(target) @@ -226,6 +268,8 @@ func remove_pipe(target: String) -> void: pipe_color.erase(target) pipe_combine.erase(target) pipe_pause.erase(target) + pipe_dice.erase(target) + pipe_reroll.erase(target) func to_dict() -> Dictionary: @@ -252,7 +296,9 @@ func to_dict() -> Dictionary: var col := str(pipe_color.get(p, "")) var comb := combine_for(p) var paused := pipe_pause.has(p) - if expr == "" and n == 1 and s == "" and w == "" and not other and wv == null and col == "" and comb == "all" and not paused: + var dice := dice_for(p) + var again := reroll_for(p) + if expr == "" and n == 1 and s == "" and w == "" and not other and wv == null and col == "" and comb == "all" and not paused and dice == "" and again.is_empty(): list.append(p) else: var po := {"table": p} @@ -274,10 +320,16 @@ func to_dict() -> Dictionary: po["combine"] = comb if paused: po["pause"] = true + if dice != "": + po["dice"] = dice + if not again.is_empty(): + po["reroll"] = again list.append(po) d["pipes"] = list if has_range: d["range"] = [range_lo, range_hi] + if not cells.is_empty(): + d["cells"] = cells.duplicate() if page != "": d["page"] = page if image != "": @@ -316,8 +368,14 @@ static func from_dict(d: Dictionary) -> TableEntry: e.pipe_combine[target] = str(p["combine"]) if bool(p.get("pause", false)): e.pipe_pause[target] = true + e.set_pipe_dice(target, str(p.get("dice", "")) if p.get("dice") != null else "") + if p.get("reroll") is Array: + e.set_pipe_reroll(target, p["reroll"]) elif str(p) != "": e.add_pipe(str(p)) + if d.get("cells") is Array: + for c: Variant in d["cells"]: + e.cells.append(str(c) if c != null else "") var r: Variant = d.get("range") if r is Array and r.size() == 2: e.has_range = true diff --git a/io/json_canon.gd b/io/json_canon.gd index 09edd42..9f2bcca 100644 --- a/io/json_canon.gd +++ b/io/json_canon.gd @@ -129,7 +129,7 @@ static func _canon_table(td: Dictionary) -> Dictionary: for e in src_entries: entries.append(_canon_entry(e)) t["entries"] = entries - _keep(td, t, ["color", "w", "list_h", "roll_floor", "roll_ceiling", "deck_empty_text"]) + _keep(td, t, ["color", "w", "list_h", "roll_floor", "roll_ceiling", "deck_empty_text", "columns", "column_rolls", "steps"]) return t @@ -180,11 +180,11 @@ static func _canon_entry(ev: Variant) -> Dictionary: var wv := _canon_with(p.get("with")) if not wv.is_empty(): np["with"] = wv - _keep(p, np, ["color", "combine", "pause"]) + _keep(p, np, ["color", "combine", "pause", "dice", "reroll"]) pipes.append(np) if not pipes.is_empty(): e["pipes"] = pipes - _keep(ed, e, ["page", "image"]) + _keep(ed, e, ["page", "image", "cells"]) if ed.get("cost") is Dictionary: e["cost"] = ed["cost"] return e diff --git a/tests/test_book_tables.gd b/tests/test_book_tables.gd new file mode 100644 index 0000000..ce98e4d --- /dev/null +++ b/tests/test_book_tables.gd @@ -0,0 +1,226 @@ +extends TestBase +## Book-table features in the engine: scale values, cards with columns, and +## threads that roll with other dice or roll again on some results. +## Run: godot --headless --path . -s res://tests/test_book_tables.gd -- --sample + + +func _init() -> void: + _test_scales() + _test_scale_effects() + await _test_columns_row() + await _test_columns_each() + _test_dice_override() + _test_reroll() + _test_save_load() + _test_lint() + finish() + + +const CLIMATE := ["Supercold", "Cold", "Temperate", "Hot", "Superhot"] + + +func _board() -> TowerBoard: + var b := TowerBoard.new() + var v := RollTable.create("variable", "v_climate", "Climate", "scale") + v.var_name = "climate" + v.steps.assign(CLIMATE) + b.tables.append(v) + var d := RollTable.create("variable", "v_atmo", "Atmosphere", "scale") + d.var_name = "atmo" + d.steps.assign(["None", "Thin", "Medium", "Dense"]) + b.tables.append(d) + return b + + +func _ctx(b: TowerBoard, seed_value: int = 1) -> RollContext: + var rng := RandomNumberGenerator.new() + rng.seed = seed_value + return Roller.new_context(b, rng, {}, {}) + + +func _ev(src: String, ctx: RollContext) -> Variant: + return Expr.evaluate(src, ctx)["value"] + + +func _test_scales() -> void: + var b := _board() + var ctx := _ctx(b) + ctx.save("@climate", 2) + _eq(ctx.get_value("@climate"), "Cold", "a number saves as the step at that position") + ctx.save("@climate", "temperate") + _eq(ctx.get_value("@climate"), "Temperate", "a step name saves in its own spelling") + ctx.save("@climate", 9) + _eq(ctx.get_value("@climate"), "Superhot", "past the top stops at the last step") + ctx.save("@climate", -3) + _eq(ctx.get_value("@climate"), "Supercold", "below the bottom stops at the first step") + ctx.save("@climate", "Cold") + _eq(_ev("@climate", ctx), 2, "a scale reads as its step's number") + _eq(_ev("@climate < \"Temperate\"", ctx), true, "a step name beside a scale reads as its number") + _eq(_ev("@climate >= \"Hot\"", ctx), false, "comparing steps") + _eq(_ev("toward(@climate, \"Temperate\")", ctx), 3, "toward moves one step") + _eq(_ev("@atmo >= \"Thin\"", ctx), false, "an unset scale reads as 0, below every step") + ctx.save("@atmo", "Medium") + _eq(_ev("@climate = \"Cold\" and @atmo >= \"Thin\"", ctx), true, "each step name goes with the scale beside it") + _eq(_ev("\"Cold\" + \"!\"", ctx), "Cold!", "text with no scale beside it stays text") + var text := TextExpander.render("It is {@climate}.", ctx) + _check(text.contains("Cold"), "{@climate} shows the step's name") + + +func _test_scale_effects() -> void: + var b := _board() + var ctx := _ctx(b) + Effects.run("@climate = \"Hot\"", ctx) + Effects.run("@climate += 1", ctx) + _eq(ctx.get_value("@climate"), "Superhot", "+= moves up a step") + Effects.run("@climate += 1", ctx) + _eq(ctx.get_value("@climate"), "Superhot", "and stops at the top") + var log := Effects.run("@climate -= 2", ctx) + _eq(ctx.get_value("@climate"), "Temperate", "-= moves down") + _check(str(log[0]["text"]).contains("Temperate") and str(log[0]["text"]).contains("steps"), "the log names the steps: %s" % log[0]["text"]) + Effects.run("@climate = 1", ctx) + Effects.run("@climate = toward(@climate, \"Temperate\")", ctx) + _eq(ctx.get_value("@climate"), "Cold", "toward the middle from the bottom") + Effects.run("@atmo = \"Thin\"; @atmo = max(@atmo, \"Medium\")", ctx) + _eq(ctx.get_value("@atmo"), "Medium", "raise to at least Medium") + var bad := Effects.run("@climate *= 2", ctx) + _check(bad[0].get("error", false), "a scale can't be multiplied") + + +## World type card: 1d10, 3 results, columns Resources | Water | Life. +func _type_card(rolls: String) -> RollTable: + var t := RollTable.new("type", "Oceanic") + t.dice = "1d10" + t.column_rolls = rolls + t.columns = [{"name": "Resources", "save_as": "@res"}, {"name": "Water", "save_as": "@water"}, + {"name": "Life", "save_as": "@life", "when": "@water != \"None\""}] + var rows := [[1, 3, "Poor", "None", "None"], [4, 9, "Rich", "Plentiful", "Simple"], [10, 10, "Ultra-Rich", "Maximal", "Complex"]] + for r: Array in rows: + var e := TableEntry.new("e%d" % r[0], r[2]) + e.has_range = true + e.range_lo = r[0] + e.range_hi = r[1] + e.cells.assign([r[3], r[4]]) + t.entries.append(e) + return t + + +func _test_columns_row() -> void: + var b := TowerBoard.new() + b.tables.append(_type_card(RollTable.COLUMNS_ROW)) + for s in 20: + var ctx := _ctx(b, s) + var node := await Roller.roll_async(b, "type", ctx) + var e: TableEntry = node["entry"] + _eq(ctx.get_value("@res"), Formatter.strip_tags(e.text), "row: column 0 saves the result's text") + if e.cells[0] == "None": + _eq(ctx.get_value("@life"), null, "a skipped column saves nothing") + _check(bool((node["columns"] as Array)[2].get("skipped", false)), "and is marked skipped") + else: + _eq(ctx.get_value("@life"), e.cells[1], "row: every column reads the same result") + _check(str(node["summary"]).begins_with("Resources: "), "the summary names the columns: %s" % node["summary"]) + + +func _test_columns_each() -> void: + var b := TowerBoard.new() + b.tables.append(_type_card(RollTable.COLUMNS_EACH)) + var mixed := false + for s in 60: + var ctx := _ctx(b, s) + var node := await Roller.roll_async(b, "type", ctx) + var cols: Array = node["columns"] + if int(cols[0]["index"]) != int(cols[1]["index"]): + mixed = true + var columns_rolled := (node["why"] as Array).filter(func(f: Dictionary) -> bool: return str(f.get("column", "")) != "") + _check(columns_rolled.size() >= 1, "each: the other columns are rolled with why facts") + _check(mixed, "each: columns can land on different rows") + + +## Feature: 1d100 card, the thread rolls it with 3d10+70. +func _feature_board() -> TowerBoard: + var b := TowerBoard.new() + var start := RollTable.new("start", "Start") + var e := TableEntry.new("s1", "Go") + e.add_pipe("feat") + e.set_pipe_dice("feat", "3d10+70") + start.entries.append(e) + var feat := RollTable.new("feat", "Feature") + for r: Array in [[1, 70, "Nothing"], [71, 95, "Something"], [96, 100, "Multiple"]]: + var x := TableEntry.new("f%d" % r[0], r[2]) + x.has_range = true + x.range_lo = r[0] + x.range_hi = r[1] + feat.entries.append(x) + b.tables.append(start) + b.tables.append(feat) + return b + + +func _test_dice_override() -> void: + var b := _feature_board() + var low := 100 + for s in 80: + var tree := Roller.roll(b, "start", _ctx(b, s).rng) + var kid: Dictionary = tree["children"][0] + low = mini(low, int(kid["value"])) + _check(str((kid["why"] as Array)[0]["dice"]) == "3d10+70", "the why fact names the thread's dice") + _check(low >= 73, "3d10+70 never rolls below 73 (lowest %d)" % low) + _eq(DescribeCards.pipe(b.get_table("start").entries[0], "feat", b), "with 3d10+70", "the thread label says the dice") + + +func _test_reroll() -> void: + var b := _feature_board() + var e := b.get_table("start").entries[0] + e.set_pipe_dice("feat", "") + e.set_pipe_reroll("feat", ["f96"]) + var skipped := false + for s in 200: + var tree := Roller.roll(b, "start", _ctx(b, s).rng) + var kid: Dictionary = tree["children"][0] + _check((kid["entry"] as TableEntry).id != "f96", "a result the thread rolls again on never stays") + for f: Dictionary in kid.get("why", []): + if f["type"] == "reroll": + skipped = true + _check(skipped, "a reroll why fact is recorded") + _eq(DescribeCards.pipe(e, "feat", b), "again on 96–00", "the label lists the numbers") + e.set_pipe_reroll("feat", ["f1", "f71", "f96"]) + var tree2 := Roller.roll(b, "start", _ctx(b).rng) + _eq(str(tree2["children"][0]["stop"]), RollCards.ALL_REROLLED, "rolling again on everything stops") + + +func _test_save_load() -> void: + var b := _board() + b.tables.append(_type_card(RollTable.COLUMNS_EACH)) + for t in _feature_board().tables: + b.tables.append(t) + b.get_table("start").entries[0].set_pipe_reroll("feat", ["f96"]) + var text := JSON.stringify(b.to_dict()) + var back := TowerBoard.new() + back.load_dict(JSON.parse_string(text)) + _eq(back.get_table("v_climate").steps, CLIMATE, "scale steps round-trip") + var t := back.get_table("type") + _eq(t.column_rolls, RollTable.COLUMNS_EACH, "column rolls round-trip") + _eq(t.column_names(), ["Resources", "Water", "Life"], "columns round-trip") + _eq(str(t.columns[2].get("when", "")), "@water != \"None\"", "a column's condition round-trips") + _eq(t.entries[1].cells, ["Plentiful", "Simple"], "cells round-trip") + var se := back.get_table("start").entries[0] + _eq(se.dice_for("feat"), "3d10+70", "thread dice round-trip") + _eq(se.reroll_for("feat"), ["f96"], "thread rerolls round-trip") + var canon := JsonIO.canonical(JSON.parse_string(text)) + var again := TowerBoard.new() + again.load_dict(canon) + _eq(again.get_table("type").entries[1].cells, ["Plentiful", "Simple"], "import keeps cells") + _eq(again.get_table("start").entries[0].reroll_for("feat"), ["f96"], "import keeps rerolls") + _eq(again.get_table("v_climate").steps, CLIMATE, "import keeps steps") + + +func _test_lint() -> void: + var b := _feature_board() + var e := b.get_table("start").entries[0] + e.set_pipe_reroll("feat", ["f1", "f71", "f96"]) + 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("every result")), "lint: rerolling everything") + var s := RollTable.create("variable", "v", "Odd", "scale") + s.steps.assign(["Only"]) + b.tables.append(s) + msgs = Roller.lint_pipes(b).map(func(i: Dictionary) -> String: return str(i["message"])) + _check(msgs.any(func(m: String) -> bool: return m.contains("two steps")), "lint: a one-step scale")