TableTower/core/describe_why.gd

300 lines
12 KiB
GDScript3
Raw Normal View History

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)
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]
"repeat":
var got := PackedStringArray()
for x: Dictionary in fact.get("rolls", []):
got.append("%s (%s)" % [x.get("text", ""), Expr.format_value(x.get("value"))])
s = ("Rolled it %d times and combined them: " % got.size() if plain else "repeat ×%d: " % got.size()) + ", ".join(got)
if str(fact.get("column", "")) != "":
s = "%s: %s" % [fact["column"], s]
"only_option":
s = "Picked the only option there was" if plain else "only one option: picked it"
"check":
s = _why_check(fact, L, plain)
"when":
s = _why_when(fact, board, L, plain)
"otherwise":
var to := _table(str(fact.get("to", "")), board, plain)
var card := bool(fact.get("card", false))
if bool(fact.get("result", false)):
if card:
s = "Took the card thread to %s because no other thread ran" % to if plain else "%s: card otherwise, ran (no other thread ran)" % to
else:
s = "Took %s because no condition was true" % to if plain else "%s: otherwise, ran (no condition was true)" % to
elif card:
s = "Skipped the card thread to %s because another thread ran" % to if plain else "%s: card otherwise, skipped" % 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":
if f.has("from") and _nonzero(f.get("mod", 0)):
var by := " for " + Describe._expr(str(f.get("mod_expr", "")).trim_prefix("-"), L) if str(f.get("mod_expr", "")) != "" else ""
if not plain:
return "roll %s: %s, moved %s rows = %s" % [f.get("dice", ""), Expr.format_value(f["from"]), _signed(f["mod"]).replace(Describe.MINUS, "-"), total]
return "Rolled %s on %s, moved %s %s%s, to row %s" % [Expr.format_value(f["from"]), f.get("dice", ""),
"down" if float(f["mod"]) > 0 else "up", _rows(absi(int(f["mod"]))), by, total]
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 _rows(count: int) -> String:
return "1 row" if count == 1 else "%d rows" % count
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)