TableTower/core/describe.gd

396 lines
13 KiB
GDScript3
Raw Normal View History

class_name Describe
extends RefCounted
## Rules in plain words (docs/PLAIN.md §1): pure functions that turn stored
## rule text into short phrases, using value labels (§3). Anything they can't
## read comes back as the original text; they never fail and keep phrases
## short (MAX_LEN characters, else the original text or a cut with "…").
##
## Labels: a value's label is its variable card's name, else the collection
## it belongs to names it by the rest of its name ("@skill_gun_combat" in the
## Skills collection -> "Gun Combat"), else a pretty form of its name ("soc"
## -> "Soc"). Card inputs are labelled by their declared label. `board` may be
## null everywhere (pretty names only).
## Longest phrase before falling back to the original text (or a cut).
const MAX_LEN := 90
const MINUS := "−"
const _CHAIN_LABELS := {"answer": "Answer", "i": "Pass", "nat": "Natural roll", "total": "Total",
"effect": "Effect", "option": "Chosen option", "option_label": "Chosen option",
"option_value": "Chosen value"}
const _OPS := {"*": "×", "/": "÷", "-": MINUS, "==": "=", "!=": "≠", ">=": "≥", "<=": "≤"}
# ---------------------------------------------------------------- labels
## What each kind of card is called in the UI (search, inspector, settings, previews).
const KIND_LABELS := {
RollTable.KIND_ROLL: "Roll table", RollTable.KIND_CHOICE: "Choice", RollTable.KIND_LOOP: "Repeat",
RollTable.KIND_ROUTER: "Branch", RollTable.KIND_CHECK: "Check", RollTable.KIND_VARIABLE: "Variable",
RollTable.KIND_SHEET: "Sheet",
}
## What each kind of choice is called (the + Card menu, settings, card, previews).
const CHOICE_LABELS := {"pick": "Which option", "number": "How many", "text": "Open ended"}
## "Roll table", "Check", "Collection", ...
static func kind_label(t: RollTable) -> String:
return "Collection" if t.is_collection() else str(KIND_LABELS.get(t.kind, "Card"))
## "Which option", "How many" or "Open ended".
static func choice_label(choice: String) -> String:
return str(CHOICE_LABELS.get(choice, choice))
## The choice kinds' labels in RollTable.CHOICES order (for segmented pickers).
static func choice_labels() -> Array:
return RollTable.CHOICES.map(choice_label)
## The label of a value: "@luck", "@skill_pilot", "@skill_*" (a collection
## or prefix: "Skills", or "Skill values" without a collection card), "@[…]"
## ("Chosen value"), or a chain name ("answer" -> "Answer", an input's label).
static func label(name: String, board: TowerBoard) -> String:
return _label(name, _labels(board))
## Label table for a board: {"vars": {name: label}, "stems": [[stem, label]]
## longest first, "inputs": {name: label}}.
static func _labels(board: TowerBoard) -> Dictionary:
var vars := {}
var stems: Array = []
var inputs := {}
if board != null:
for t in board.tables:
if t.kind == RollTable.KIND_VARIABLE and t.var_name != "":
var lab := Formatter.strip_tags(t.name).strip_edges()
if t.var_type == RollTable.VAR_COLLECTION:
stems.append([t.var_name, lab if lab != "" else RollContext.pretty_name(t.var_name)])
elif lab != "" and not vars.has(t.var_name):
vars[t.var_name] = lab
for inp: Dictionary in t.inputs:
var il := str(inp.get("label", "")).strip_edges()
if il != "" and not inputs.has(str(inp.get("name", ""))):
inputs[str(inp.get("name", ""))] = il
stems.sort_custom(func(a: Array, b: Array) -> bool: return str(a[0]).length() > str(b[0]).length())
return {"vars": vars, "stems": stems, "inputs": inputs}
static func _label(name: String, L: Dictionary) -> String:
var n := name.strip_edges()
if n.begins_with("@["):
return "Chosen value"
if n.begins_with("@"):
n = n.substr(1).to_lower()
if n.ends_with("*"):
var stem := n.trim_suffix("*").trim_suffix("_")
for sp: Array in L["stems"]:
if sp[0] == stem:
return sp[1]
return "%s values" % RollContext.pretty_name(stem)
if L["vars"].has(n):
return L["vars"][n]
for sp: Array in L["stems"]:
var pre := str(sp[0]) + "_"
if n.begins_with(pre) and n.length() > pre.length():
return RollContext.pretty_name(n.substr(pre.length()))
return RollContext.pretty_name(n)
if L["inputs"].has(n):
return L["inputs"][n]
if _CHAIN_LABELS.has(n):
return _CHAIN_LABELS[n]
return RollContext.pretty_name(n)
## The collection a value belongs to ({"stem", "label"}) or {}.
static func _collection_of(name: String, L: Dictionary) -> Dictionary:
var n := name.strip_edges().trim_prefix("@").to_lower()
for sp: Array in L["stems"]:
var pre := str(sp[0]) + "_"
if n.begins_with(pre):
return {"stem": sp[0], "label": sp[1]}
return {}
# ---------------------------------------------------------------- effects
## One effect statement in plain words: "@luck -= 1" -> "Luck −1",
## "@town = \"Millbrook\"" -> "Town = Millbrook", "reset @skill_*" -> "Reset
## all Skills", "@traits += \"Psionic\"" -> "Add Psionic to Traits",
## "@[option] += 1" -> "Chosen skill +1" when `table` is a pick card taking
## options from a collection (else "Chosen value +1").
static func effect(stmt: String, board: TowerBoard, table: RollTable = null) -> String:
return _effect(stmt, _labels(board), table)
## One phrase per statement of an effects field.
static func effects(text: String, board: TowerBoard, table: RollTable = null) -> Array[String]:
var L := _labels(board)
var out: Array[String] = []
for s in Effects.split(text):
out.append(_effect(s, L, table))
return out
static func _effect(stmt: String, L: Dictionary, table: RollTable) -> String:
var src := stmt.strip_edges()
var m := Builder.parse_effect(src)
if not m["ok"]:
return src
var v := str(m["var"])
var subj := _chosen(table, L) if v.begins_with("@[") else _label(v, L)
var amount := str(m["amount"])
var out := ""
match str(m["op"]):
"reset":
if v.ends_with("*"):
out = "Reset all " + _label(v, L)
elif L["vars"].has(v.trim_prefix("@")):
out = "Reset " + subj
else:
out = "Clear " + subj
"set":
out = "%s = %s" % [subj, _expr(amount, L)]
"add", "subtract":
var sub: bool = m["op"] == "subtract"
if amount.is_valid_float() and not amount.to_lower().contains("e") and not amount.to_lower().contains("n"):
var x: Variant = Expr.to_value(amount)
if x < 0:
sub = not sub
x = -x
out = "%s %s%s" % [subj, MINUS if sub else "+", Expr.format_value(x)]
else:
out = "%s %s %s" % [subj, MINUS if sub else "+", _expr(amount, L)]
"multiply":
out = "%s ×%s" % [subj, _compact(amount, L)]
"divide":
out = "%s ÷%s" % [subj, _compact(amount, L)]
"append":
out = "Add %s to %s" % [amount, subj]
"remove":
out = "Remove %s from %s" % [amount, subj]
return _short(out, src)
static func _compact(amount: String, L: Dictionary) -> String:
var t := Builder.tokens(amount)
var e := _expr(amount, L)
return e if t.size() == 1 else " " + e
## "Chosen skill" on a pick card whose options come from a collection, else
## "Chosen value".
static func _chosen(table: RollTable, L: Dictionary) -> String:
if table != null and table.is_dynamic():
var p := RollTable.parse_options_from(table.options_from)
if str(p["kind"]) == "prefix":
var stem := str(p["name"]).trim_suffix("_")
for sp: Array in L["stems"]:
if sp[0] == stem:
return "Chosen " + _singular(str(sp[1]).to_lower())
return "Chosen value"
static func _singular(s: String) -> String:
if s.length() > 3 and s.ends_with("s") and not s.ends_with("ss"):
return s.substr(0, s.length() - 1)
return s
# ---------------------------------------------------------------- conditions
## A condition in plain words: "@str >= 8" -> "Strength is 8 or more",
## "@x = 0 and @soc >= 9" -> "X is 0 and Social Standing is 9 or more",
## "has(@traits, \"Psionic\")" -> "Traits include Psionic". "" for an empty
## condition; the original text for anything Builder.parse_condition() can't
## read.
static func condition(expr: String, board: TowerBoard) -> String:
return _condition(expr, _labels(board))
static func _condition(expr: String, L: Dictionary) -> String:
var src := expr.strip_edges()
var m := Builder.parse_condition(src)
if not m["ok"]:
return src
var parts := PackedStringArray()
for c: Dictionary in m["clauses"]:
parts.append(_clause(c, L))
return _short((" %s " % m["join"]).join(parts), src)
static func _clause(c: Dictionary, L: Dictionary) -> String:
var subj := _label(str(c["var"]), L)
var cmp := str(c["cmp"])
match cmp:
"set":
return subj + " is set"
"unset":
return subj + " is not set"
"has":
return "%s include %s" % [subj, _value(str(c["value"]), L)]
return "%s %s" % [subj, _tail(cmp, str(c["value"]), L)]
## The comparison after a value name: "is 8 or more", "is at most 3", "is
## Aslan", "is not 0", "is more than 2", "is less than 2".
static func _tail(cmp: String, value: String, L: Dictionary) -> String:
var v := _value(value, L)
var num := Expr.is_number(value) or (value.begins_with("-") and Expr.is_number(value.substr(1)))
match cmp:
"eq":
return "is " + v
"ne":
return "is not " + v
"ge":
return ("is %s or more" % v) if num else "is at least " + v
"le":
return "is at most " + v
"gt":
return "is more than " + v
"lt":
return "is less than " + v
"has":
return "includes " + v
"set":
return "is set"
"unset":
return "is not set"
return "%s %s" % [cmp, v]
## A value token in words: numbers as they are, quoted text without quotes,
## @names and chain names by label, true/false as yes/no.
static func _value(tok: String, L: Dictionary) -> String:
var s := tok.strip_edges()
if s == "true":
return "yes"
if s == "false":
return "no"
if Builder.is_text_literal(s):
var u := Builder.unquote(s)
return u if u != "" else "empty"
if s.begins_with("-") and Expr.is_number(s.substr(1)):
return MINUS + s.substr(1)
if Expr.is_number(s):
return s
if s.begins_with("@") or Builder._is_word(s.substr(0, 1)):
return _label(s, L)
return s
# ---------------------------------------------------------------- dice
## A dice or count expression in plain words: "2d6 + dm(@str)" -> "2d6 +
## Strength modifier", "1d6 + tier" -> "d6 + Tier", "@terms" -> "Terms".
## d6 dice read as "ND"; other dice as "dN" / "NdM". Text that can't be read
## comes back as it is.
static func dice(expr: String, board: TowerBoard) -> String:
return _expr(expr, _labels(board))
static func _expr(expr: String, L: Dictionary) -> String:
var src := expr.strip_edges()
if src == "":
return ""
var toks := Builder.tokens(src)
if toks.is_empty():
return src
var pieces: Array = [] # [kind, text]; kinds: val fn op neg ( ) ,
var k := 0
while k < toks.size():
var tk: Dictionary = toks[k]
var t := str(tk["t"])
var s := str(tk["s"])
var prevk := str(pieces.back()[0]) if not pieces.is_empty() else ""
# dm(x) with one value inside: "X modifier".
if t == "name" and s == "dm" and k + 3 < toks.size() and toks[k + 1]["s"] == "(" and toks[k + 3]["s"] == ")" \
and ["var", "name", "num"].has(str(toks[k + 2]["t"])):
pieces.append(["val", _value(str(toks[k + 2]["s"]), L) + " modifier"])
k += 4
continue
k += 1
match t:
"dice":
var dp := Builder.dice_parts(s)
if int(dp[0]) == 1:
pieces.append(["val", "d%d" % int(dp[1])])
else:
pieces.append(["val", "%dd%d" % [int(dp[0]), int(dp[1])]])
"var", "prefix":
pieces.append(["val", _label(s, L)])
"name":
if k < toks.size() and toks[k]["s"] == "(":
pieces.append(["fn", s])
else:
pieces.append(["val", _value(s, L)])
"num":
pieces.append(["val", s])
"str":
pieces.append(["val", Builder.unquote(s)])
"kw":
pieces.append(["op", s])
_:
if s == "(" or s == ")" or s == ",":
pieces.append([s, s])
elif s == "-" and (prevk == "" or prevk == "op" or prevk == "(" or prevk == "," or prevk == "neg"):
pieces.append(["neg", MINUS])
else:
pieces.append(["op", _OPS.get(s, s)])
var out := ""
var prev := ""
for pc: Array in pieces:
var kind := str(pc[0])
var space := false
match kind:
"op":
space = out != ""
"val", "fn":
space = prev in ["op", ",", "val", ")"]
"(", "neg":
space = prev in ["op", ","]
if space:
out += " "
out += str(pc[1])
prev = kind
return _short(out, src)
# ---------------------------------------------------------------- helpers
## `s`, or when it's too long the original text (if that's shorter) or a cut.
static func _short(s: String, original: String) -> String:
if s.length() <= MAX_LEN:
return s
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)