Size audit: split Describe and JsonIO into helper files
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9f06af9676
commit
b1525687ad
10 changed files with 711 additions and 645 deletions
389
core/describe.gd
389
core/describe.gd
|
|
@ -356,373 +356,8 @@ static func _expr(expr: String, L: Dictionary) -> String:
|
|||
return _short(out, src)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- cards and pipes
|
||||
|
||||
## A pick card's dynamic options source: "your Skills, level 1 or more",
|
||||
## "your Contacts", "your Skill values, where Chosen option is not Pilot".
|
||||
## "" for a card without options_from; the pattern as written when it's bad.
|
||||
static func options(table: RollTable, board: TowerBoard) -> String:
|
||||
if table == null or table.options_from.strip_edges() == "":
|
||||
return ""
|
||||
var L := _labels(board)
|
||||
var p := RollTable.parse_options_from(table.options_from)
|
||||
var s := ""
|
||||
match str(p["kind"]):
|
||||
"prefix":
|
||||
s = "your " + _label("@%s*" % p["name"], L)
|
||||
"list":
|
||||
s = "your " + _label("@" + str(p["name"]), L)
|
||||
_:
|
||||
return table.options_from.strip_edges()
|
||||
var w := _where(table.options_where, L)
|
||||
if w != "":
|
||||
s += ", " + w
|
||||
return _short(s, table.options_description())
|
||||
|
||||
|
||||
## The options_where filter as a short tail: "level 1 or more" for one
|
||||
## comparison on option_value, else "where <condition>"; "" when empty.
|
||||
static func _where(where: String, L: Dictionary) -> String:
|
||||
var src := where.strip_edges()
|
||||
if src == "":
|
||||
return ""
|
||||
var m := Builder.parse_condition(src)
|
||||
if m["ok"] and (m["clauses"] as Array).size() == 1:
|
||||
var c: Dictionary = m["clauses"][0]
|
||||
if str(c["var"]) == "option_value" and ["eq", "ge", "le", "gt", "lt"].has(str(c["cmp"])):
|
||||
var tail := _tail(str(c["cmp"]), str(c["value"]), L).trim_prefix("is ")
|
||||
return "level " + tail
|
||||
return "where " + _condition(src, L)
|
||||
|
||||
|
||||
## A pipe's label in plain words, parts joined with " · ": its inputs ("Tier
|
||||
## 3"), "only if <condition>" or "otherwise", the count ("×2", "×Terms") and
|
||||
## "saves <name>". "" for a plain pipe.
|
||||
static func pipe(entry: TableEntry, target_id: String, board: TowerBoard) -> String:
|
||||
if entry == null:
|
||||
return ""
|
||||
var L := _labels(board)
|
||||
var parts := PackedStringArray()
|
||||
var w := entry.with_for(target_id)
|
||||
for nm: String in w:
|
||||
parts.append("%s %s" % [_label(nm, L), _expr(str(w[nm]), L)])
|
||||
var cond := entry.when_for(target_id)
|
||||
if cond != "":
|
||||
parts.append("only if " + _condition(cond, L))
|
||||
elif entry.is_otherwise(target_id):
|
||||
parts.append("otherwise")
|
||||
var ce := entry.count_expr(target_id)
|
||||
if ce != "":
|
||||
parts.append("×" + _expr(ce, L))
|
||||
elif entry.count_for(target_id) != 1:
|
||||
parts.append("×%d" % entry.count_for(target_id))
|
||||
var sv := entry.save_for(target_id)
|
||||
if sv != "":
|
||||
parts.append("saves " + _label(sv, L))
|
||||
return " · ".join(parts)
|
||||
|
||||
|
||||
## 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:
|
||||
if table == null or table.kind != RollTable.KIND_CHECK:
|
||||
return ""
|
||||
var L := _labels(board)
|
||||
var roll := _with_mod(table.check_dice, table.check_mod, L)
|
||||
var mod := table.check_mod.strip_edges()
|
||||
var target := _expr(table.check_target, L)
|
||||
var num := Expr.is_number(table.check_target.strip_edges())
|
||||
var need := ""
|
||||
if table.check_cmp == "le":
|
||||
need = ("%s or less" % target) if num else "at most " + target
|
||||
else:
|
||||
need = ("%s or more" % target) if num else "at least " + target
|
||||
return _short("Roll %s, need %s" % [roll, need], "Roll %s %s vs %s" % [table.check_dice, mod, table.check_target])
|
||||
|
||||
|
||||
## A ranged roll table's roll: "Roll d20 + Luck", "Roll 2D − Fatigue",
|
||||
## "Roll d100". "" for other cards.
|
||||
static func roll(table: RollTable, board: TowerBoard) -> String:
|
||||
if table == null or table.kind != RollTable.KIND_ROLL or not table.is_ranged():
|
||||
return ""
|
||||
return "Roll " + _with_mod(table.dice, table.dice_mod, _labels(board))
|
||||
|
||||
|
||||
## Dice plus a modifier in words: "2D + Strength modifier", "d20 − Fatigue".
|
||||
static func _with_mod(dice_src: String, mod_src: String, L: Dictionary) -> String:
|
||||
var out := _expr(dice_src, L)
|
||||
var mod := mod_src.strip_edges()
|
||||
if mod != "":
|
||||
var mt := Builder.tokens(mod)
|
||||
if not mt.is_empty() and mt[0]["s"] == "-":
|
||||
out += " %s %s" % [MINUS, _expr(mod.substr(1), L)]
|
||||
else:
|
||||
out += " + " + _expr(mod, L)
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- why
|
||||
|
||||
## One trace fact (Roller node/step "why") as a sentence. Plain mode uses
|
||||
## labels and words ("Skipped Tier 3 because Luck was 1 (needs 2 or more)");
|
||||
## text mode (plain = false) shows the rules as written ("Skipped tier3: when
|
||||
## @luck >= 2 was false (@luck = 1)"). Unknown facts give a short dump.
|
||||
static func why(fact: Dictionary, board: TowerBoard, plain: bool = true) -> String:
|
||||
if fact == null:
|
||||
return ""
|
||||
var L := _labels(board)
|
||||
var s := ""
|
||||
match str(fact.get("type", "")):
|
||||
"roll":
|
||||
s = _why_roll(fact, L, plain)
|
||||
"check":
|
||||
s = _why_check(fact, L, plain)
|
||||
"when":
|
||||
s = _why_when(fact, board, L, plain)
|
||||
"otherwise":
|
||||
var to := _table(str(fact.get("to", "")), board, plain)
|
||||
if bool(fact.get("result", false)):
|
||||
s = "Took %s because no condition was true" % to if plain else "%s: otherwise, ran (no condition was true)" % to
|
||||
else:
|
||||
s = "Skipped %s because a condition was true" % to if plain else "%s: otherwise, skipped" % to
|
||||
"case":
|
||||
s = _why_case(fact, L, plain)
|
||||
"show_if":
|
||||
var h := int(fact.get("hidden", 0))
|
||||
var parts := PackedStringArray()
|
||||
if h > 0:
|
||||
parts.append(("%d option hidden by its condition" if h == 1 else "%d options hidden by their conditions") % h)
|
||||
if bool(fact.get("chosen_hidden", false)):
|
||||
parts.append("the options from values were hidden")
|
||||
s = ", and ".join(parts)
|
||||
if s != "":
|
||||
s = s.substr(0, 1).to_upper() + s.substr(1)
|
||||
if not plain:
|
||||
s = "show_if hid %d option(s)%s" % [h, ", and the Chosen result" if bool(fact.get("chosen_hidden", false)) else ""]
|
||||
"options_where":
|
||||
var kept := int(fact.get("kept", 0))
|
||||
var total := int(fact.get("total", 0))
|
||||
if plain:
|
||||
var from := str(fact.get("from", ""))
|
||||
var p := RollTable.parse_options_from(from)
|
||||
var what := _label("@%s*" % p["name"], L) if str(p["kind"]) == "prefix" else (_label("@" + str(p["name"]), L) if str(p["kind"]) == "list" else "options")
|
||||
s = "Offered %d of %d %s (%s)" % [kept, total, what, _where(str(fact.get("expr", "")), L)]
|
||||
else:
|
||||
s = "options_where %s kept %d of %d" % [fact.get("expr", ""), kept, total]
|
||||
"effect":
|
||||
s = _why_effect(fact, L, plain)
|
||||
"input":
|
||||
var nm := str(fact.get("name", ""))
|
||||
var val := Expr.format_value(fact.get("value"))
|
||||
var from_pipe := str(fact.get("from", "")) == "pipe"
|
||||
if plain:
|
||||
s = "%s was %s (%s)" % [_label(nm, L), val, "from the thread" if from_pipe else "default"]
|
||||
else:
|
||||
s = "input %s = %s (%s)" % [nm, val, "with" if from_pipe else "default"]
|
||||
_:
|
||||
s = JSON.stringify(fact)
|
||||
if s.length() > MAX_LEN * 2:
|
||||
s = s.substr(0, MAX_LEN * 2 - 1) + "…"
|
||||
return s
|
||||
|
||||
|
||||
static func _table(id: String, board: TowerBoard, plain: bool) -> String:
|
||||
if not plain or board == null:
|
||||
return id
|
||||
var t := board.get_table(id)
|
||||
if t == null:
|
||||
return id
|
||||
var n := Formatter.strip_tags(t.name).strip_edges()
|
||||
return n if n != "" else id
|
||||
|
||||
|
||||
## "3 + 4 = 7" (or "5" for one die).
|
||||
static func _faces(faces: Variant) -> String:
|
||||
if not (faces is Array) or (faces as Array).is_empty():
|
||||
return ""
|
||||
var parts := PackedStringArray()
|
||||
var sum := 0.0
|
||||
for f: Variant in faces:
|
||||
parts.append(Expr.format_value(f))
|
||||
sum += float(Expr.to_value(f)) if Expr.is_number(f) else 0.0
|
||||
if parts.size() == 1:
|
||||
return parts[0]
|
||||
return "%s = %s" % [" + ".join(parts), Expr.format_value(sum)]
|
||||
|
||||
|
||||
static func _nonzero(v: Variant) -> bool:
|
||||
var n: Variant = Expr.to_value(v)
|
||||
return Expr.is_number(n) and n != 0
|
||||
|
||||
|
||||
## "+2", "−1", "+0".
|
||||
static func signed_number(n: int) -> String:
|
||||
return _signed(n)
|
||||
|
||||
|
||||
static func _signed(v: Variant) -> String:
|
||||
var n: Variant = Expr.to_value(v)
|
||||
if not Expr.is_number(n):
|
||||
return str(v)
|
||||
return ("+" + Expr.format_value(n)) if n >= 0 else (MINUS + Expr.format_value(-n))
|
||||
|
||||
|
||||
## A roll fact as a sentence: "Rolled 17, +3 for Luck = 20". A total past
|
||||
## the table's ends adds "past the top of the table, so it counts as 24"
|
||||
## (fact key counts_as).
|
||||
static func _why_roll(f: Dictionary, L: Dictionary, plain: bool) -> String:
|
||||
var total := Expr.format_value(f.get("total"))
|
||||
match str(f.get("pick", "dice")):
|
||||
"weighted":
|
||||
return "Rolled %s on %s" % [total, f.get("dice", "")] if plain else "roll %s: %s" % [f.get("dice", ""), total]
|
||||
"card":
|
||||
return "Drew card %s" % total if plain else "draw: card %s" % total
|
||||
var faces := _faces(f.get("faces"))
|
||||
var past := f.has("counts_as")
|
||||
var ends := Expr.format_value(f.get("counts_as"))
|
||||
if not plain:
|
||||
var t := "roll %s: %s" % [f.get("dice", ""), faces if faces != "" else total]
|
||||
if f.has("mod") and _nonzero(f["mod"]):
|
||||
t += " %s = %s" % [_signed(f["mod"]).replace(MINUS, "-"), Expr.format_value(f.get("raw", f.get("total")))]
|
||||
if f.has("limited"):
|
||||
t += " (%s %s: %s)" % ["min" if f["limited"] == "floor" else "max", f.get("limit_expr", ""), total]
|
||||
if past:
|
||||
t += " (past the end: %s)" % ends
|
||||
return t
|
||||
var s := "Worked out %s" % total
|
||||
if faces != "":
|
||||
s = "Rolled " + faces
|
||||
if f.has("mod") and _nonzero(f["mod"]):
|
||||
var why_mod := ""
|
||||
if str(f.get("mod_expr", "")) != "":
|
||||
why_mod = " for " + _expr(str(f["mod_expr"]).trim_prefix("-"), L)
|
||||
s += ", %s%s = %s" % [_signed(f["mod"]), why_mod, Expr.format_value(f.get("raw", f.get("total")))]
|
||||
if f.has("limited"):
|
||||
var up: bool = f["limited"] == "floor"
|
||||
s += ", %s to %s (never %s %s)" % ["raised" if up else "lowered", total, "below" if up else "above", _expr(str(f.get("limit_expr", "")), L)]
|
||||
if past:
|
||||
var top: bool = float(Expr.to_value(f.get("counts_as"))) < float(Expr.to_value(f.get("total")))
|
||||
s += ", past the %s of the table, so it counts as %s" % ["top" if top else "bottom", ends]
|
||||
return s
|
||||
|
||||
|
||||
static func _why_check(f: Dictionary, L: Dictionary, plain: bool) -> String:
|
||||
var faces := _faces(f.get("faces"))
|
||||
var nat := Expr.format_value(f.get("nat"))
|
||||
var total := Expr.format_value(f.get("total"))
|
||||
var target := Expr.format_value(f.get("target"))
|
||||
var le := str(f.get("cmp", "ge")) == "le"
|
||||
var ok := bool(f.get("success", false))
|
||||
if not plain:
|
||||
return "check %s%s vs %s (%s): %s %s = %s → %s" % [f.get("dice", ""),
|
||||
(" + " + str(f.get("mod_expr", ""))) if str(f.get("mod_expr", "")) != "" else "", f.get("target_expr", target),
|
||||
f.get("cmp", "ge"), nat, _signed(f.get("mod", 0)).replace(MINUS, "-"), total, "success" if ok else "failure"]
|
||||
var s := "Rolled " + (faces if faces != "" else nat)
|
||||
if _nonzero(f.get("mod", 0)):
|
||||
s += ", %s = %s" % [_signed(f.get("mod", 0)), total]
|
||||
s += ": needed %s or %s, %s" % [target, "less" if le else "more", "success" if ok else "failure"]
|
||||
return s
|
||||
|
||||
|
||||
## "Luck was 1 and Social Standing was 9" from a fact's values.
|
||||
static func _values(values: Variant, L: Dictionary, plain: bool) -> String:
|
||||
if not (values is Dictionary) or (values as Dictionary).is_empty():
|
||||
return ""
|
||||
var parts := PackedStringArray()
|
||||
for key: Variant in values:
|
||||
var nm := str(key)
|
||||
var v: Variant = values[key]
|
||||
if plain:
|
||||
parts.append(("%s wasn't set" % _label(nm, L)) if v == null else "%s was %s" % [_label(nm, L), _shown(v)])
|
||||
else:
|
||||
parts.append("%s = %s" % [nm, "unset" if v == null else Expr.format_value(v)])
|
||||
if not plain:
|
||||
return ", ".join(parts)
|
||||
if parts.size() == 1:
|
||||
return parts[0]
|
||||
return ", ".join(parts.slice(0, parts.size() - 1)) + " and " + parts[parts.size() - 1]
|
||||
|
||||
|
||||
static func _shown(v: Variant) -> String:
|
||||
var s := Expr.format_value(v)
|
||||
return s if s != "" else "empty"
|
||||
|
||||
|
||||
## "(needs 2 or more)" for one comparison on a value that was read, else
|
||||
## "(rule: <condition>)".
|
||||
static func _needs(expr: String, values: Variant, L: Dictionary) -> String:
|
||||
var m := Builder.parse_condition(expr)
|
||||
if m["ok"] and (m["clauses"] as Array).size() == 1:
|
||||
var c: Dictionary = m["clauses"][0]
|
||||
if values is Dictionary and (values as Dictionary).has(str(c["var"])):
|
||||
var tail := _tail(str(c["cmp"]), str(c["value"]), L)
|
||||
if tail.begins_with("is "):
|
||||
tail = tail.substr(3)
|
||||
elif tail.begins_with("includes "):
|
||||
tail = "to include " + tail.substr(9)
|
||||
return "(needs %s)" % tail
|
||||
return "(rule: %s)" % _condition(expr, L)
|
||||
|
||||
|
||||
static func _why_when(f: Dictionary, board: TowerBoard, L: Dictionary, plain: bool) -> String:
|
||||
var to := _table(str(f.get("to", "")), board, plain)
|
||||
var expr := str(f.get("expr", ""))
|
||||
var ok := bool(f.get("result", false))
|
||||
if not plain:
|
||||
var t := "%s %s: when %s was %s" % ["Took" if ok else "Skipped", to, expr, "true" if ok else "false"]
|
||||
if f.has("error"):
|
||||
t = "Skipped %s: when %s failed: %s" % [to, expr, f["error"]]
|
||||
var vals := _values(f.get("values"), L, false)
|
||||
return t + (" (%s)" % vals if vals != "" else "")
|
||||
if f.has("error"):
|
||||
return "Skipped %s: its condition couldn't be worked out (%s)" % [to, f["error"]]
|
||||
var vals2 := _values(f.get("values"), L, true)
|
||||
var verb := "Took" if ok else "Skipped"
|
||||
if vals2 == "":
|
||||
return "%s %s: %s was %s" % [verb, to, _condition(expr, L), "true" if ok else "false"]
|
||||
return "%s %s because %s %s" % [verb, to, vals2, _needs(expr, f.get("values"), L)]
|
||||
|
||||
|
||||
static func _why_case(f: Dictionary, L: Dictionary, plain: bool) -> String:
|
||||
var n := int(f.get("index", 0)) + 1
|
||||
var expr := str(f.get("expr", ""))
|
||||
var ok := bool(f.get("result", false))
|
||||
if expr == "":
|
||||
return "Otherwise (case %d): no case before it matched" % n if plain else "case %d: otherwise" % n
|
||||
if not plain:
|
||||
var t := "case %d: %s → %s" % [n, expr, "error: " + str(f["error"]) if f.has("error") else ("true" if ok else "false")]
|
||||
var vals := _values(f.get("values"), L, false)
|
||||
return t + (" (%s)" % vals if vals != "" else "")
|
||||
if f.has("error"):
|
||||
return "Case %d couldn't be worked out (%s)" % [n, f["error"]]
|
||||
var vals2 := _values(f.get("values"), L, true)
|
||||
var verb := "matched" if ok else "didn't match"
|
||||
if vals2 == "":
|
||||
return "Case %d %s: %s was %s" % [n, verb, _condition(expr, L), "true" if ok else "false"]
|
||||
return "Case %d %s because %s %s" % [n, verb, vals2, _needs(expr, f.get("values"), L)]
|
||||
|
||||
|
||||
static func _why_effect(f: Dictionary, L: Dictionary, plain: bool) -> String:
|
||||
var v := str(f.get("var", ""))
|
||||
var op := str(f.get("op", ""))
|
||||
if not plain:
|
||||
if f.has("count"):
|
||||
return "reset %s (%s)" % [v, Expr.format_value(f["count"])]
|
||||
return "%s %s: %s → %s" % [v, op, _raw(f.get("before")), _raw(f.get("after"))]
|
||||
var lab := _label(v, L)
|
||||
if f.has("count"):
|
||||
return "Reset all %s (%s)" % [lab, Expr.format_value(f["count"])]
|
||||
var before: Variant = f.get("before")
|
||||
var after: Variant = f.get("after")
|
||||
if op == "reset" and after == null:
|
||||
return "%s was cleared" % lab
|
||||
if before == null:
|
||||
return "%s became %s" % [lab, _shown(after)]
|
||||
return "%s went from %s to %s" % [lab, _shown(before), _shown(after)]
|
||||
|
||||
|
||||
static func _raw(v: Variant) -> String:
|
||||
return "unset" if v == null else Expr.format_value(v)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- helpers
|
||||
|
|
@ -734,3 +369,27 @@ static func _short(s: String, original: String) -> String:
|
|||
if original.length() <= MAX_LEN:
|
||||
return original
|
||||
return s.substr(0, MAX_LEN - 1) + "…"
|
||||
|
||||
|
||||
static func check(table: RollTable, board: TowerBoard) -> String:
|
||||
return DescribeCards.check(table, board)
|
||||
|
||||
|
||||
static func options(table: RollTable, board: TowerBoard) -> String:
|
||||
return DescribeCards.options(table, board)
|
||||
|
||||
|
||||
static func pipe(entry: TableEntry, target_id: String, board: TowerBoard) -> String:
|
||||
return DescribeCards.pipe(entry, target_id, board)
|
||||
|
||||
|
||||
static func roll(table: RollTable, board: TowerBoard) -> String:
|
||||
return DescribeCards.roll(table, board)
|
||||
|
||||
|
||||
static func signed_number(n: int) -> String:
|
||||
return DescribeWhy.signed_number(n)
|
||||
|
||||
|
||||
static func why(fact: Dictionary, board: TowerBoard, plain: bool = true) -> String:
|
||||
return DescribeWhy.why(fact, board, plain)
|
||||
|
|
|
|||
106
core/describe_cards.gd
Normal file
106
core/describe_cards.gd
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
class_name DescribeCards
|
||||
extends RefCounted
|
||||
## Plain-language sentences for cards, options and pipes (see Describe).
|
||||
|
||||
|
||||
## A pick card's dynamic options source: "your Skills, level 1 or more",
|
||||
## "your Contacts", "your Skill values, where Chosen option is not Pilot".
|
||||
## "" for a card without options_from; the pattern as written when it's bad.
|
||||
static func options(table: RollTable, board: TowerBoard) -> String:
|
||||
if table == null or table.options_from.strip_edges() == "":
|
||||
return ""
|
||||
var L := Describe._labels(board)
|
||||
var p := RollTable.parse_options_from(table.options_from)
|
||||
var s := ""
|
||||
match str(p["kind"]):
|
||||
"prefix":
|
||||
s = "your " + Describe._label("@%s*" % p["name"], L)
|
||||
"list":
|
||||
s = "your " + Describe._label("@" + str(p["name"]), L)
|
||||
_:
|
||||
return table.options_from.strip_edges()
|
||||
var w := _where(table.options_where, L)
|
||||
if w != "":
|
||||
s += ", " + w
|
||||
return Describe._short(s, table.options_description())
|
||||
|
||||
|
||||
## The options_where filter as a short tail: "level 1 or more" for one
|
||||
## comparison on option_value, else "where <condition>"; "" when empty.
|
||||
static func _where(where: String, L: Dictionary) -> String:
|
||||
var src := where.strip_edges()
|
||||
if src == "":
|
||||
return ""
|
||||
var m := Builder.parse_condition(src)
|
||||
if m["ok"] and (m["clauses"] as Array).size() == 1:
|
||||
var c: Dictionary = m["clauses"][0]
|
||||
if str(c["var"]) == "option_value" and ["eq", "ge", "le", "gt", "lt"].has(str(c["cmp"])):
|
||||
var tail := Describe._tail(str(c["cmp"]), str(c["value"]), L).trim_prefix("is ")
|
||||
return "level " + tail
|
||||
return "where " + Describe._condition(src, L)
|
||||
|
||||
|
||||
## A pipe's label in plain words, parts joined with " · ": its inputs ("Tier
|
||||
## 3"), "only if <condition>" or "otherwise", the count ("×2", "×Terms") and
|
||||
## "saves <name>". "" for a plain pipe.
|
||||
static func pipe(entry: TableEntry, target_id: String, board: TowerBoard) -> String:
|
||||
if entry == null:
|
||||
return ""
|
||||
var L := Describe._labels(board)
|
||||
var parts := PackedStringArray()
|
||||
var w := entry.with_for(target_id)
|
||||
for nm: String in w:
|
||||
parts.append("%s %s" % [Describe._label(nm, L), Describe._expr(str(w[nm]), L)])
|
||||
var cond := entry.when_for(target_id)
|
||||
if cond != "":
|
||||
parts.append("only if " + Describe._condition(cond, L))
|
||||
elif entry.is_otherwise(target_id):
|
||||
parts.append("otherwise")
|
||||
var ce := entry.count_expr(target_id)
|
||||
if ce != "":
|
||||
parts.append("×" + Describe._expr(ce, L))
|
||||
elif entry.count_for(target_id) != 1:
|
||||
parts.append("×%d" % entry.count_for(target_id))
|
||||
var sv := entry.save_for(target_id)
|
||||
if sv != "":
|
||||
parts.append("saves " + Describe._label(sv, L))
|
||||
return " · ".join(parts)
|
||||
|
||||
|
||||
## 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:
|
||||
if table == null or table.kind != RollTable.KIND_CHECK:
|
||||
return ""
|
||||
var L := Describe._labels(board)
|
||||
var roll := _with_mod(table.check_dice, table.check_mod, L)
|
||||
var mod := table.check_mod.strip_edges()
|
||||
var target := Describe._expr(table.check_target, L)
|
||||
var num := Expr.is_number(table.check_target.strip_edges())
|
||||
var need := ""
|
||||
if table.check_cmp == "le":
|
||||
need = ("%s or less" % target) if num else "at most " + target
|
||||
else:
|
||||
need = ("%s or more" % target) if num else "at least " + target
|
||||
return Describe._short("Roll %s, need %s" % [roll, need], "Roll %s %s vs %s" % [table.check_dice, mod, table.check_target])
|
||||
|
||||
|
||||
## A ranged roll table's roll: "Roll d20 + Luck", "Roll 2D − Fatigue",
|
||||
## "Roll d100". "" for other cards.
|
||||
static func roll(table: RollTable, board: TowerBoard) -> String:
|
||||
if table == null or table.kind != RollTable.KIND_ROLL or not table.is_ranged():
|
||||
return ""
|
||||
return "Roll " + _with_mod(table.dice, table.dice_mod, Describe._labels(board))
|
||||
|
||||
|
||||
## Dice plus a modifier in words: "2D + Strength modifier", "d20 − Fatigue".
|
||||
static func _with_mod(dice_src: String, mod_src: String, L: Dictionary) -> String:
|
||||
var out := Describe._expr(dice_src, L)
|
||||
var mod := mod_src.strip_edges()
|
||||
if mod != "":
|
||||
var mt := Builder.tokens(mod)
|
||||
if not mt.is_empty() and mt[0]["s"] == "-":
|
||||
out += " %s %s" % [Describe.MINUS, Describe._expr(mod.substr(1), L)]
|
||||
else:
|
||||
out += " + " + Describe._expr(mod, L)
|
||||
return out
|
||||
1
core/describe_cards.gd.uid
Normal file
1
core/describe_cards.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://b55xjcxnywwu3
|
||||
265
core/describe_why.gd
Normal file
265
core/describe_why.gd
Normal file
|
|
@ -0,0 +1,265 @@
|
|||
class_name DescribeWhy
|
||||
extends RefCounted
|
||||
## The "Why this?" sentences for trace facts (see Describe).
|
||||
|
||||
|
||||
## One trace fact (Roller node/step "why") as a sentence. Plain mode uses
|
||||
## labels and words ("Skipped Tier 3 because Luck was 1 (needs 2 or more)");
|
||||
## text mode (plain = false) shows the rules as written ("Skipped tier3: when
|
||||
## @luck >= 2 was false (@luck = 1)"). Unknown facts give a short dump.
|
||||
static func why(fact: Dictionary, board: TowerBoard, plain: bool = true) -> String:
|
||||
if fact == null:
|
||||
return ""
|
||||
var L := Describe._labels(board)
|
||||
var s := ""
|
||||
match str(fact.get("type", "")):
|
||||
"roll":
|
||||
s = _why_roll(fact, L, plain)
|
||||
"check":
|
||||
s = _why_check(fact, L, plain)
|
||||
"when":
|
||||
s = _why_when(fact, board, L, plain)
|
||||
"otherwise":
|
||||
var to := _table(str(fact.get("to", "")), board, plain)
|
||||
if bool(fact.get("result", false)):
|
||||
s = "Took %s because no condition was true" % to if plain else "%s: otherwise, ran (no condition was true)" % to
|
||||
else:
|
||||
s = "Skipped %s because a condition was true" % to if plain else "%s: otherwise, skipped" % to
|
||||
"case":
|
||||
s = _why_case(fact, L, plain)
|
||||
"show_if":
|
||||
var h := int(fact.get("hidden", 0))
|
||||
var parts := PackedStringArray()
|
||||
if h > 0:
|
||||
parts.append(("%d option hidden by its condition" if h == 1 else "%d options hidden by their conditions") % h)
|
||||
if bool(fact.get("chosen_hidden", false)):
|
||||
parts.append("the options from values were hidden")
|
||||
s = ", and ".join(parts)
|
||||
if s != "":
|
||||
s = s.substr(0, 1).to_upper() + s.substr(1)
|
||||
if not plain:
|
||||
s = "show_if hid %d option(s)%s" % [h, ", and the Chosen result" if bool(fact.get("chosen_hidden", false)) else ""]
|
||||
"options_where":
|
||||
var kept := int(fact.get("kept", 0))
|
||||
var total := int(fact.get("total", 0))
|
||||
if plain:
|
||||
var from := str(fact.get("from", ""))
|
||||
var p := RollTable.parse_options_from(from)
|
||||
var what := Describe._label("@%s*" % p["name"], L) if str(p["kind"]) == "prefix" else (Describe._label("@" + str(p["name"]), L) if str(p["kind"]) == "list" else "options")
|
||||
s = "Offered %d of %d %s (%s)" % [kept, total, what, DescribeCards._where(str(fact.get("expr", "")), L)]
|
||||
else:
|
||||
s = "options_where %s kept %d of %d" % [fact.get("expr", ""), kept, total]
|
||||
"effect":
|
||||
s = _why_effect(fact, L, plain)
|
||||
"input":
|
||||
var nm := str(fact.get("name", ""))
|
||||
var val := Expr.format_value(fact.get("value"))
|
||||
var from_pipe := str(fact.get("from", "")) == "pipe"
|
||||
if plain:
|
||||
s = "%s was %s (%s)" % [Describe._label(nm, L), val, "from the thread" if from_pipe else "default"]
|
||||
else:
|
||||
s = "input %s = %s (%s)" % [nm, val, "with" if from_pipe else "default"]
|
||||
_:
|
||||
s = JSON.stringify(fact)
|
||||
if s.length() > Describe.MAX_LEN * 2:
|
||||
s = s.substr(0, Describe.MAX_LEN * 2 - 1) + "…"
|
||||
return s
|
||||
|
||||
|
||||
static func _table(id: String, board: TowerBoard, plain: bool) -> String:
|
||||
if not plain or board == null:
|
||||
return id
|
||||
var t := board.get_table(id)
|
||||
if t == null:
|
||||
return id
|
||||
var n := Formatter.strip_tags(t.name).strip_edges()
|
||||
return n if n != "" else id
|
||||
|
||||
|
||||
## "3 + 4 = 7" (or "5" for one die).
|
||||
static func _faces(faces: Variant) -> String:
|
||||
if not (faces is Array) or (faces as Array).is_empty():
|
||||
return ""
|
||||
var parts := PackedStringArray()
|
||||
var sum := 0.0
|
||||
for f: Variant in faces:
|
||||
parts.append(Expr.format_value(f))
|
||||
sum += float(Expr.to_value(f)) if Expr.is_number(f) else 0.0
|
||||
if parts.size() == 1:
|
||||
return parts[0]
|
||||
return "%s = %s" % [" + ".join(parts), Expr.format_value(sum)]
|
||||
|
||||
|
||||
static func _nonzero(v: Variant) -> bool:
|
||||
var n: Variant = Expr.to_value(v)
|
||||
return Expr.is_number(n) and n != 0
|
||||
|
||||
|
||||
## "+2", "−1", "+0".
|
||||
static func signed_number(n: int) -> String:
|
||||
return _signed(n)
|
||||
|
||||
|
||||
static func _signed(v: Variant) -> String:
|
||||
var n: Variant = Expr.to_value(v)
|
||||
if not Expr.is_number(n):
|
||||
return str(v)
|
||||
return ("+" + Expr.format_value(n)) if n >= 0 else (Describe.MINUS + Expr.format_value(-n))
|
||||
|
||||
|
||||
## A roll fact as a sentence: "Rolled 17, +3 for Luck = 20". A total past
|
||||
## the table's ends adds "past the top of the table, so it counts as 24"
|
||||
## (fact key counts_as).
|
||||
static func _why_roll(f: Dictionary, L: Dictionary, plain: bool) -> String:
|
||||
var total := Expr.format_value(f.get("total"))
|
||||
match str(f.get("pick", "dice")):
|
||||
"weighted":
|
||||
return "Rolled %s on %s" % [total, f.get("dice", "")] if plain else "roll %s: %s" % [f.get("dice", ""), total]
|
||||
"card":
|
||||
return "Drew card %s" % total if plain else "draw: card %s" % total
|
||||
var faces := _faces(f.get("faces"))
|
||||
var past := f.has("counts_as")
|
||||
var ends := Expr.format_value(f.get("counts_as"))
|
||||
if not plain:
|
||||
var t := "roll %s: %s" % [f.get("dice", ""), faces if faces != "" else total]
|
||||
if f.has("mod") and _nonzero(f["mod"]):
|
||||
t += " %s = %s" % [_signed(f["mod"]).replace(Describe.MINUS, "-"), Expr.format_value(f.get("raw", f.get("total")))]
|
||||
if f.has("limited"):
|
||||
t += " (%s %s: %s)" % ["min" if f["limited"] == "floor" else "max", f.get("limit_expr", ""), total]
|
||||
if past:
|
||||
t += " (past the end: %s)" % ends
|
||||
return t
|
||||
var s := "Worked out %s" % total
|
||||
if faces != "":
|
||||
s = "Rolled " + faces
|
||||
if f.has("mod") and _nonzero(f["mod"]):
|
||||
var why_mod := ""
|
||||
if str(f.get("mod_expr", "")) != "":
|
||||
why_mod = " for " + Describe._expr(str(f["mod_expr"]).trim_prefix("-"), L)
|
||||
s += ", %s%s = %s" % [_signed(f["mod"]), why_mod, Expr.format_value(f.get("raw", f.get("total")))]
|
||||
if f.has("limited"):
|
||||
var up: bool = f["limited"] == "floor"
|
||||
s += ", %s to %s (never %s %s)" % ["raised" if up else "lowered", total, "below" if up else "above", Describe._expr(str(f.get("limit_expr", "")), L)]
|
||||
if past:
|
||||
var top: bool = float(Expr.to_value(f.get("counts_as"))) < float(Expr.to_value(f.get("total")))
|
||||
s += ", past the %s of the table, so it counts as %s" % ["top" if top else "bottom", ends]
|
||||
return s
|
||||
|
||||
|
||||
static func _why_check(f: Dictionary, L: Dictionary, plain: bool) -> String:
|
||||
var faces := _faces(f.get("faces"))
|
||||
var nat := Expr.format_value(f.get("nat"))
|
||||
var total := Expr.format_value(f.get("total"))
|
||||
var target := Expr.format_value(f.get("target"))
|
||||
var le := str(f.get("cmp", "ge")) == "le"
|
||||
var ok := bool(f.get("success", false))
|
||||
if not plain:
|
||||
return "check %s%s vs %s (%s): %s %s = %s → %s" % [f.get("dice", ""),
|
||||
(" + " + str(f.get("mod_expr", ""))) if str(f.get("mod_expr", "")) != "" else "", f.get("target_expr", target),
|
||||
f.get("cmp", "ge"), nat, _signed(f.get("mod", 0)).replace(Describe.MINUS, "-"), total, "success" if ok else "failure"]
|
||||
var s := "Rolled " + (faces if faces != "" else nat)
|
||||
if _nonzero(f.get("mod", 0)):
|
||||
s += ", %s = %s" % [_signed(f.get("mod", 0)), total]
|
||||
s += ": needed %s or %s, %s" % [target, "less" if le else "more", "success" if ok else "failure"]
|
||||
return s
|
||||
|
||||
|
||||
## "Luck was 1 and Social Standing was 9" from a fact's values.
|
||||
static func _values(values: Variant, L: Dictionary, plain: bool) -> String:
|
||||
if not (values is Dictionary) or (values as Dictionary).is_empty():
|
||||
return ""
|
||||
var parts := PackedStringArray()
|
||||
for key: Variant in values:
|
||||
var nm := str(key)
|
||||
var v: Variant = values[key]
|
||||
if plain:
|
||||
parts.append(("%s wasn't set" % Describe._label(nm, L)) if v == null else "%s was %s" % [Describe._label(nm, L), _shown(v)])
|
||||
else:
|
||||
parts.append("%s = %s" % [nm, "unset" if v == null else Expr.format_value(v)])
|
||||
if not plain:
|
||||
return ", ".join(parts)
|
||||
if parts.size() == 1:
|
||||
return parts[0]
|
||||
return ", ".join(parts.slice(0, parts.size() - 1)) + " and " + parts[parts.size() - 1]
|
||||
|
||||
|
||||
static func _shown(v: Variant) -> String:
|
||||
var s := Expr.format_value(v)
|
||||
return s if s != "" else "empty"
|
||||
|
||||
|
||||
## "(needs 2 or more)" for one comparison on a value that was read, else
|
||||
## "(rule: <condition>)".
|
||||
static func _needs(expr: String, values: Variant, L: Dictionary) -> String:
|
||||
var m := Builder.parse_condition(expr)
|
||||
if m["ok"] and (m["clauses"] as Array).size() == 1:
|
||||
var c: Dictionary = m["clauses"][0]
|
||||
if values is Dictionary and (values as Dictionary).has(str(c["var"])):
|
||||
var tail := Describe._tail(str(c["cmp"]), str(c["value"]), L)
|
||||
if tail.begins_with("is "):
|
||||
tail = tail.substr(3)
|
||||
elif tail.begins_with("includes "):
|
||||
tail = "to include " + tail.substr(9)
|
||||
return "(needs %s)" % tail
|
||||
return "(rule: %s)" % Describe._condition(expr, L)
|
||||
|
||||
|
||||
static func _why_when(f: Dictionary, board: TowerBoard, L: Dictionary, plain: bool) -> String:
|
||||
var to := _table(str(f.get("to", "")), board, plain)
|
||||
var expr := str(f.get("expr", ""))
|
||||
var ok := bool(f.get("result", false))
|
||||
if not plain:
|
||||
var t := "%s %s: when %s was %s" % ["Took" if ok else "Skipped", to, expr, "true" if ok else "false"]
|
||||
if f.has("error"):
|
||||
t = "Skipped %s: when %s failed: %s" % [to, expr, f["error"]]
|
||||
var vals := _values(f.get("values"), L, false)
|
||||
return t + (" (%s)" % vals if vals != "" else "")
|
||||
if f.has("error"):
|
||||
return "Skipped %s: its condition couldn't be worked out (%s)" % [to, f["error"]]
|
||||
var vals2 := _values(f.get("values"), L, true)
|
||||
var verb := "Took" if ok else "Skipped"
|
||||
if vals2 == "":
|
||||
return "%s %s: %s was %s" % [verb, to, Describe._condition(expr, L), "true" if ok else "false"]
|
||||
return "%s %s because %s %s" % [verb, to, vals2, _needs(expr, f.get("values"), L)]
|
||||
|
||||
|
||||
static func _why_case(f: Dictionary, L: Dictionary, plain: bool) -> String:
|
||||
var n := int(f.get("index", 0)) + 1
|
||||
var expr := str(f.get("expr", ""))
|
||||
var ok := bool(f.get("result", false))
|
||||
if expr == "":
|
||||
return "Otherwise (case %d): no case before it matched" % n if plain else "case %d: otherwise" % n
|
||||
if not plain:
|
||||
var t := "case %d: %s → %s" % [n, expr, "error: " + str(f["error"]) if f.has("error") else ("true" if ok else "false")]
|
||||
var vals := _values(f.get("values"), L, false)
|
||||
return t + (" (%s)" % vals if vals != "" else "")
|
||||
if f.has("error"):
|
||||
return "Case %d couldn't be worked out (%s)" % [n, f["error"]]
|
||||
var vals2 := _values(f.get("values"), L, true)
|
||||
var verb := "matched" if ok else "didn't match"
|
||||
if vals2 == "":
|
||||
return "Case %d %s: %s was %s" % [n, verb, Describe._condition(expr, L), "true" if ok else "false"]
|
||||
return "Case %d %s because %s %s" % [n, verb, vals2, _needs(expr, f.get("values"), L)]
|
||||
|
||||
|
||||
static func _why_effect(f: Dictionary, L: Dictionary, plain: bool) -> String:
|
||||
var v := str(f.get("var", ""))
|
||||
var op := str(f.get("op", ""))
|
||||
if not plain:
|
||||
if f.has("count"):
|
||||
return "reset %s (%s)" % [v, Expr.format_value(f["count"])]
|
||||
return "%s %s: %s → %s" % [v, op, _raw(f.get("before")), _raw(f.get("after"))]
|
||||
var lab := Describe._label(v, L)
|
||||
if f.has("count"):
|
||||
return "Reset all %s (%s)" % [lab, Expr.format_value(f["count"])]
|
||||
var before: Variant = f.get("before")
|
||||
var after: Variant = f.get("after")
|
||||
if op == "reset" and after == null:
|
||||
return "%s was cleared" % lab
|
||||
if before == null:
|
||||
return "%s became %s" % [lab, _shown(after)]
|
||||
return "%s went from %s to %s" % [lab, _shown(before), _shown(after)]
|
||||
|
||||
|
||||
static func _raw(v: Variant) -> String:
|
||||
return "unset" if v == null else Expr.format_value(v)
|
||||
1
core/describe_why.gd.uid
Normal file
1
core/describe_why.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://ctf61koova5sn
|
||||
204
io/json_canon.gd
Normal file
204
io/json_canon.gd
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
class_name JsonCanon
|
||||
extends RefCounted
|
||||
## Collection normaliser behind JsonIO.canonical() (format version 2).
|
||||
|
||||
|
||||
## Normalizes a collection to format version 2: legacy keys are converted
|
||||
## (`die` -> `dice`, `triggers` -> `pipes`, `collection` -> `name`), missing
|
||||
## optional keys are tolerated and unknown keys are dropped.
|
||||
static func canonical(src: Dictionary) -> Dictionary:
|
||||
var tables: Array = []
|
||||
var src_tables: Variant = src.get("tables", [])
|
||||
if src_tables is Array:
|
||||
for t in src_tables:
|
||||
if t is Dictionary:
|
||||
tables.append(_canon_table(t))
|
||||
var cname := str(src.get("name", src.get("collection", "")))
|
||||
var out := {"format_version": JsonIO.FORMAT_VERSION, "id": str(src.get("id", "")), "name": cname, "tables": tables}
|
||||
var groups: Array = []
|
||||
var src_groups: Variant = src.get("groups", [])
|
||||
if src_groups is Array:
|
||||
for g in src_groups:
|
||||
if g is Dictionary:
|
||||
groups.append(_canon_group(g))
|
||||
if not groups.is_empty():
|
||||
out["groups"] = groups
|
||||
# The Book and pictures (2026-11-10): taken as they are; TowerBoard checks them.
|
||||
if src.get("book") is Array:
|
||||
out["book"] = (src["book"] as Array).filter(func(v: Variant) -> bool: return v is Dictionary)
|
||||
if src.get("images") is Dictionary:
|
||||
var pics := {}
|
||||
for k: Variant in src["images"]:
|
||||
if src["images"][k] is String:
|
||||
pics[str(k)] = src["images"][k]
|
||||
out["images"] = pics
|
||||
return out
|
||||
|
||||
|
||||
## Copies the keys that are present and not empty (newer optional keys that
|
||||
## need no conversion).
|
||||
static func _keep(src: Dictionary, dst: Dictionary, keys: Array) -> void:
|
||||
for k: String in keys:
|
||||
var v: Variant = src.get(k)
|
||||
if v != null and not (v is String and (v as String).strip_edges() == "") and not (v is bool and not v):
|
||||
dst[k] = v
|
||||
|
||||
|
||||
static func _canon_group(gd: Dictionary) -> Dictionary:
|
||||
var g := {
|
||||
"id": str(gd.get("id", "")),
|
||||
"name": str(gd.get("name", "")),
|
||||
"x": int(JsonIO._num(gd.get("x", 0), 0)),
|
||||
"y": int(JsonIO._num(gd.get("y", 0), 0)),
|
||||
"w": int(JsonIO._num(gd.get("w", 320), 320)),
|
||||
"h": int(JsonIO._num(gd.get("h", 200), 200)),
|
||||
}
|
||||
if bool(gd.get("collapsed", false)):
|
||||
g["collapsed"] = true
|
||||
var details := str(gd.get("details", ""))
|
||||
if details != "":
|
||||
g["details"] = details
|
||||
var members: Array = []
|
||||
var src: Variant = gd.get("members", [])
|
||||
if src is Array:
|
||||
for m in src:
|
||||
if str(m) != "" and not members.has(str(m)):
|
||||
members.append(str(m))
|
||||
g["members"] = members
|
||||
_keep(gd, g, ["parent"])
|
||||
return g
|
||||
|
||||
|
||||
static func _canon_table(td: Dictionary) -> Dictionary:
|
||||
var t := {
|
||||
"id": str(td.get("id", "")),
|
||||
"name": str(td.get("name", "")),
|
||||
"x": int(JsonIO._num(td.get("x", 0), 0)),
|
||||
"y": int(JsonIO._num(td.get("y", 0), 0)),
|
||||
}
|
||||
if bool(td.get("collapsed", false)):
|
||||
t["collapsed"] = true
|
||||
var details := str(td.get("details", ""))
|
||||
if details != "":
|
||||
t["details"] = details
|
||||
var tags: Array = []
|
||||
var src_tags: Variant = td.get("tags", [])
|
||||
if src_tags is Array:
|
||||
for tag in src_tags:
|
||||
tags.append(str(tag))
|
||||
if not tags.is_empty():
|
||||
t["tags"] = tags
|
||||
var dice := str(td.get("dice", "")).strip_edges()
|
||||
if dice == "" and td.has("die"):
|
||||
var die: Variant = JsonIO._num(td["die"], 0)
|
||||
if (die is int or die is float) and die > 0:
|
||||
dice = "1d%d" % int(die)
|
||||
if dice != "":
|
||||
t["dice"] = dice
|
||||
for key in ["card_mode", "deck_empty"]:
|
||||
var v: Variant = td.get(key)
|
||||
if v != null and not (v is bool and not v) and not (v is String and v == ""):
|
||||
t[key] = v
|
||||
# Logic cards (docs/LOGIC.md §9). Defaults are left out.
|
||||
var kind := str(td.get("kind", "roll"))
|
||||
if RollTable.KINDS.has(kind) and kind != "roll":
|
||||
t["kind"] = kind
|
||||
var defaults := {"dice_mod": "", "choice": "pick", "prompt": "", "save_as": "", "options_from": "", "options_where": "", "min": "0", "max": "99",
|
||||
"loop": "times", "loop_expr": "", "var_name": "", "var_type": "number", "initial": "",
|
||||
"check_dice": RollTable.CHECK_DEFAULT_DICE, "check_mod": "", "check_cmp": "ge", "check_target": RollTable.CHECK_DEFAULT_TARGET}
|
||||
for key: String in defaults:
|
||||
if not td.has(key) or td[key] == null:
|
||||
continue
|
||||
var s := RollTable.expr_text(td[key], str(defaults[key]))
|
||||
if s != str(defaults[key]):
|
||||
t[key] = s
|
||||
var inputs := RollTable.clean_inputs(td.get("inputs", []))
|
||||
if not inputs.is_empty():
|
||||
var list: Array = []
|
||||
for inp: Dictionary in inputs:
|
||||
var o := {"name": inp["name"]}
|
||||
if str(inp["label"]) != "":
|
||||
o["label"] = inp["label"]
|
||||
if str(inp["default"]) != "":
|
||||
o["default"] = inp["default"]
|
||||
list.append(o)
|
||||
t["inputs"] = list
|
||||
var entries: Array = []
|
||||
var src_entries: Variant = td.get("entries", [])
|
||||
if src_entries is Array:
|
||||
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"])
|
||||
return t
|
||||
|
||||
|
||||
static func _canon_entry(ev: Variant) -> Dictionary:
|
||||
if ev is String:
|
||||
return {"id": "", "text": ev}
|
||||
var ed: Dictionary = ev
|
||||
var e := {"id": str(ed.get("id", "")), "text": str(ed.get("text", ""))}
|
||||
var details := str(ed.get("details", ""))
|
||||
if details != "":
|
||||
e["details"] = details
|
||||
var w: Variant = JsonIO._num(ed.get("weight", 1), 1)
|
||||
if (w is int or w is float) and w != 1:
|
||||
e["weight"] = w
|
||||
var r: Variant = ed.get("range")
|
||||
if r is Array and (r as Array).size() == 2:
|
||||
e["range"] = [int(JsonIO._num(r[0], 0)), int(JsonIO._num(r[1], 0))]
|
||||
var effects := str(ed.get("effects", "")) if ed.get("effects") != null else ""
|
||||
if effects.strip_edges() != "":
|
||||
e["effects"] = effects
|
||||
var when := str(ed.get("when", "")).strip_edges() if ed.get("when") != null else ""
|
||||
if when != "":
|
||||
e["when"] = when
|
||||
var show_if := str(ed.get("show_if", "")).strip_edges() if ed.get("show_if") != null else ""
|
||||
if show_if != "":
|
||||
e["show_if"] = show_if
|
||||
var src_pipes: Variant = ed.get("pipes", ed.get("triggers", []))
|
||||
var pipes: Array = []
|
||||
if src_pipes is Array:
|
||||
for p in src_pipes:
|
||||
if p is String and p != "":
|
||||
pipes.append(p)
|
||||
elif p is Dictionary and str(p.get("table", "")) != "":
|
||||
var np := {"table": str(p["table"])}
|
||||
if p.has("count"):
|
||||
var cnt: Variant = JsonIO._num(p["count"], null)
|
||||
if cnt == null and p["count"] is String and (p["count"] as String).strip_edges() != "":
|
||||
np["count"] = (p["count"] as String).strip_edges() # an expression
|
||||
else:
|
||||
np["count"] = int(cnt if cnt != null else 1)
|
||||
if str(p.get("save_as", "")) != "":
|
||||
np["save_as"] = str(p["save_as"])
|
||||
var pw := str(p.get("when", "")).strip_edges() if p.get("when") != null else ""
|
||||
if pw != "":
|
||||
np["when"] = pw
|
||||
elif p.get("otherwise", false) is bool and bool(p.get("otherwise", false)):
|
||||
np["otherwise"] = true
|
||||
var wv := _canon_with(p.get("with"))
|
||||
if not wv.is_empty():
|
||||
np["with"] = wv
|
||||
_keep(p, np, ["color", "combine", "pause"])
|
||||
pipes.append(np)
|
||||
if not pipes.is_empty():
|
||||
e["pipes"] = pipes
|
||||
_keep(ed, e, ["page", "image"])
|
||||
if ed.get("cost") is Dictionary:
|
||||
e["cost"] = ed["cost"]
|
||||
return e
|
||||
|
||||
|
||||
## A pipe's "with" object: {input name: expression text}, names trimmed (a
|
||||
## leading "@" dropped), numbers as text, empty names and values left out.
|
||||
static func _canon_with(v: Variant) -> Dictionary:
|
||||
var out := {}
|
||||
if not (v is Dictionary):
|
||||
return out
|
||||
for k: Variant in v:
|
||||
var nm := str(k).strip_edges().trim_prefix("@")
|
||||
var ex := RollTable.expr_text(v[k], "").strip_edges()
|
||||
if nm != "" and ex != "":
|
||||
out[nm] = ex
|
||||
return out
|
||||
1
io/json_canon.gd.uid
Normal file
1
io/json_canon.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bw2ha6nahxfyo
|
||||
305
io/json_io.gd
305
io/json_io.gd
|
|
@ -242,207 +242,6 @@ static func _import_groups(c: Dictionary, id_map: Dictionary, by_name: Dictionar
|
|||
g["members"] = keep
|
||||
|
||||
|
||||
# ------------------------------------------------------------ canonical
|
||||
|
||||
## Normalizes a collection to format version 2: legacy keys are converted
|
||||
## (`die` -> `dice`, `triggers` -> `pipes`, `collection` -> `name`), missing
|
||||
## optional keys are tolerated and unknown keys are dropped.
|
||||
static func canonical(src: Dictionary) -> Dictionary:
|
||||
var tables: Array = []
|
||||
var src_tables: Variant = src.get("tables", [])
|
||||
if src_tables is Array:
|
||||
for t in src_tables:
|
||||
if t is Dictionary:
|
||||
tables.append(_canon_table(t))
|
||||
var cname := str(src.get("name", src.get("collection", "")))
|
||||
var out := {"format_version": FORMAT_VERSION, "id": str(src.get("id", "")), "name": cname, "tables": tables}
|
||||
var groups: Array = []
|
||||
var src_groups: Variant = src.get("groups", [])
|
||||
if src_groups is Array:
|
||||
for g in src_groups:
|
||||
if g is Dictionary:
|
||||
groups.append(_canon_group(g))
|
||||
if not groups.is_empty():
|
||||
out["groups"] = groups
|
||||
# The Book and pictures (2026-11-10): taken as they are; TowerBoard checks them.
|
||||
if src.get("book") is Array:
|
||||
out["book"] = (src["book"] as Array).filter(func(v: Variant) -> bool: return v is Dictionary)
|
||||
if src.get("images") is Dictionary:
|
||||
var pics := {}
|
||||
for k: Variant in src["images"]:
|
||||
if src["images"][k] is String:
|
||||
pics[str(k)] = src["images"][k]
|
||||
out["images"] = pics
|
||||
return out
|
||||
|
||||
|
||||
## Copies the keys that are present and not empty (newer optional keys that
|
||||
## need no conversion).
|
||||
static func _keep(src: Dictionary, dst: Dictionary, keys: Array) -> void:
|
||||
for k: String in keys:
|
||||
var v: Variant = src.get(k)
|
||||
if v != null and not (v is String and (v as String).strip_edges() == "") and not (v is bool and not v):
|
||||
dst[k] = v
|
||||
|
||||
|
||||
static func _canon_group(gd: Dictionary) -> Dictionary:
|
||||
var g := {
|
||||
"id": str(gd.get("id", "")),
|
||||
"name": str(gd.get("name", "")),
|
||||
"x": int(_num(gd.get("x", 0), 0)),
|
||||
"y": int(_num(gd.get("y", 0), 0)),
|
||||
"w": int(_num(gd.get("w", 320), 320)),
|
||||
"h": int(_num(gd.get("h", 200), 200)),
|
||||
}
|
||||
if bool(gd.get("collapsed", false)):
|
||||
g["collapsed"] = true
|
||||
var details := str(gd.get("details", ""))
|
||||
if details != "":
|
||||
g["details"] = details
|
||||
var members: Array = []
|
||||
var src: Variant = gd.get("members", [])
|
||||
if src is Array:
|
||||
for m in src:
|
||||
if str(m) != "" and not members.has(str(m)):
|
||||
members.append(str(m))
|
||||
g["members"] = members
|
||||
_keep(gd, g, ["parent"])
|
||||
return g
|
||||
|
||||
|
||||
static func _canon_table(td: Dictionary) -> Dictionary:
|
||||
var t := {
|
||||
"id": str(td.get("id", "")),
|
||||
"name": str(td.get("name", "")),
|
||||
"x": int(_num(td.get("x", 0), 0)),
|
||||
"y": int(_num(td.get("y", 0), 0)),
|
||||
}
|
||||
if bool(td.get("collapsed", false)):
|
||||
t["collapsed"] = true
|
||||
var details := str(td.get("details", ""))
|
||||
if details != "":
|
||||
t["details"] = details
|
||||
var tags: Array = []
|
||||
var src_tags: Variant = td.get("tags", [])
|
||||
if src_tags is Array:
|
||||
for tag in src_tags:
|
||||
tags.append(str(tag))
|
||||
if not tags.is_empty():
|
||||
t["tags"] = tags
|
||||
var dice := str(td.get("dice", "")).strip_edges()
|
||||
if dice == "" and td.has("die"):
|
||||
var die: Variant = _num(td["die"], 0)
|
||||
if (die is int or die is float) and die > 0:
|
||||
dice = "1d%d" % int(die)
|
||||
if dice != "":
|
||||
t["dice"] = dice
|
||||
for key in ["card_mode", "deck_empty"]:
|
||||
var v: Variant = td.get(key)
|
||||
if v != null and not (v is bool and not v) and not (v is String and v == ""):
|
||||
t[key] = v
|
||||
# Logic cards (docs/LOGIC.md §9). Defaults are left out.
|
||||
var kind := str(td.get("kind", "roll"))
|
||||
if RollTable.KINDS.has(kind) and kind != "roll":
|
||||
t["kind"] = kind
|
||||
var defaults := {"dice_mod": "", "choice": "pick", "prompt": "", "save_as": "", "options_from": "", "options_where": "", "min": "0", "max": "99",
|
||||
"loop": "times", "loop_expr": "", "var_name": "", "var_type": "number", "initial": "",
|
||||
"check_dice": RollTable.CHECK_DEFAULT_DICE, "check_mod": "", "check_cmp": "ge", "check_target": RollTable.CHECK_DEFAULT_TARGET}
|
||||
for key: String in defaults:
|
||||
if not td.has(key) or td[key] == null:
|
||||
continue
|
||||
var s := RollTable.expr_text(td[key], str(defaults[key]))
|
||||
if s != str(defaults[key]):
|
||||
t[key] = s
|
||||
var inputs := RollTable.clean_inputs(td.get("inputs", []))
|
||||
if not inputs.is_empty():
|
||||
var list: Array = []
|
||||
for inp: Dictionary in inputs:
|
||||
var o := {"name": inp["name"]}
|
||||
if str(inp["label"]) != "":
|
||||
o["label"] = inp["label"]
|
||||
if str(inp["default"]) != "":
|
||||
o["default"] = inp["default"]
|
||||
list.append(o)
|
||||
t["inputs"] = list
|
||||
var entries: Array = []
|
||||
var src_entries: Variant = td.get("entries", [])
|
||||
if src_entries is Array:
|
||||
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"])
|
||||
return t
|
||||
|
||||
|
||||
static func _canon_entry(ev: Variant) -> Dictionary:
|
||||
if ev is String:
|
||||
return {"id": "", "text": ev}
|
||||
var ed: Dictionary = ev
|
||||
var e := {"id": str(ed.get("id", "")), "text": str(ed.get("text", ""))}
|
||||
var details := str(ed.get("details", ""))
|
||||
if details != "":
|
||||
e["details"] = details
|
||||
var w: Variant = _num(ed.get("weight", 1), 1)
|
||||
if (w is int or w is float) and w != 1:
|
||||
e["weight"] = w
|
||||
var r: Variant = ed.get("range")
|
||||
if r is Array and (r as Array).size() == 2:
|
||||
e["range"] = [int(_num(r[0], 0)), int(_num(r[1], 0))]
|
||||
var effects := str(ed.get("effects", "")) if ed.get("effects") != null else ""
|
||||
if effects.strip_edges() != "":
|
||||
e["effects"] = effects
|
||||
var when := str(ed.get("when", "")).strip_edges() if ed.get("when") != null else ""
|
||||
if when != "":
|
||||
e["when"] = when
|
||||
var show_if := str(ed.get("show_if", "")).strip_edges() if ed.get("show_if") != null else ""
|
||||
if show_if != "":
|
||||
e["show_if"] = show_if
|
||||
var src_pipes: Variant = ed.get("pipes", ed.get("triggers", []))
|
||||
var pipes: Array = []
|
||||
if src_pipes is Array:
|
||||
for p in src_pipes:
|
||||
if p is String and p != "":
|
||||
pipes.append(p)
|
||||
elif p is Dictionary and str(p.get("table", "")) != "":
|
||||
var np := {"table": str(p["table"])}
|
||||
if p.has("count"):
|
||||
var cnt: Variant = _num(p["count"], null)
|
||||
if cnt == null and p["count"] is String and (p["count"] as String).strip_edges() != "":
|
||||
np["count"] = (p["count"] as String).strip_edges() # an expression
|
||||
else:
|
||||
np["count"] = int(cnt if cnt != null else 1)
|
||||
if str(p.get("save_as", "")) != "":
|
||||
np["save_as"] = str(p["save_as"])
|
||||
var pw := str(p.get("when", "")).strip_edges() if p.get("when") != null else ""
|
||||
if pw != "":
|
||||
np["when"] = pw
|
||||
elif p.get("otherwise", false) is bool and bool(p.get("otherwise", false)):
|
||||
np["otherwise"] = true
|
||||
var wv := _canon_with(p.get("with"))
|
||||
if not wv.is_empty():
|
||||
np["with"] = wv
|
||||
_keep(p, np, ["color", "combine", "pause"])
|
||||
pipes.append(np)
|
||||
if not pipes.is_empty():
|
||||
e["pipes"] = pipes
|
||||
_keep(ed, e, ["page", "image"])
|
||||
if ed.get("cost") is Dictionary:
|
||||
e["cost"] = ed["cost"]
|
||||
return e
|
||||
|
||||
|
||||
## A pipe's "with" object: {input name: expression text}, names trimmed (a
|
||||
## leading "@" dropped), numbers as text, empty names and values left out.
|
||||
static func _canon_with(v: Variant) -> Dictionary:
|
||||
var out := {}
|
||||
if not (v is Dictionary):
|
||||
return out
|
||||
for k: Variant in v:
|
||||
var nm := str(k).strip_edges().trim_prefix("@")
|
||||
var ex := RollTable.expr_text(v[k], "").strip_edges()
|
||||
if nm != "" and ex != "":
|
||||
out[nm] = ex
|
||||
return out
|
||||
|
||||
|
||||
# -------------------------------------------------------------- helpers
|
||||
|
|
@ -492,7 +291,7 @@ static func pipe_info(p: Variant) -> Dictionary:
|
|||
var w := str(p.get("when", "")).strip_edges() if p.get("when") != null else ""
|
||||
return {"table": str(p.get("table", "")), "count": int(_num(c, 1)), "save_as": str(p.get("save_as", "")), "count_expr": expr,
|
||||
"when": w, "otherwise": w == "" and p.get("otherwise", false) is bool and bool(p.get("otherwise", false)),
|
||||
"with": _canon_with(p.get("with"))}
|
||||
"with": JsonCanon._canon_with(p.get("with"))}
|
||||
return {"table": str(p), "count": 1, "save_as": "", "count_expr": "", "when": "", "otherwise": false, "with": {}}
|
||||
|
||||
|
||||
|
|
@ -543,84 +342,6 @@ static func dice_max(dice: String) -> int:
|
|||
return m.get_string(1).to_int() * m.get_string(2).to_int()
|
||||
|
||||
|
||||
## Id of the table whose name matches (case-insensitive), or "".
|
||||
static func table_id_by_name(collection: Dictionary, table_name: String) -> String:
|
||||
var want := table_name.strip_edges().to_lower()
|
||||
for t in collection.get("tables", []):
|
||||
if str(t.get("name", "")).to_lower() == want:
|
||||
return str(t.get("id", ""))
|
||||
return ""
|
||||
|
||||
|
||||
## Every connection in a collection, pipes and inline references, in
|
||||
## table/entry order. Each item: kind ("pipe" or "ref"), table_index,
|
||||
## entry_index, from_table, from_entry (ids), target (table id, or "" when the
|
||||
## table is missing), target_name (as written), label, count, save_as,
|
||||
## entry_text (BBCode stripped). Expects a canonical collection.
|
||||
static func links(collection: Dictionary) -> Array[Dictionary]:
|
||||
var out: Array[Dictionary] = []
|
||||
var tables: Array = collection.get("tables", [])
|
||||
var ids := {}
|
||||
for t in tables:
|
||||
ids[str(t["id"])] = true
|
||||
for ti in tables.size():
|
||||
var t2: Dictionary = tables[ti]
|
||||
var elist: Array = t2.get("entries", [])
|
||||
for ei in elist.size():
|
||||
var e: Dictionary = elist[ei]
|
||||
for p in e.get("pipes", []):
|
||||
var info := pipe_info(p)
|
||||
var tgt: String = info["table"]
|
||||
out.append({
|
||||
"kind": "pipe", "table_index": ti, "entry_index": ei,
|
||||
"from_table": t2["id"], "from_entry": e["id"],
|
||||
"target": tgt if ids.has(tgt) else "", "target_name": tgt,
|
||||
"label": pipe_label(info), "count": info["count"], "save_as": info["save_as"],
|
||||
"entry_text": strip_bbcode(str(e["text"])),
|
||||
})
|
||||
for ref in find_refs(str(e["text"])):
|
||||
var rid := table_id_by_name(collection, ref["name"])
|
||||
out.append({
|
||||
"kind": "ref", "table_index": ti, "entry_index": ei,
|
||||
"from_table": t2["id"], "from_entry": e["id"],
|
||||
"target": rid, "target_name": ref["name"],
|
||||
"label": ("ref → " + ref["var"]) if ref["var"] != "" else "ref",
|
||||
"count": 1, "save_as": ref["var"],
|
||||
"entry_text": strip_bbcode(str(e["text"])),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
## Display label for a table number range, zero padded; the top of a d100 or
|
||||
## d1000 reads as zeros ("96–00").
|
||||
static func range_text(lo: int, hi: int, dmax: int) -> String:
|
||||
return "%s–%s" % [_num_text(lo, dmax), _num_text(hi, dmax)]
|
||||
|
||||
|
||||
static func _num_text(n: int, dmax: int) -> String:
|
||||
if dmax >= 100 and _is_power_of_ten(dmax):
|
||||
if n == dmax:
|
||||
return "0".repeat(str(dmax - 1).length())
|
||||
return str(n).pad_zeros(str(dmax - 1).length())
|
||||
return str(n).pad_zeros(str(maxi(dmax, 1)).length())
|
||||
|
||||
|
||||
static func _is_power_of_ten(n: int) -> bool:
|
||||
while n >= 10 and n % 10 == 0:
|
||||
n /= 10
|
||||
return n == 1
|
||||
|
||||
|
||||
## An entry as one plain line for an export: "3-4: text", "2 × text" or "text".
|
||||
static func entry_line(e: Dictionary, dmax: int) -> String:
|
||||
var plain := strip_bbcode(str(e["text"]))
|
||||
if e.has("range"):
|
||||
var r: Array = e["range"]
|
||||
return "%s: %s" % [range_text(int(r[0]), int(r[1]), dmax), plain]
|
||||
var w: Variant = e.get("weight", 1)
|
||||
if w != 1:
|
||||
return "%s × %s" % [str(w), plain]
|
||||
return plain
|
||||
|
||||
|
||||
## Imports a converted collection (`raw`) and adds its warnings, errors and
|
||||
|
|
@ -632,3 +353,27 @@ static func finish_import(raw: Dictionary, sanitize: Callable, result: Dictionar
|
|||
result["ok"] = imported["ok"]
|
||||
result["collection"] = imported["collection"]
|
||||
return result
|
||||
|
||||
|
||||
static func canonical(src: Dictionary) -> Dictionary:
|
||||
return JsonCanon.canonical(src)
|
||||
|
||||
|
||||
static func entry_line(e: Dictionary, dmax: int) -> String:
|
||||
return JsonLinks.entry_line(e, dmax)
|
||||
|
||||
|
||||
static func links(collection: Dictionary) -> Array[Dictionary]:
|
||||
return JsonLinks.links(collection)
|
||||
|
||||
|
||||
static func range_text(lo: int, hi: int, dmax: int) -> String:
|
||||
return JsonLinks.range_text(lo, hi, dmax)
|
||||
|
||||
|
||||
static func table_id_by_name(collection: Dictionary, table_name: String) -> String:
|
||||
return JsonLinks.table_id_by_name(collection, table_name)
|
||||
|
||||
|
||||
static func _canon_table(td: Dictionary) -> Dictionary:
|
||||
return JsonCanon._canon_table(td)
|
||||
|
|
|
|||
83
io/json_links.gd
Normal file
83
io/json_links.gd
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
class_name JsonLinks
|
||||
extends RefCounted
|
||||
## Connections and plain-text entry lines for exports (see JsonIO).
|
||||
|
||||
|
||||
## Id of the table whose name matches (case-insensitive), or "".
|
||||
static func table_id_by_name(collection: Dictionary, table_name: String) -> String:
|
||||
var want := table_name.strip_edges().to_lower()
|
||||
for t in collection.get("tables", []):
|
||||
if str(t.get("name", "")).to_lower() == want:
|
||||
return str(t.get("id", ""))
|
||||
return ""
|
||||
|
||||
|
||||
## Every connection in a collection, pipes and inline references, in
|
||||
## table/entry order. Each item: kind ("pipe" or "ref"), table_index,
|
||||
## entry_index, from_table, from_entry (ids), target (table id, or "" when the
|
||||
## table is missing), target_name (as written), label, count, save_as,
|
||||
## entry_text (BBCode stripped). Expects a canonical collection.
|
||||
static func links(collection: Dictionary) -> Array[Dictionary]:
|
||||
var out: Array[Dictionary] = []
|
||||
var tables: Array = collection.get("tables", [])
|
||||
var ids := {}
|
||||
for t in tables:
|
||||
ids[str(t["id"])] = true
|
||||
for ti in tables.size():
|
||||
var t2: Dictionary = tables[ti]
|
||||
var elist: Array = t2.get("entries", [])
|
||||
for ei in elist.size():
|
||||
var e: Dictionary = elist[ei]
|
||||
for p in e.get("pipes", []):
|
||||
var info := JsonIO.pipe_info(p)
|
||||
var tgt: String = info["table"]
|
||||
out.append({
|
||||
"kind": "pipe", "table_index": ti, "entry_index": ei,
|
||||
"from_table": t2["id"], "from_entry": e["id"],
|
||||
"target": tgt if ids.has(tgt) else "", "target_name": tgt,
|
||||
"label": JsonIO.pipe_label(info), "count": info["count"], "save_as": info["save_as"],
|
||||
"entry_text": JsonIO.strip_bbcode(str(e["text"])),
|
||||
})
|
||||
for ref in JsonIO.find_refs(str(e["text"])):
|
||||
var rid := table_id_by_name(collection, ref["name"])
|
||||
out.append({
|
||||
"kind": "ref", "table_index": ti, "entry_index": ei,
|
||||
"from_table": t2["id"], "from_entry": e["id"],
|
||||
"target": rid, "target_name": ref["name"],
|
||||
"label": ("ref → " + ref["var"]) if ref["var"] != "" else "ref",
|
||||
"count": 1, "save_as": ref["var"],
|
||||
"entry_text": JsonIO.strip_bbcode(str(e["text"])),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
## Display label for a table number range, zero padded; the top of a d100 or
|
||||
## d1000 reads as zeros ("96–00").
|
||||
static func range_text(lo: int, hi: int, dmax: int) -> String:
|
||||
return "%s–%s" % [_num_text(lo, dmax), _num_text(hi, dmax)]
|
||||
|
||||
|
||||
static func _num_text(n: int, dmax: int) -> String:
|
||||
if dmax >= 100 and _is_power_of_ten(dmax):
|
||||
if n == dmax:
|
||||
return "0".repeat(str(dmax - 1).length())
|
||||
return str(n).pad_zeros(str(dmax - 1).length())
|
||||
return str(n).pad_zeros(str(maxi(dmax, 1)).length())
|
||||
|
||||
|
||||
static func _is_power_of_ten(n: int) -> bool:
|
||||
while n >= 10 and n % 10 == 0:
|
||||
n /= 10
|
||||
return n == 1
|
||||
|
||||
|
||||
## An entry as one plain line for an export: "3-4: text", "2 × text" or "text".
|
||||
static func entry_line(e: Dictionary, dmax: int) -> String:
|
||||
var plain := JsonIO.strip_bbcode(str(e["text"]))
|
||||
if e.has("range"):
|
||||
var r: Array = e["range"]
|
||||
return "%s: %s" % [range_text(int(r[0]), int(r[1]), dmax), plain]
|
||||
var w: Variant = e.get("weight", 1)
|
||||
if w != 1:
|
||||
return "%s × %s" % [str(w), plain]
|
||||
return plain
|
||||
1
io/json_links.gd.uid
Normal file
1
io/json_links.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://i7qjiydrprhh
|
||||
Loading…
Reference in a new issue