Logic cards engine: expressions, effects, choice/loop/variable/sheet cards, coroutine roller
- Expr: @vars, chain vars, dice tokens, dm/has/count, lone = as ==, errors as values, parse cache
- Effects: = += -= *= /= and reset (with prefix), number vs list semantics, logs, validation
- RollTable kinds and per-kind fields with factories; expression dice with end clamping
- TableEntry effects and expression pipe counts; JSON round trip through JsonIO
- TextExpander: {@prefix_*}, {= expr}, number display, expand_async and live render()
- Roller: coroutine with an explicit work stack, prompts for choice cards, loops,
10,000-action limit, partial tree on ctx.root, iterative flatten/collect_lit
- Variables keep numbers as numbers through StateStore
- Main: awaits the roll with a default (headless) prompt hook, iterative playback,
long chains show at once
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
49b9a0c10e
commit
85b8a99ef5
19 changed files with 2585 additions and 147 deletions
|
|
@ -34,7 +34,7 @@ func reshuffle() -> void:
|
||||||
## Copies of this entry that are in the deck in total.
|
## Copies of this entry that are in the deck in total.
|
||||||
static func copies_of(table: RollTable, e: TableEntry) -> int:
|
static func copies_of(table: RollTable, e: TableEntry) -> int:
|
||||||
if table.is_ranged():
|
if table.is_ranged():
|
||||||
return 1 if e.has_range and table.chance(e) > 0.0 else 0
|
return 1 if table.can_come_up(e) else 0
|
||||||
return maxi(0, e.weight)
|
return maxi(0, e.weight)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -60,7 +60,7 @@ func draw(table: RollTable, rng: RandomNumberGenerator) -> Dictionary:
|
||||||
for e in table.entries:
|
for e in table.entries:
|
||||||
var w := float(_remaining(table, e))
|
var w := float(_remaining(table, e))
|
||||||
if table.is_ranged():
|
if table.is_ranged():
|
||||||
w *= table.chance(e)
|
w *= 1.0 if table.is_expr_dice() else table.chance(e)
|
||||||
weights.append(w)
|
weights.append(w)
|
||||||
sum += w
|
sum += w
|
||||||
if sum <= 0.0:
|
if sum <= 0.0:
|
||||||
|
|
@ -84,6 +84,8 @@ func draw(table: RollTable, rng: RandomNumberGenerator) -> Dictionary:
|
||||||
|
|
||||||
## A die value inside the entry's range, weighted by the dice distribution.
|
## A die value inside the entry's range, weighted by the dice distribution.
|
||||||
func _value_in(table: RollTable, e: TableEntry, rng: RandomNumberGenerator) -> int:
|
func _value_in(table: RollTable, e: TableEntry, rng: RandomNumberGenerator) -> int:
|
||||||
|
if table.is_expr_dice():
|
||||||
|
return rng.randi_range(e.range_lo, e.range_hi)
|
||||||
var dist := table.dice_obj().distribution()
|
var dist := table.dice_obj().distribution()
|
||||||
var vals: Array[int] = []
|
var vals: Array[int] = []
|
||||||
var mass := 0.0
|
var mass := 0.0
|
||||||
|
|
|
||||||
237
core/effects.gd
Normal file
237
core/effects.gd
Normal file
|
|
@ -0,0 +1,237 @@
|
||||||
|
class_name Effects
|
||||||
|
extends RefCounted
|
||||||
|
## Effect statements on entries (docs/LOGIC.md §5.2): one per line or
|
||||||
|
## separated by ";".
|
||||||
|
##
|
||||||
|
## @str = 2d6 set
|
||||||
|
## @terms += 1 add a number, or append ", item" to text/list if absent
|
||||||
|
## @credits -= 1000 subtract a number, or remove the item from text/list
|
||||||
|
## @age *= 2 multiply (/= divides, rounding down)
|
||||||
|
## reset @name back to the variable card's starting value, or deleted
|
||||||
|
## reset @skill_* every variable with that prefix
|
||||||
|
##
|
||||||
|
## A target without "@" is a chain variable. Unset counts as 0 (or "" when the
|
||||||
|
## value added is text). run() never stops on a bad statement: it logs an error
|
||||||
|
## line and carries on.
|
||||||
|
|
||||||
|
const OPS := ["+=", "-=", "*=", "/=", "="]
|
||||||
|
|
||||||
|
static var _stmt_re: RegEx = null
|
||||||
|
static var _reset_re: RegEx = null
|
||||||
|
|
||||||
|
|
||||||
|
## Splits effect text into statements: lines, and ";" outside quotes. Empty
|
||||||
|
## statements are dropped.
|
||||||
|
static func split(text: String) -> Array[String]:
|
||||||
|
var out: Array[String] = []
|
||||||
|
var cur := ""
|
||||||
|
var quote := ""
|
||||||
|
for c in text:
|
||||||
|
if quote != "":
|
||||||
|
cur += c
|
||||||
|
if c == quote:
|
||||||
|
quote = ""
|
||||||
|
elif c == "\"" or c == "'":
|
||||||
|
quote = c
|
||||||
|
cur += c
|
||||||
|
elif c == ";" or c == "\n":
|
||||||
|
if cur.strip_edges() != "":
|
||||||
|
out.append(cur.strip_edges())
|
||||||
|
cur = ""
|
||||||
|
else:
|
||||||
|
cur += c
|
||||||
|
if cur.strip_edges() != "":
|
||||||
|
out.append(cur.strip_edges())
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
## Parses one statement. Returns {src, op ("=", "+=", "-=", "*=", "/=" or
|
||||||
|
## "reset"), target ("@name", "name", or "@prefix_*" for reset), expr} or
|
||||||
|
## {src, error}.
|
||||||
|
static func parse_statement(src: String) -> Dictionary:
|
||||||
|
_compile()
|
||||||
|
var s := src.strip_edges()
|
||||||
|
var m := _reset_re.search(s)
|
||||||
|
if m != null:
|
||||||
|
var target := "@" + m.get_string(1).to_lower() + m.get_string(2)
|
||||||
|
return {"src": s, "op": "reset", "target": target, "expr": ""}
|
||||||
|
if s.to_lower().begins_with("reset"):
|
||||||
|
return {"src": s, "error": "Write reset @name or reset @prefix_*"}
|
||||||
|
m = _stmt_re.search(s)
|
||||||
|
if m == null:
|
||||||
|
return {"src": s, "error": "Not a statement; try @name = value"}
|
||||||
|
var t := m.get_string(1)
|
||||||
|
if t.begins_with("@"):
|
||||||
|
t = t.to_lower()
|
||||||
|
var expr := m.get_string(3).strip_edges()
|
||||||
|
if expr == "":
|
||||||
|
return {"src": s, "error": "Nothing after %s" % m.get_string(2)}
|
||||||
|
return {"src": s, "op": m.get_string(2), "target": t, "expr": expr}
|
||||||
|
|
||||||
|
|
||||||
|
## Problems in effect text for the Build-mode editor: Array of {index (0-based
|
||||||
|
## statement number), src, error}. Empty when everything parses.
|
||||||
|
static func validate(text: String) -> Array[Dictionary]:
|
||||||
|
var out: Array[Dictionary] = []
|
||||||
|
var list := split(text)
|
||||||
|
for k in list.size():
|
||||||
|
var st := parse_statement(list[k])
|
||||||
|
var err := str(st.get("error", ""))
|
||||||
|
if err == "" and st["op"] != "reset":
|
||||||
|
err = Expr.check(st["expr"])
|
||||||
|
if err != "":
|
||||||
|
out.append({"index": k, "src": list[k], "error": err})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
## Runs every statement against the context. Returns the log, one line per
|
||||||
|
## statement: Array of {"text": String, "error": bool (only when true)}.
|
||||||
|
## `source_id` is stored as the variables' source table.
|
||||||
|
static func run(text: String, ctx: RollContext, source_id: String = "") -> Array[Dictionary]:
|
||||||
|
var log: Array[Dictionary] = []
|
||||||
|
if text.strip_edges() == "":
|
||||||
|
return log
|
||||||
|
for src in split(text):
|
||||||
|
var st := parse_statement(src)
|
||||||
|
if st.has("error"):
|
||||||
|
log.append({"text": "%s: %s" % [src, st["error"]], "error": true})
|
||||||
|
continue
|
||||||
|
if st["op"] == "reset":
|
||||||
|
log.append(_reset(st["target"], ctx))
|
||||||
|
else:
|
||||||
|
log.append(_assign(st, ctx, source_id))
|
||||||
|
return log
|
||||||
|
|
||||||
|
|
||||||
|
## Plain log lines (errors included), for copying and history.
|
||||||
|
static func log_text(log: Array) -> PackedStringArray:
|
||||||
|
var out := PackedStringArray()
|
||||||
|
for l: Variant in log:
|
||||||
|
out.append(str((l as Dictionary).get("text", "")) if l is Dictionary else str(l))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
static func _assign(st: Dictionary, ctx: RollContext, source_id: String) -> Dictionary:
|
||||||
|
var target: String = st["target"]
|
||||||
|
var op: String = st["op"]
|
||||||
|
var r := Expr.evaluate(st["expr"], ctx)
|
||||||
|
if r["error"] != "":
|
||||||
|
return {"text": "%s: %s" % [st["src"], r["error"]], "error": true}
|
||||||
|
var rhs: Variant = Expr.normalize(r["value"])
|
||||||
|
var label := ctx.display_name(target) if target.begins_with("@") else target
|
||||||
|
var cur: Variant = ctx.get_value(target)
|
||||||
|
var type := ""
|
||||||
|
if target.begins_with("@"):
|
||||||
|
var card := ctx.declared(target)
|
||||||
|
if card != null:
|
||||||
|
type = card.var_type
|
||||||
|
var as_list := false
|
||||||
|
if op == "+=" or op == "-=":
|
||||||
|
if type == "text" or type == "list":
|
||||||
|
as_list = true
|
||||||
|
elif type == "number":
|
||||||
|
as_list = false
|
||||||
|
else:
|
||||||
|
as_list = not Expr.is_number(rhs) or (cur != null and not Expr.is_number(cur) and str(cur).strip_edges() != "")
|
||||||
|
var value: Variant
|
||||||
|
var line: String
|
||||||
|
match op:
|
||||||
|
"=":
|
||||||
|
if type == "number" and not Expr.is_number(rhs):
|
||||||
|
return {"text": "%s: %s is a number, not \"%s\"" % [st["src"], label, Expr.format_value(rhs)], "error": true}
|
||||||
|
value = Expr.to_value(rhs) if type == "number" else rhs
|
||||||
|
line = "%s = %s" % [label, _shown(value)]
|
||||||
|
"+=", "-=":
|
||||||
|
if as_list:
|
||||||
|
var items := Expr.list_items(cur if cur != null else "")
|
||||||
|
var item := Expr.format_value(rhs).strip_edges()
|
||||||
|
var at := -1
|
||||||
|
for k in items.size():
|
||||||
|
if items[k].to_lower() == item.to_lower():
|
||||||
|
at = k
|
||||||
|
break
|
||||||
|
if op == "+=" and at < 0 and item != "":
|
||||||
|
items.append(item)
|
||||||
|
elif op == "-=" and at >= 0:
|
||||||
|
items.remove_at(at)
|
||||||
|
value = ", ".join(items)
|
||||||
|
line = "%s %s %s → %s" % [label, "+" if op == "+=" else "−", item, _shown(value)]
|
||||||
|
else:
|
||||||
|
var a: Variant = Expr.to_value(cur) if cur != null and str(cur).strip_edges() != "" else 0
|
||||||
|
var b: Variant = Expr.to_value(rhs)
|
||||||
|
if not Expr.is_number(a) or not Expr.is_number(b):
|
||||||
|
return {"text": "%s: %s needs a number" % [st["src"], label], "error": true}
|
||||||
|
var delta: Variant = b if op == "+=" else -b
|
||||||
|
value = Expr.normalize(a + delta)
|
||||||
|
line = "%s %s → %s" % [label, _signed(delta), _shown(value)]
|
||||||
|
"*=", "/=":
|
||||||
|
var a2: Variant = Expr.to_value(cur) if cur != null and str(cur).strip_edges() != "" else 0
|
||||||
|
var b2: Variant = Expr.to_value(rhs)
|
||||||
|
if not Expr.is_number(a2) or not Expr.is_number(b2):
|
||||||
|
return {"text": "%s: %s needs a number" % [st["src"], label], "error": true}
|
||||||
|
if op == "*=":
|
||||||
|
value = Expr.normalize(a2 * b2)
|
||||||
|
line = "%s ×%s → %s" % [label, Expr.format_value(b2), _shown(value)]
|
||||||
|
else:
|
||||||
|
if b2 == 0:
|
||||||
|
return {"text": "%s: can't divide by 0" % st["src"], "error": true}
|
||||||
|
value = floori(float(a2) / float(b2))
|
||||||
|
line = "%s ÷%s → %s" % [label, Expr.format_value(b2), _shown(value)]
|
||||||
|
ctx.save(target, value, source_id)
|
||||||
|
return {"text": line}
|
||||||
|
|
||||||
|
|
||||||
|
static func _reset(target: String, ctx: RollContext) -> Dictionary:
|
||||||
|
if target.ends_with("*"):
|
||||||
|
var prefix := target.trim_prefix("@").trim_suffix("*")
|
||||||
|
var names := {}
|
||||||
|
for n: String in ctx.persistent_vars:
|
||||||
|
if n.begins_with(prefix):
|
||||||
|
names[n] = true
|
||||||
|
for n in ctx.declared_names():
|
||||||
|
if n.begins_with(prefix):
|
||||||
|
names[n] = true
|
||||||
|
var errors := PackedStringArray()
|
||||||
|
for n: String in names:
|
||||||
|
var r := reset_one(n, ctx)
|
||||||
|
if r != "":
|
||||||
|
errors.append(r)
|
||||||
|
if not errors.is_empty():
|
||||||
|
return {"text": "reset %s: %s" % [target, "; ".join(errors)], "error": true}
|
||||||
|
return {"text": "Reset %s (%d)" % [target, names.size()]}
|
||||||
|
var name := target.trim_prefix("@")
|
||||||
|
var err := reset_one(name, ctx)
|
||||||
|
if err != "":
|
||||||
|
return {"text": "reset %s: %s" % [target, err], "error": true}
|
||||||
|
var v: Variant = ctx.get_value("@" + name)
|
||||||
|
if v == null:
|
||||||
|
return {"text": "Reset %s (cleared)" % ctx.display_name(name)}
|
||||||
|
return {"text": "Reset %s → %s" % [ctx.display_name(name), _shown(v)]}
|
||||||
|
|
||||||
|
|
||||||
|
## Resets one board variable (no "@"): a declared one goes back to its starting
|
||||||
|
## value, an undeclared one is deleted. Returns an error message or "".
|
||||||
|
static func reset_one(name: String, ctx: RollContext) -> String:
|
||||||
|
var card := ctx.declared(name)
|
||||||
|
if card == null:
|
||||||
|
ctx.erase("@" + name)
|
||||||
|
return ""
|
||||||
|
var r := card.initial_value(ctx)
|
||||||
|
ctx.save("@" + name, r["value"], card.id)
|
||||||
|
return str(r["error"])
|
||||||
|
|
||||||
|
|
||||||
|
static func _shown(v: Variant) -> String:
|
||||||
|
var s := Expr.format_value(v)
|
||||||
|
return s if s != "" else "(none)"
|
||||||
|
|
||||||
|
|
||||||
|
static func _signed(v: Variant) -> String:
|
||||||
|
var s := Expr.format_value(v)
|
||||||
|
return s if s.begins_with("-") else "+" + s
|
||||||
|
|
||||||
|
|
||||||
|
static func _compile() -> void:
|
||||||
|
if _stmt_re == null:
|
||||||
|
_stmt_re = RegEx.create_from_string("^(@?[A-Za-z_][A-Za-z0-9_]*)\\s*(\\+=|-=|\\*=|/=|=)(?!=)\\s*(.*)$")
|
||||||
|
_reset_re = RegEx.create_from_string("^(?i:reset)\\s+@([A-Za-z_][A-Za-z0-9_]*|)(\\*?)\\s*$")
|
||||||
1
core/effects.gd.uid
Normal file
1
core/effects.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
uid://doevsgi5ip72d
|
||||||
397
core/expr.gd
Normal file
397
core/expr.gd
Normal file
|
|
@ -0,0 +1,397 @@
|
||||||
|
class_name Expr
|
||||||
|
extends RefCounted
|
||||||
|
## Expressions for logic cards (docs/LOGIC.md §4), evaluated with Godot's
|
||||||
|
## Expression after a small rewrite:
|
||||||
|
## @name a board variable (unset reads as 0, or "" next to text)
|
||||||
|
## name a chain variable (answer, i, or anything saved with -> name)
|
||||||
|
## 2d6 d20 3D D3 dice, rolled fresh every time (a missing count is 1, missing
|
||||||
|
## sides are 6)
|
||||||
|
## a = b a lone "=" means equals
|
||||||
|
## dm(x) has(list, item) count(prefix), plus Expression's built-ins
|
||||||
|
## (min max clamp abs floor ceil round ...)
|
||||||
|
##
|
||||||
|
## Errors never crash: evaluate() returns {"value", "error"} and the error text
|
||||||
|
## is "" on success. Parsed expressions are cached by source text.
|
||||||
|
|
||||||
|
## Most dice one token may roll (a typo like 1000d6 is refused, not hung on).
|
||||||
|
const MAX_DICE := 100
|
||||||
|
const MAX_SIDES := 1000
|
||||||
|
|
||||||
|
const _KEYWORDS := ["and", "or", "not", "in", "true", "false", "null", "if", "else",
|
||||||
|
"PI", "TAU", "INF", "NAN", "self"]
|
||||||
|
|
||||||
|
## source text -> {expr: Expression or null, inputs: Array[String] (input
|
||||||
|
## names in order), vars: Array of [kind, name] per input ("@" board, "" chain),
|
||||||
|
## text_side: Array[bool] per input (an unset value reads as ""), error: String}
|
||||||
|
static var _cache: Dictionary = {}
|
||||||
|
static var _dice_re: RegEx = null
|
||||||
|
|
||||||
|
|
||||||
|
## Evaluates `src` against a roll context. `ctx` may be null (variables then
|
||||||
|
## read as unset and dice use a fresh RNG). Returns {"value": Variant,
|
||||||
|
## "error": String}; whole floats come back as ints.
|
||||||
|
static func evaluate(src: String, ctx: RollContext) -> Dictionary:
|
||||||
|
var p := _parsed(src)
|
||||||
|
if p["error"] != "":
|
||||||
|
return {"value": null, "error": p["error"]}
|
||||||
|
var inputs: Array = p["inputs"]
|
||||||
|
var kinds: Array = p["vars"]
|
||||||
|
var text_side: Array = p["text_side"]
|
||||||
|
var values: Array = []
|
||||||
|
var unset: Array[int] = []
|
||||||
|
for k in inputs.size():
|
||||||
|
var pair: Array = kinds[k]
|
||||||
|
var v: Variant = null
|
||||||
|
if ctx != null:
|
||||||
|
v = ctx.get_value(("@" if pair[0] == "@" else "") + str(pair[1]))
|
||||||
|
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()
|
||||||
|
base.ctx = ctx
|
||||||
|
var e: Expression = p["expr"]
|
||||||
|
var out: Variant = e.execute(values, base, false)
|
||||||
|
if e.has_execute_failed() and not unset.is_empty():
|
||||||
|
# An unset variable next to text: try again with "" for the unset ones.
|
||||||
|
var again := values.duplicate()
|
||||||
|
for k in unset:
|
||||||
|
again[k] = ""
|
||||||
|
var out2: Variant = e.execute(again, base, false)
|
||||||
|
if not e.has_execute_failed():
|
||||||
|
return {"value": normalize(out2), "error": ""}
|
||||||
|
if e.has_execute_failed():
|
||||||
|
var msg := e.get_error_text()
|
||||||
|
return {"value": null, "error": msg if msg != "" else "Can't work out %s" % src}
|
||||||
|
if base.error != "":
|
||||||
|
return {"value": null, "error": base.error}
|
||||||
|
return {"value": normalize(out), "error": ""}
|
||||||
|
|
||||||
|
|
||||||
|
## The value as an int: numbers are floored, true/false are 1/0, numeric text
|
||||||
|
## is parsed. `fallback` when it can't be a number or has an error.
|
||||||
|
static func as_int(r: Dictionary, fallback: int = 0) -> int:
|
||||||
|
if str(r.get("error", "")) != "":
|
||||||
|
return fallback
|
||||||
|
var v: Variant = to_value(r.get("value"))
|
||||||
|
if v is bool:
|
||||||
|
return 1 if v else 0
|
||||||
|
if v is int:
|
||||||
|
return v
|
||||||
|
if v is float:
|
||||||
|
return floori(v)
|
||||||
|
return fallback
|
||||||
|
|
||||||
|
|
||||||
|
## Evaluates and converts in one step (see as_int).
|
||||||
|
static func eval_int(src: String, ctx: RollContext, fallback: int = 0) -> int:
|
||||||
|
return as_int(evaluate(src, ctx), fallback)
|
||||||
|
|
||||||
|
|
||||||
|
## Truthiness for loop and pipe conditions: false, 0, "" and null are false.
|
||||||
|
static func truthy(v: Variant) -> bool:
|
||||||
|
v = to_value(v)
|
||||||
|
if v == null:
|
||||||
|
return false
|
||||||
|
if v is bool:
|
||||||
|
return v
|
||||||
|
if v is int or v is float:
|
||||||
|
return v != 0
|
||||||
|
if v is String:
|
||||||
|
return v != ""
|
||||||
|
return true
|
||||||
|
|
||||||
|
|
||||||
|
## Checks that `src` parses, without running it. "" when it's fine.
|
||||||
|
static func check(src: String) -> String:
|
||||||
|
return str(_parsed(src)["error"])
|
||||||
|
|
||||||
|
|
||||||
|
## Number-like text becomes a number ("12" -> 12, "2.5" -> 2.5); whole floats
|
||||||
|
## become ints; anything else is unchanged.
|
||||||
|
static func to_value(v: Variant) -> Variant:
|
||||||
|
if v is String:
|
||||||
|
var s := (v as String).strip_edges()
|
||||||
|
if s.is_valid_int():
|
||||||
|
return s.to_int()
|
||||||
|
if s.is_valid_float() and not s.to_lower().contains("n"):
|
||||||
|
return normalize(s.to_float())
|
||||||
|
return v
|
||||||
|
return normalize(v)
|
||||||
|
|
||||||
|
|
||||||
|
## Whole floats (as JSON gives back) become ints.
|
||||||
|
static func normalize(v: Variant) -> Variant:
|
||||||
|
if v is float and is_finite(v) and is_equal_approx(v, roundf(v)) and absf(v) < 1e15:
|
||||||
|
return int(roundf(v))
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
static func is_number(v: Variant) -> bool:
|
||||||
|
v = to_value(v)
|
||||||
|
return v is int or v is float
|
||||||
|
|
||||||
|
|
||||||
|
## A value for display: 9, 2.5, "Aslan"; no ".0" on whole numbers.
|
||||||
|
static func format_value(v: Variant) -> String:
|
||||||
|
if v == null:
|
||||||
|
return ""
|
||||||
|
if v is bool:
|
||||||
|
return "yes" if v else "no"
|
||||||
|
v = normalize(v)
|
||||||
|
if v is int:
|
||||||
|
return str(v)
|
||||||
|
if v is float:
|
||||||
|
var s := "%.4f" % v
|
||||||
|
s = s.rstrip("0").rstrip(".")
|
||||||
|
return s
|
||||||
|
return str(v)
|
||||||
|
|
||||||
|
|
||||||
|
## The 2D-game characteristic modifier.
|
||||||
|
static func dm(x: Variant) -> int:
|
||||||
|
var n := 0
|
||||||
|
var v: Variant = to_value(x)
|
||||||
|
if v is int:
|
||||||
|
n = v
|
||||||
|
elif v is float:
|
||||||
|
n = floori(v)
|
||||||
|
if n <= 0:
|
||||||
|
return -3
|
||||||
|
if n <= 2:
|
||||||
|
return -2
|
||||||
|
if n <= 5:
|
||||||
|
return -1
|
||||||
|
if n <= 8:
|
||||||
|
return 0
|
||||||
|
if n <= 11:
|
||||||
|
return 1
|
||||||
|
if n <= 14:
|
||||||
|
return 2
|
||||||
|
return 3
|
||||||
|
|
||||||
|
|
||||||
|
## Items of a comma-separated list (trimmed, empty ones dropped).
|
||||||
|
static func list_items(list: Variant) -> Array[String]:
|
||||||
|
var out: Array[String] = []
|
||||||
|
if list is Array:
|
||||||
|
for x: Variant in list:
|
||||||
|
var s := format_value(x).strip_edges()
|
||||||
|
if s != "":
|
||||||
|
out.append(s)
|
||||||
|
return out
|
||||||
|
for part in format_value(list).split(","):
|
||||||
|
var s := part.strip_edges()
|
||||||
|
if s != "":
|
||||||
|
out.append(s)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
## Whether a comma-separated list contains an item (case-insensitive).
|
||||||
|
static func has_item(list: Variant, item: Variant) -> bool:
|
||||||
|
var want := format_value(item).strip_edges().to_lower()
|
||||||
|
for s in list_items(list):
|
||||||
|
if s.to_lower() == want:
|
||||||
|
return true
|
||||||
|
return false
|
||||||
|
|
||||||
|
|
||||||
|
## Rolls NdM with `rng` (a fresh one when null).
|
||||||
|
static func roll_dice(n: int, sides: int, rng: RandomNumberGenerator) -> int:
|
||||||
|
if rng == null:
|
||||||
|
rng = RandomNumberGenerator.new()
|
||||||
|
var total := 0
|
||||||
|
for k in n:
|
||||||
|
total += rng.randi_range(1, sides)
|
||||||
|
return total
|
||||||
|
|
||||||
|
|
||||||
|
## The rewritten source (for tests and debugging).
|
||||||
|
static func rewrite(src: String) -> String:
|
||||||
|
return str(_rewrite(src)["text"])
|
||||||
|
|
||||||
|
|
||||||
|
static func _parsed(src: String) -> Dictionary:
|
||||||
|
if _cache.has(src):
|
||||||
|
return _cache[src]
|
||||||
|
var p := {"expr": null, "inputs": [], "vars": [], "text_side": [], "error": ""}
|
||||||
|
if src.strip_edges() == "":
|
||||||
|
p["error"] = "Empty expression"
|
||||||
|
else:
|
||||||
|
var rw := _rewrite(src)
|
||||||
|
if rw["error"] != "":
|
||||||
|
p["error"] = rw["error"]
|
||||||
|
else:
|
||||||
|
var e := Expression.new()
|
||||||
|
var names: Array = rw["inputs"]
|
||||||
|
var err := e.parse(rw["text"], PackedStringArray(names))
|
||||||
|
if err != OK:
|
||||||
|
p["error"] = e.get_error_text() if e.get_error_text() != "" else "Can't read %s" % src
|
||||||
|
else:
|
||||||
|
p["expr"] = e
|
||||||
|
p["inputs"] = names
|
||||||
|
p["vars"] = rw["vars"]
|
||||||
|
p["text_side"] = rw["text_side"]
|
||||||
|
if _cache.size() > 4000:
|
||||||
|
_cache.clear()
|
||||||
|
_cache[src] = p
|
||||||
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
## Rewrites the user's syntax into Godot Expression syntax. Returns {text,
|
||||||
|
## inputs, vars, text_side, error}.
|
||||||
|
static func _rewrite(src: String) -> Dictionary:
|
||||||
|
var out := ""
|
||||||
|
var inputs: Array = []
|
||||||
|
var vars: Array = []
|
||||||
|
var text_side: Array = []
|
||||||
|
var slot := {} # "@name" / "name" -> input index
|
||||||
|
# Tokens as [kind, text]: kind "str", "var", "op", "other" (for text_side).
|
||||||
|
var toks: Array = []
|
||||||
|
var i := 0
|
||||||
|
var n := src.length()
|
||||||
|
while i < n:
|
||||||
|
var c := src[i]
|
||||||
|
if c == "\"" or c == "'":
|
||||||
|
var j := i + 1
|
||||||
|
while j < n and src[j] != c:
|
||||||
|
if src[j] == "\\":
|
||||||
|
j += 1
|
||||||
|
j += 1
|
||||||
|
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])
|
||||||
|
i = j + 1
|
||||||
|
continue
|
||||||
|
if c == "@":
|
||||||
|
var j := i + 1
|
||||||
|
while j < n and _is_word(src[j]):
|
||||||
|
j += 1
|
||||||
|
var name := src.substr(i + 1, j - i - 1).to_lower()
|
||||||
|
if name == "" or not _is_word_start(name[0]):
|
||||||
|
return {"text": "", "inputs": [], "vars": [], "text_side": [], "error": "\"@\" must be followed by a variable name"}
|
||||||
|
if j < n and src[j] == "*":
|
||||||
|
# @prefix_* as an argument, e.g. count(@skill_*): the prefix as text.
|
||||||
|
var lit := "\"%s\"" % name
|
||||||
|
out += lit
|
||||||
|
toks.append(["str", lit])
|
||||||
|
i = j + 1
|
||||||
|
continue
|
||||||
|
var key := "@" + name
|
||||||
|
if not slot.has(key):
|
||||||
|
slot[key] = inputs.size()
|
||||||
|
inputs.append("_v%d" % inputs.size())
|
||||||
|
vars.append(["@", name])
|
||||||
|
text_side.append(false)
|
||||||
|
out += inputs[slot[key]]
|
||||||
|
toks.append(["var", slot[key]])
|
||||||
|
i = j
|
||||||
|
continue
|
||||||
|
if _is_word(c):
|
||||||
|
var j := i
|
||||||
|
while j < n and (_is_word(src[j]) or (src[j] == "." and j + 1 < n and src[j + 1].is_valid_int() and src.substr(i, j - i).is_valid_int())):
|
||||||
|
j += 1
|
||||||
|
var word := src.substr(i, j - i)
|
||||||
|
var dice := _dice_of(word)
|
||||||
|
if not dice.is_empty():
|
||||||
|
if dice[0] < 1 or dice[0] > MAX_DICE or dice[1] < 1 or dice[1] > MAX_SIDES:
|
||||||
|
return {"text": "", "inputs": [], "vars": [], "text_side": [], "error": "%s isn't a dice roll this can make" % word}
|
||||||
|
out += "_d(%d, %d)" % [dice[0], dice[1]]
|
||||||
|
toks.append(["other", word])
|
||||||
|
elif word[0].is_valid_int():
|
||||||
|
out += word
|
||||||
|
toks.append(["other", word])
|
||||||
|
else:
|
||||||
|
# A function call, a keyword or a chain variable.
|
||||||
|
var k := j
|
||||||
|
while k < n and src[k] == " ":
|
||||||
|
k += 1
|
||||||
|
var is_call := k < n and src[k] == "("
|
||||||
|
if is_call or _KEYWORDS.has(word):
|
||||||
|
out += word
|
||||||
|
toks.append(["op" if word == "in" else "other", word])
|
||||||
|
else:
|
||||||
|
if not slot.has(word):
|
||||||
|
slot[word] = inputs.size()
|
||||||
|
inputs.append("_v%d" % inputs.size())
|
||||||
|
vars.append(["", word])
|
||||||
|
text_side.append(false)
|
||||||
|
out += inputs[slot[word]]
|
||||||
|
toks.append(["var", slot[word]])
|
||||||
|
i = j
|
||||||
|
continue
|
||||||
|
if c == "=":
|
||||||
|
var prev := src[i - 1] if i > 0 else ""
|
||||||
|
var next := src[i + 1] if i + 1 < n else ""
|
||||||
|
if next == "=":
|
||||||
|
out += "=="
|
||||||
|
toks.append(["op", "=="])
|
||||||
|
i += 2
|
||||||
|
continue
|
||||||
|
if prev != "=" and prev != "!" and prev != "<" and prev != ">":
|
||||||
|
out += "=="
|
||||||
|
toks.append(["op", "=="])
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
if c != " " and c != "\t" and c != "\n":
|
||||||
|
toks.append(["op", c])
|
||||||
|
out += c
|
||||||
|
i += 1
|
||||||
|
# A variable directly beside a text literal (or `in`) reads as "" when unset.
|
||||||
|
for t in toks.size():
|
||||||
|
if toks[t][0] != "var":
|
||||||
|
continue
|
||||||
|
for d in [-2, -1, 1, 2]:
|
||||||
|
var u: int = t + d
|
||||||
|
if u < 0 or u >= toks.size():
|
||||||
|
continue
|
||||||
|
if toks[u][0] == "str" or (toks[u][0] == "op" and toks[u][1] == "in"):
|
||||||
|
text_side[toks[t][1]] = true
|
||||||
|
return {"text": out, "inputs": inputs, "vars": vars, "text_side": text_side, "error": ""}
|
||||||
|
|
||||||
|
|
||||||
|
## [count, sides] for a dice word ("2d6", "d20", "3D", "D3", "2D"), or [].
|
||||||
|
static func _dice_of(word: String) -> Array:
|
||||||
|
if _dice_re == null:
|
||||||
|
_dice_re = RegEx.create_from_string("^(\\d*)[dD](\\d*)$")
|
||||||
|
var m := _dice_re.search(word)
|
||||||
|
if m == null:
|
||||||
|
return []
|
||||||
|
var a := m.get_string(1)
|
||||||
|
var b := m.get_string(2)
|
||||||
|
if a == "" and b == "":
|
||||||
|
return []
|
||||||
|
return [int(a) if a != "" else 1, int(b) if b != "" else 6]
|
||||||
|
|
||||||
|
|
||||||
|
static func _is_word(c: String) -> bool:
|
||||||
|
return c == "_" or c.is_valid_int() or (c.to_lower() != c.to_upper())
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
return Expr.roll_dice(n, sides, ctx.rng if ctx != null else null)
|
||||||
|
|
||||||
|
func dm(x: Variant) -> int:
|
||||||
|
return Expr.dm(x)
|
||||||
|
|
||||||
|
func has(list: Variant, item: Variant) -> bool:
|
||||||
|
return Expr.has_item(list, item)
|
||||||
|
|
||||||
|
func count(prefix: Variant) -> int:
|
||||||
|
if ctx == null:
|
||||||
|
return 0
|
||||||
|
return ctx.count_vars(str(prefix))
|
||||||
1
core/expr.gd.uid
Normal file
1
core/expr.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
uid://2r7dds243gsc
|
||||||
|
|
@ -36,7 +36,7 @@ const IMPORT_ALLOWED_TAGS: Array[String] = [
|
||||||
]
|
]
|
||||||
|
|
||||||
## url parameters with these prefixes are TextExpander's internal markers.
|
## url parameters with these prefixes are TextExpander's internal markers.
|
||||||
const INTERNAL_META_PREFIXES: Array[String] = ["table:", "var:", "missing:", "unset:", "deep:"]
|
const INTERNAL_META_PREFIXES: Array[String] = ["table:", "var:", "missing:", "unset:", "deep:", "error:"]
|
||||||
|
|
||||||
## Matches one tag: [name], [/name], [name=param] or [name key=value ...].
|
## Matches one tag: [name], [/name], [name=param] or [name key=value ...].
|
||||||
## Parameters may contain quoted strings, so [url={"a":1}] is one tag.
|
## Parameters may contain quoted strings, so [url={"a":1}] is one tag.
|
||||||
|
|
|
||||||
|
|
@ -25,13 +25,22 @@ extends RefCounted
|
||||||
## - When the roller itself stops (depth limit, empty table), it still returns a
|
## - When the roller itself stops (depth limit, empty table), it still returns a
|
||||||
## node whose summary explains why, for example [method TextExpander.deep_marker].
|
## node whose summary explains why, for example [method TextExpander.deep_marker].
|
||||||
## - roll_table may change [member depth] while it runs; TextExpander restores it.
|
## - roll_table may change [member depth] while it runs; TextExpander restores it.
|
||||||
|
##
|
||||||
|
## [b]Logic cards[/b] (docs/LOGIC.md): the context also carries the prompt hook
|
||||||
|
## for choice cards, the action counter and limit, the tree built so far
|
||||||
|
## ([member root]) and the board, for variable cards and display names.
|
||||||
|
## Variable values are Variants: int, float or String.
|
||||||
|
|
||||||
const DEFAULT_MAX_DEPTH := 32
|
const DEFAULT_MAX_DEPTH := 32
|
||||||
|
## Most actions (a table rolled or answered, or one loop pass) one top-level
|
||||||
|
## roll may take.
|
||||||
|
const DEFAULT_MAX_ACTIONS := 10000
|
||||||
|
|
||||||
## Chain variables: name (no "@") -> String value. Fresh for every top-level roll.
|
## Chain variables: name (no "@") -> value (String, int or float). Fresh for
|
||||||
|
## every top-level roll. The roller sets "answer" and "i".
|
||||||
var chain_vars: Dictionary = {}
|
var chain_vars: Dictionary = {}
|
||||||
## The collection's persistent variables, owned and saved elsewhere:
|
## The collection's persistent variables, owned and saved elsewhere:
|
||||||
## name (without the "@") -> {"value": String, "source": table_id}.
|
## name (without the "@") -> {"value": Variant, "source": table_id}.
|
||||||
## This is the caller's Dictionary itself, not a copy, so saves show up there.
|
## This is the caller's Dictionary itself, not a copy, so saves show up there.
|
||||||
var persistent_vars: Dictionary = {}
|
var persistent_vars: Dictionary = {}
|
||||||
## True once save() has written a persistent variable in this roll, so the caller
|
## True once save() has written a persistent variable in this roll, so the caller
|
||||||
|
|
@ -47,6 +56,32 @@ var rng: RandomNumberGenerator = null
|
||||||
var resolve_table: Callable = Callable()
|
var resolve_table: Callable = Callable()
|
||||||
## func(table_id: String, depth: int) -> Dictionary (a result node).
|
## func(table_id: String, depth: int) -> Dictionary (a result node).
|
||||||
var roll_table: Callable = Callable()
|
var roll_table: Callable = Callable()
|
||||||
|
## Coroutine form of roll_table, used by TextExpander.expand_async so that a
|
||||||
|
## reference into a choice card can prompt.
|
||||||
|
## func(table_id: String, depth: int) -> Dictionary
|
||||||
|
var roll_table_async: Callable = Callable()
|
||||||
|
## The board being rolled (variable cards, display names). May be null.
|
||||||
|
var board: TowerBoard = null
|
||||||
|
## Choice-card hook: func(request: Dictionary) -> Variant, awaited by the
|
||||||
|
## roller. Not set (the default) means the headless answers: Random for a pick,
|
||||||
|
## min for a number, "" for text. See docs/LOGIC.md §8 and Roller.ask().
|
||||||
|
var prompt: Callable = Callable()
|
||||||
|
## Actions taken so far in this top-level roll, and the limit.
|
||||||
|
var actions: int = 0
|
||||||
|
var max_actions: int = DEFAULT_MAX_ACTIONS
|
||||||
|
## Why the roll stopped early, "" while it runs normally: the action-limit
|
||||||
|
## message or "Cancelled". Once set, the roller unwinds and keeps what it has.
|
||||||
|
var halted: String = ""
|
||||||
|
## The result tree of the current top-level roll, filled in while it runs, so
|
||||||
|
## a UI can show the steps so far while a prompt is open (Roller.progress()).
|
||||||
|
var root: Dictionary = {}
|
||||||
|
## Nesting of running roller chains (internal to Roller).
|
||||||
|
var running: int = 0
|
||||||
|
## While true the roller never awaits the prompt hook (sync Roller.roll()).
|
||||||
|
var no_prompt: bool = false
|
||||||
|
|
||||||
|
var _decl: Dictionary = {}
|
||||||
|
var _decl_built := false
|
||||||
|
|
||||||
|
|
||||||
func _init(p_persistent: Dictionary = {}, p_rng: RandomNumberGenerator = null) -> void:
|
func _init(p_persistent: Dictionary = {}, p_rng: RandomNumberGenerator = null) -> void:
|
||||||
|
|
@ -61,8 +96,10 @@ static func is_persistent(name: String) -> bool:
|
||||||
|
|
||||||
## Saves a value. Names starting with "@" go to the persistent variables
|
## Saves a value. Names starting with "@" go to the persistent variables
|
||||||
## (stored without the "@", with the source table id); others to the chain.
|
## (stored without the "@", with the source table id); others to the chain.
|
||||||
func save(name: String, value: String, source_id: String = "") -> void:
|
## Whole floats are stored as ints.
|
||||||
|
func save(name: String, value: Variant, source_id: String = "") -> void:
|
||||||
var n: String = name.strip_edges()
|
var n: String = name.strip_edges()
|
||||||
|
value = Expr.normalize(value)
|
||||||
if n.begins_with("@"):
|
if n.begins_with("@"):
|
||||||
n = n.substr(1)
|
n = n.substr(1)
|
||||||
if n == "":
|
if n == "":
|
||||||
|
|
@ -73,22 +110,131 @@ func save(name: String, value: String, source_id: String = "") -> void:
|
||||||
chain_vars[n] = value
|
chain_vars[n] = value
|
||||||
|
|
||||||
|
|
||||||
## Returns the saved String value, or null when the variable isn't set.
|
## Returns the saved value as display text (numbers without ".0"), or null
|
||||||
## "@name" reads a persistent variable, "name" a chain variable.
|
## when the variable isn't set. "@name" reads a persistent variable, "name" a
|
||||||
|
## chain variable.
|
||||||
func lookup(name: String) -> Variant:
|
func lookup(name: String) -> Variant:
|
||||||
|
var v: Variant = get_value(name)
|
||||||
|
return null if v == null else Expr.format_value(v)
|
||||||
|
|
||||||
|
|
||||||
|
## The saved value itself (int, float or String), or null when it isn't set.
|
||||||
|
func get_value(name: String) -> Variant:
|
||||||
var n: String = name.strip_edges()
|
var n: String = name.strip_edges()
|
||||||
if n.begins_with("@"):
|
if n.begins_with("@"):
|
||||||
var entry: Variant = persistent_vars.get(n.substr(1))
|
var entry: Variant = persistent_vars.get(n.substr(1))
|
||||||
if entry is Dictionary:
|
if entry is Dictionary:
|
||||||
return str((entry as Dictionary).get("value", ""))
|
return Expr.normalize((entry as Dictionary).get("value", ""))
|
||||||
if entry != null:
|
return Expr.normalize(entry)
|
||||||
return str(entry)
|
|
||||||
return null
|
|
||||||
if chain_vars.has(n):
|
if chain_vars.has(n):
|
||||||
return str(chain_vars[n])
|
return Expr.normalize(chain_vars[n])
|
||||||
return null
|
return null
|
||||||
|
|
||||||
|
|
||||||
|
## Forgets a variable ("@name" or a chain variable name).
|
||||||
|
func erase(name: String) -> void:
|
||||||
|
var n: String = name.strip_edges()
|
||||||
|
if n.begins_with("@"):
|
||||||
|
if persistent_vars.erase(n.substr(1)):
|
||||||
|
persistent_changed = true
|
||||||
|
else:
|
||||||
|
chain_vars.erase(n)
|
||||||
|
|
||||||
|
|
||||||
|
## How many board variables are set whose names start with `prefix` (a leading
|
||||||
|
## "@" and a trailing "*" are ignored).
|
||||||
|
func count_vars(prefix: String) -> int:
|
||||||
|
var p := _prefix(prefix)
|
||||||
|
var k := 0
|
||||||
|
for name: String in persistent_vars:
|
||||||
|
if name.begins_with(p):
|
||||||
|
k += 1
|
||||||
|
return k
|
||||||
|
|
||||||
|
|
||||||
|
## Board variables whose names start with `prefix`, sorted by label: Array of
|
||||||
|
## {name (no "@"), label (the part after the prefix, title-cased, "_" read as a
|
||||||
|
## space), value}.
|
||||||
|
func list_vars(prefix: String) -> Array[Dictionary]:
|
||||||
|
return RollContext.vars_with_prefix(persistent_vars, prefix)
|
||||||
|
|
||||||
|
|
||||||
|
## list_vars() for a plain variables Dictionary (name -> {value, source}), for
|
||||||
|
## UI code without a roll context.
|
||||||
|
static func vars_with_prefix(vars: Dictionary, prefix: String) -> Array[Dictionary]:
|
||||||
|
var p := _prefix(prefix)
|
||||||
|
var out: Array[Dictionary] = []
|
||||||
|
for name: String in vars:
|
||||||
|
if not name.begins_with(p):
|
||||||
|
continue
|
||||||
|
var rest := name.substr(p.length())
|
||||||
|
var raw: Variant = vars[name]
|
||||||
|
var value: Variant = (raw as Dictionary).get("value", "") if raw is Dictionary else raw
|
||||||
|
out.append({"name": name, "label": pretty_name(rest if rest != "" else name),
|
||||||
|
"value": Expr.normalize(value)})
|
||||||
|
out.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
|
||||||
|
return str(a["label"]).naturalnocasecmp_to(str(b["label"])) < 0)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
## The {@prefix_*} text: "Gun Combat 1, Pilot 0".
|
||||||
|
func list_text(prefix: String) -> String:
|
||||||
|
var parts := PackedStringArray()
|
||||||
|
for v in list_vars(prefix):
|
||||||
|
var shown := Expr.format_value(v["value"])
|
||||||
|
parts.append(str(v["label"]) if shown == "" else "%s %s" % [v["label"], shown])
|
||||||
|
return ", ".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
## "gun_combat" -> "Gun Combat".
|
||||||
|
static func pretty_name(name: String) -> String:
|
||||||
|
var words := PackedStringArray()
|
||||||
|
for w in name.replace("_", " ").strip_edges().split(" ", false):
|
||||||
|
words.append(w.substr(0, 1).to_upper() + w.substr(1))
|
||||||
|
return " ".join(words)
|
||||||
|
|
||||||
|
|
||||||
|
## Display name of a board variable for effect logs: the variable card's name
|
||||||
|
## when a card declares it, else the name title-cased ("skill_pilot" ->
|
||||||
|
## "Skill Pilot"). `name` may start with "@".
|
||||||
|
func display_name(name: String) -> String:
|
||||||
|
var n := name.strip_edges().trim_prefix("@")
|
||||||
|
var card := declared(n)
|
||||||
|
if card != null and Formatter.strip_tags(card.name).strip_edges() != "":
|
||||||
|
return Formatter.strip_tags(card.name).strip_edges()
|
||||||
|
return pretty_name(n)
|
||||||
|
|
||||||
|
|
||||||
|
## The variable card that declares board variable `name` (no "@"), or null.
|
||||||
|
func declared(name: String) -> RollTable:
|
||||||
|
if not _decl_built:
|
||||||
|
_decl_built = true
|
||||||
|
_decl.clear()
|
||||||
|
if board != null:
|
||||||
|
for t in board.tables:
|
||||||
|
if t.kind == RollTable.KIND_VARIABLE and t.var_name != "" and not _decl.has(t.var_name):
|
||||||
|
_decl[t.var_name] = t
|
||||||
|
return _decl.get(name.strip_edges().trim_prefix("@"))
|
||||||
|
|
||||||
|
|
||||||
|
## Every declared variable name (no "@").
|
||||||
|
func declared_names() -> Array[String]:
|
||||||
|
declared("")
|
||||||
|
var out: Array[String] = []
|
||||||
|
for k: String in _decl:
|
||||||
|
out.append(k)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
## Call after the board's variable cards change.
|
||||||
|
func forget_declarations() -> void:
|
||||||
|
_decl_built = false
|
||||||
|
|
||||||
|
|
||||||
|
static func _prefix(prefix: String) -> String:
|
||||||
|
return prefix.strip_edges().trim_prefix("@").trim_suffix("*")
|
||||||
|
|
||||||
|
|
||||||
## Calls resolve_table, returning "" if the hook isn't set.
|
## Calls resolve_table, returning "" if the hook isn't set.
|
||||||
func resolve(name_or_id: String) -> String:
|
func resolve(name_or_id: String) -> String:
|
||||||
if not resolve_table.is_valid():
|
if not resolve_table.is_valid():
|
||||||
|
|
@ -108,6 +254,17 @@ func roll(table_id: String) -> Dictionary:
|
||||||
return result as Dictionary if result is Dictionary else {}
|
return result as Dictionary if result is Dictionary else {}
|
||||||
|
|
||||||
|
|
||||||
|
## Coroutine form of roll(): uses roll_table_async when it's set, else
|
||||||
|
## roll_table. Restores depth afterwards.
|
||||||
|
func roll_async(table_id: String) -> Dictionary:
|
||||||
|
if not roll_table_async.is_valid():
|
||||||
|
return roll(table_id)
|
||||||
|
var d: int = depth
|
||||||
|
var result: Variant = await roll_table_async.call(table_id, d)
|
||||||
|
depth = d
|
||||||
|
return result as Dictionary if result is Dictionary else {}
|
||||||
|
|
||||||
|
|
||||||
## Lowercase, trimmed, BBCode-free form of a table name, for matching
|
## Lowercase, trimmed, BBCode-free form of a table name, for matching
|
||||||
## [[references]] against names: normalize_name("[b]Gems[/b] ") == "gems".
|
## [[references]] against names: normalize_name("[b]Gems[/b] ") == "gems".
|
||||||
static func normalize_name(name: String) -> String:
|
static func normalize_name(name: String) -> String:
|
||||||
|
|
|
||||||
|
|
@ -5,9 +5,28 @@ extends RefCounted
|
||||||
## Plain tables pick by entry weight (6 equal entries = d6). If any entry has a
|
## Plain tables pick by entry weight (6 equal entries = d6). If any entry has a
|
||||||
## range, the table becomes a ranged dice table (1d100 by default, or any dice
|
## range, the table becomes a ranged dice table (1d100 by default, or any dice
|
||||||
## expression) where the probability mass of each range sets its chance.
|
## expression) where the probability mass of each range sets its chance.
|
||||||
|
##
|
||||||
|
## Every table has a `kind` (docs/LOGIC.md §1): "roll" (the default), "choice",
|
||||||
|
## "loop", "variable" or "sheet", with the per-kind fields below. Use create()
|
||||||
|
## for a well-formed card of each kind.
|
||||||
|
##
|
||||||
|
## Ranged tables also accept a full expression in `dice` ("2d6 + dm(@end)",
|
||||||
|
## "@terms"). Anything that isn't plain dice is evaluated with Expr; values
|
||||||
|
## past the lowest or highest range clamp to that range, and chances aren't
|
||||||
|
## known (chance() is 0, has_chances() false).
|
||||||
|
|
||||||
const DEFAULT_DICE := "1d100"
|
const DEFAULT_DICE := "1d100"
|
||||||
|
|
||||||
|
const KIND_ROLL := "roll"
|
||||||
|
const KIND_CHOICE := "choice"
|
||||||
|
const KIND_LOOP := "loop"
|
||||||
|
const KIND_VARIABLE := "variable"
|
||||||
|
const KIND_SHEET := "sheet"
|
||||||
|
const KINDS: Array[String] = [KIND_ROLL, KIND_CHOICE, KIND_LOOP, KIND_VARIABLE, KIND_SHEET]
|
||||||
|
const CHOICES: Array[String] = ["pick", "number", "text"]
|
||||||
|
const LOOPS: Array[String] = ["times", "while", "until"]
|
||||||
|
const VAR_TYPES: Array[String] = ["number", "text", "list"]
|
||||||
|
|
||||||
var id: String = ""
|
var id: String = ""
|
||||||
var name: String = ""
|
var name: String = ""
|
||||||
var position: Vector2 = Vector2.ZERO
|
var position: Vector2 = Vector2.ZERO
|
||||||
|
|
@ -15,7 +34,8 @@ var collapsed: bool = false
|
||||||
## Longer description (may contain BBCode).
|
## Longer description (may contain BBCode).
|
||||||
var details: String = ""
|
var details: String = ""
|
||||||
var tags: Array[String] = []
|
var tags: Array[String] = []
|
||||||
## Dice expression for ranged tables, e.g. "1d100", "2d6", "1d8+2".
|
## Dice expression for ranged tables, e.g. "1d100", "2d6", "1d8+2", or any
|
||||||
|
## expression such as "2d6 + dm(@end)".
|
||||||
var dice: String = DEFAULT_DICE
|
var dice: String = DEFAULT_DICE
|
||||||
## Card mode: entries are drawn without replacement until the deck is empty.
|
## Card mode: entries are drawn without replacement until the deck is empty.
|
||||||
var card_mode: bool = false
|
var card_mode: bool = false
|
||||||
|
|
@ -23,8 +43,29 @@ var card_mode: bool = false
|
||||||
var deck_empty: String = "reshuffle"
|
var deck_empty: String = "reshuffle"
|
||||||
var entries: Array[TableEntry] = []
|
var entries: Array[TableEntry] = []
|
||||||
|
|
||||||
|
## One of KINDS.
|
||||||
|
var kind: String = KIND_ROLL
|
||||||
|
## Choice cards: "pick", "number" or "text".
|
||||||
|
var choice: String = "pick"
|
||||||
|
## Choice cards: the question, BBCode with {@var} expansion.
|
||||||
|
var prompt: String = ""
|
||||||
|
## Choice cards: variable the answer is saved under ("@name" or a chain name).
|
||||||
|
var save_as: String = ""
|
||||||
|
## Number choices: bounds, as expressions.
|
||||||
|
var min_expr: String = "0"
|
||||||
|
var max_expr: String = "99"
|
||||||
|
## Loop cards: "times", "while" or "until", and the count or condition.
|
||||||
|
var loop_mode: String = "times"
|
||||||
|
var loop_expr: String = ""
|
||||||
|
## Variable cards: the variable's name (no "@"), its type and starting value
|
||||||
|
## (an expression).
|
||||||
|
var var_name: String = ""
|
||||||
|
var var_type: String = "number"
|
||||||
|
var initial: String = ""
|
||||||
|
|
||||||
var _dice_cache: Dice = null
|
var _dice_cache: Dice = null
|
||||||
var _dice_cache_text: String = ""
|
var _dice_cache_text: String = ""
|
||||||
|
var _dice_plain: bool = true
|
||||||
|
|
||||||
|
|
||||||
func _init(p_id: String = "", p_name: String = "") -> void:
|
func _init(p_id: String = "", p_name: String = "") -> void:
|
||||||
|
|
@ -32,6 +73,50 @@ func _init(p_id: String = "", p_name: String = "") -> void:
|
||||||
name = p_name
|
name = p_name
|
||||||
|
|
||||||
|
|
||||||
|
## A well-formed card of any kind. `sub` picks the variant: the choice
|
||||||
|
## ("pick", "number", "text"), the loop mode ("times", "while", "until") or
|
||||||
|
## the variable type ("number", "text", "list").
|
||||||
|
## roll: four "Result N" entries · choice pick: three options ·
|
||||||
|
## choice number/text: one "Answer" entry · loop: "Each time" and
|
||||||
|
## "Afterwards" · variable: no entries · sheet: one template entry.
|
||||||
|
static func create(p_kind: String, p_id: String, p_name: String, sub: String = "") -> RollTable:
|
||||||
|
var t := RollTable.new(p_id, p_name)
|
||||||
|
t.kind = p_kind if KINDS.has(p_kind) else KIND_ROLL
|
||||||
|
match t.kind:
|
||||||
|
KIND_ROLL:
|
||||||
|
for n in range(1, 5):
|
||||||
|
t.entries.append(TableEntry.new("e%d" % n, "Result %d" % n))
|
||||||
|
KIND_CHOICE:
|
||||||
|
t.choice = sub if CHOICES.has(sub) else "pick"
|
||||||
|
match t.choice:
|
||||||
|
"pick":
|
||||||
|
t.prompt = "Which one?"
|
||||||
|
for n in range(1, 4):
|
||||||
|
t.entries.append(TableEntry.new("e%d" % n, "Option %d" % n))
|
||||||
|
"number":
|
||||||
|
t.prompt = "How many?"
|
||||||
|
t.entries.append(TableEntry.new("e1", "Answer"))
|
||||||
|
"text":
|
||||||
|
t.prompt = "What is it?"
|
||||||
|
t.entries.append(TableEntry.new("e1", "Answer"))
|
||||||
|
KIND_LOOP:
|
||||||
|
t.loop_mode = sub if LOOPS.has(sub) else "times"
|
||||||
|
t.loop_expr = "3" if t.loop_mode == "times" else "i < 3"
|
||||||
|
t.entries.append(TableEntry.new("e1", "Each time"))
|
||||||
|
t.entries.append(TableEntry.new("e2", "Afterwards"))
|
||||||
|
KIND_VARIABLE:
|
||||||
|
t.var_type = sub if VAR_TYPES.has(sub) else "number"
|
||||||
|
t.var_name = JsonIO.slug(Formatter.strip_tags(p_name), "var") if p_name != "" else "var"
|
||||||
|
t.initial = "0" if t.var_type == "number" else ""
|
||||||
|
KIND_SHEET:
|
||||||
|
t.entries.append(TableEntry.new("e1", "[b]%s[/b]" % p_name))
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
|
func is_kind(k: String) -> bool:
|
||||||
|
return kind == k
|
||||||
|
|
||||||
|
|
||||||
func is_ranged() -> bool:
|
func is_ranged() -> bool:
|
||||||
for e in entries:
|
for e in entries:
|
||||||
if e.has_range:
|
if e.has_range:
|
||||||
|
|
@ -39,34 +124,79 @@ func is_ranged() -> bool:
|
||||||
return false
|
return false
|
||||||
|
|
||||||
|
|
||||||
## The parsed dice expression (falls back to 1d100 if `dice` is invalid).
|
## True when `dice` is a full expression rather than plain dice (ranged tables).
|
||||||
|
func is_expr_dice() -> bool:
|
||||||
|
dice_obj()
|
||||||
|
return is_ranged() and not _dice_plain
|
||||||
|
|
||||||
|
|
||||||
|
## The parsed dice expression (falls back to 1d100 if `dice` is invalid or an
|
||||||
|
## expression; see is_expr_dice()).
|
||||||
func dice_obj() -> Dice:
|
func dice_obj() -> Dice:
|
||||||
if _dice_cache == null or _dice_cache_text != dice:
|
if _dice_cache == null or _dice_cache_text != dice:
|
||||||
var d := Dice.parse(dice)
|
var d := Dice.parse(dice)
|
||||||
|
_dice_plain = d.valid or dice.strip_edges() == ""
|
||||||
_dice_cache = d if d.valid else Dice.make(1, 100)
|
_dice_cache = d if d.valid else Dice.make(1, 100)
|
||||||
_dice_cache_text = dice
|
_dice_cache_text = dice
|
||||||
return _dice_cache
|
return _dice_cache
|
||||||
|
|
||||||
|
|
||||||
## Label for the dice: "d100", "2d6", "1d8+2". Plain tables label by entry count.
|
## Rolls the ranged table's dice. Returns {"value": int, "error": String}.
|
||||||
|
func roll_value(ctx: RollContext) -> Dictionary:
|
||||||
|
if not is_expr_dice():
|
||||||
|
return {"value": dice_obj().roll(ctx.rng), "error": ""}
|
||||||
|
var r := Expr.evaluate(dice, ctx)
|
||||||
|
if r["error"] != "":
|
||||||
|
return {"value": 0, "error": r["error"]}
|
||||||
|
return {"value": Expr.as_int(r, 0), "error": ""}
|
||||||
|
|
||||||
|
|
||||||
|
## Label for the dice: "d100", "2d6", "1d8+2". Plain tables label by entry
|
||||||
|
## count; expression dice show the expression.
|
||||||
func dice_label() -> String:
|
func dice_label() -> String:
|
||||||
if is_ranged():
|
if is_ranged():
|
||||||
return dice_obj().label()
|
return dice.strip_edges() if is_expr_dice() else dice_obj().label()
|
||||||
return "d%d" % die_size()
|
return "d%d" % die_size()
|
||||||
|
|
||||||
|
|
||||||
## Lowest value that can be rolled (1 on plain tables).
|
## Lowest value that can be rolled (1 on plain tables). For expression dice,
|
||||||
|
## the lowest range start.
|
||||||
func min_value() -> int:
|
func min_value() -> int:
|
||||||
return dice_obj().min_value() if is_ranged() else 1
|
if not is_ranged():
|
||||||
|
return 1
|
||||||
|
if is_expr_dice():
|
||||||
|
return _range_span().x
|
||||||
|
return dice_obj().min_value()
|
||||||
|
|
||||||
|
|
||||||
## Highest value that can be rolled. Plain tables: the entry count.
|
## Highest value that can be rolled. Plain tables: the entry count. For
|
||||||
|
## expression dice, the highest range end.
|
||||||
func die_size() -> int:
|
func die_size() -> int:
|
||||||
if is_ranged():
|
if is_ranged():
|
||||||
|
if is_expr_dice():
|
||||||
|
return _range_span().y
|
||||||
return dice_obj().max_value()
|
return dice_obj().max_value()
|
||||||
return entries.size()
|
return entries.size()
|
||||||
|
|
||||||
|
|
||||||
|
## Vector2i(lowest range start, highest range end) over ranged entries.
|
||||||
|
func _range_span() -> Vector2i:
|
||||||
|
var lo := 0
|
||||||
|
var hi := 0
|
||||||
|
var first := true
|
||||||
|
for e in entries:
|
||||||
|
if not e.has_range:
|
||||||
|
continue
|
||||||
|
if first:
|
||||||
|
lo = e.range_lo
|
||||||
|
hi = e.range_hi
|
||||||
|
first = false
|
||||||
|
else:
|
||||||
|
lo = mini(lo, e.range_lo)
|
||||||
|
hi = maxi(hi, e.range_hi)
|
||||||
|
return Vector2i(lo, hi)
|
||||||
|
|
||||||
|
|
||||||
func total_weight() -> int:
|
func total_weight() -> int:
|
||||||
var w := 0
|
var w := 0
|
||||||
for e in entries:
|
for e in entries:
|
||||||
|
|
@ -77,7 +207,7 @@ func total_weight() -> int:
|
||||||
## Formats a die value the way printed tables do: d100 values are two digits
|
## Formats a die value the way printed tables do: d100 values are two digits
|
||||||
## and 100 is written "00".
|
## and 100 is written "00".
|
||||||
func fmt(value: int) -> String:
|
func fmt(value: int) -> String:
|
||||||
var two_digit := dice_obj().is_d100() if is_ranged() else entries.size() == 100
|
var two_digit := (dice_obj().is_d100() and not is_expr_dice()) if is_ranged() else entries.size() == 100
|
||||||
if two_digit:
|
if two_digit:
|
||||||
return "00" if value == 100 else "%02d" % value
|
return "00" if value == 100 else "%02d" % value
|
||||||
return str(value)
|
return str(value)
|
||||||
|
|
@ -86,21 +216,45 @@ func fmt(value: int) -> String:
|
||||||
func num_label(e: TableEntry, index: int) -> String:
|
func num_label(e: TableEntry, index: int) -> String:
|
||||||
if not e.has_range:
|
if not e.has_range:
|
||||||
return fmt(index + 1)
|
return fmt(index + 1)
|
||||||
|
if is_expr_dice():
|
||||||
|
var span := _range_span()
|
||||||
|
var ranged := 0
|
||||||
|
for x in entries:
|
||||||
|
if x.has_range:
|
||||||
|
ranged += 1
|
||||||
|
if ranged > 1:
|
||||||
|
if e.range_lo == span.x:
|
||||||
|
return "≤%s" % fmt(e.range_hi)
|
||||||
|
if e.range_hi == span.y:
|
||||||
|
return "%s+" % fmt(e.range_lo)
|
||||||
if e.range_lo == e.range_hi:
|
if e.range_lo == e.range_hi:
|
||||||
return fmt(e.range_lo)
|
return fmt(e.range_lo)
|
||||||
return "%s–%s" % [fmt(e.range_lo), fmt(e.range_hi)]
|
return "%s–%s" % [fmt(e.range_lo), fmt(e.range_hi)]
|
||||||
|
|
||||||
|
|
||||||
## Chance (0–1) that a roll lands on this entry.
|
## False when chances can't be known (expression dice).
|
||||||
|
func has_chances() -> bool:
|
||||||
|
return not is_expr_dice()
|
||||||
|
|
||||||
|
|
||||||
|
## Chance (0–1) that a roll lands on this entry. 0 for expression dice, whose
|
||||||
|
## chances can't be known (see has_chances()).
|
||||||
func chance(e: TableEntry) -> float:
|
func chance(e: TableEntry) -> float:
|
||||||
if is_ranged():
|
if is_ranged():
|
||||||
if not e.has_range:
|
if not e.has_range or is_expr_dice():
|
||||||
return 0.0
|
return 0.0
|
||||||
return dice_obj().probability_between(e.range_lo, e.range_hi)
|
return dice_obj().probability_between(e.range_lo, e.range_hi)
|
||||||
var total := total_weight()
|
var total := total_weight()
|
||||||
return float(maxi(0, e.weight)) / float(total) if total > 0 else 0.0
|
return float(maxi(0, e.weight)) / float(total) if total > 0 else 0.0
|
||||||
|
|
||||||
|
|
||||||
|
## True when the entry can come up at all.
|
||||||
|
func can_come_up(e: TableEntry) -> bool:
|
||||||
|
if is_ranged():
|
||||||
|
return e.has_range and (is_expr_dice() or chance(e) > 0.0)
|
||||||
|
return e.weight > 0
|
||||||
|
|
||||||
|
|
||||||
func entry_index_for(value: int) -> int:
|
func entry_index_for(value: int) -> int:
|
||||||
for i in entries.size():
|
for i in entries.size():
|
||||||
var e := entries[i]
|
var e := entries[i]
|
||||||
|
|
@ -109,6 +263,13 @@ func entry_index_for(value: int) -> int:
|
||||||
return -1
|
return -1
|
||||||
|
|
||||||
|
|
||||||
|
## Like entry_index_for(), but a value below the lowest range or above the
|
||||||
|
## highest one lands on that end range (expression dice).
|
||||||
|
func entry_index_clamped(value: int) -> int:
|
||||||
|
var span := _range_span()
|
||||||
|
return entry_index_for(clampi(value, span.x, span.y))
|
||||||
|
|
||||||
|
|
||||||
func find_entry(eid: String) -> TableEntry:
|
func find_entry(eid: String) -> TableEntry:
|
||||||
for e in entries:
|
for e in entries:
|
||||||
if e.id == eid:
|
if e.id == eid:
|
||||||
|
|
@ -117,19 +278,23 @@ func find_entry(eid: String) -> TableEntry:
|
||||||
|
|
||||||
|
|
||||||
## Describes gaps, overlaps and out-of-span ranges in a ranged table, or "" when clean.
|
## Describes gaps, overlaps and out-of-span ranges in a ranged table, or "" when clean.
|
||||||
|
## Expression dice have no fixed span, so only gaps between ranges and
|
||||||
|
## overlaps are reported.
|
||||||
func range_problems() -> String:
|
func range_problems() -> String:
|
||||||
if not is_ranged():
|
if not is_ranged():
|
||||||
return ""
|
return ""
|
||||||
var lo := min_value()
|
var lo := min_value()
|
||||||
var hi := die_size()
|
var hi := die_size()
|
||||||
|
if hi - lo > 100000:
|
||||||
|
return "The ranges span too many values to check."
|
||||||
var hits := PackedInt32Array()
|
var hits := PackedInt32Array()
|
||||||
hits.resize(hi + 1)
|
hits.resize(maxi(0, hi - lo + 1))
|
||||||
var outside := PackedStringArray()
|
var outside := PackedStringArray()
|
||||||
for e in entries:
|
for e in entries:
|
||||||
if not e.has_range:
|
if not e.has_range:
|
||||||
continue
|
continue
|
||||||
for v in range(maxi(lo, e.range_lo), mini(hi, e.range_hi) + 1):
|
for v in range(maxi(lo, e.range_lo), mini(hi, e.range_hi) + 1):
|
||||||
hits[v] += 1
|
hits[v - lo] += 1
|
||||||
if e.range_lo < lo or e.range_hi > hi:
|
if e.range_lo < lo or e.range_hi > hi:
|
||||||
outside.append("%s–%s" % [fmt(e.range_lo), fmt(e.range_hi)])
|
outside.append("%s–%s" % [fmt(e.range_lo), fmt(e.range_hi)])
|
||||||
var gaps := _runs(hits, lo, hi, func(h: int) -> bool: return h == 0)
|
var gaps := _runs(hits, lo, hi, func(h: int) -> bool: return h == 0)
|
||||||
|
|
@ -148,7 +313,7 @@ func _runs(hits: PackedInt32Array, lo: int, n: int, test: Callable) -> String:
|
||||||
var out := PackedStringArray()
|
var out := PackedStringArray()
|
||||||
var start := -1
|
var start := -1
|
||||||
for v in range(lo, n + 2):
|
for v in range(lo, n + 2):
|
||||||
var on: bool = v <= n and test.call(hits[v])
|
var on: bool = v <= n and test.call(hits[v - lo])
|
||||||
if on and start < 0:
|
if on and start < 0:
|
||||||
start = v
|
start = v
|
||||||
elif not on and start >= 0:
|
elif not on and start >= 0:
|
||||||
|
|
@ -157,11 +322,34 @@ func _runs(hits: PackedInt32Array, lo: int, n: int, test: Callable) -> String:
|
||||||
return ", ".join(out)
|
return ", ".join(out)
|
||||||
|
|
||||||
|
|
||||||
|
## A variable card's starting value: {"value", "error"}. An empty `initial`
|
||||||
|
## gives 0 for numbers and "" otherwise. For text and list variables, plain
|
||||||
|
## words that aren't an expression ("Aslan") are taken as they are.
|
||||||
|
func initial_value(ctx: RollContext) -> Dictionary:
|
||||||
|
var src := initial.strip_edges()
|
||||||
|
if src == "":
|
||||||
|
return {"value": 0 if var_type == "number" else "", "error": ""}
|
||||||
|
if var_type != "number" and _looks_literal(src):
|
||||||
|
return {"value": src, "error": ""}
|
||||||
|
var r := Expr.evaluate(src, ctx)
|
||||||
|
if r["error"] != "":
|
||||||
|
return {"value": 0 if var_type == "number" else "", "error": r["error"]}
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
static func _looks_literal(src: String) -> bool:
|
||||||
|
if src.begins_with("\"") or src.begins_with("'") or src.contains("@") or src.contains("("):
|
||||||
|
return false
|
||||||
|
return RegEx.create_from_string("^[^+\\-*/%=<>!&|]*$").search(src) != null and not src.is_valid_float()
|
||||||
|
|
||||||
|
|
||||||
func to_dict() -> Dictionary:
|
func to_dict() -> Dictionary:
|
||||||
var list: Array = []
|
var list: Array = []
|
||||||
for e in entries:
|
for e in entries:
|
||||||
list.append(e.to_dict())
|
list.append(e.to_dict())
|
||||||
var d := {"id": id, "name": name, "x": roundi(position.x), "y": roundi(position.y), "entries": list}
|
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:
|
if collapsed:
|
||||||
d["collapsed"] = true
|
d["collapsed"] = true
|
||||||
if details != "":
|
if details != "":
|
||||||
|
|
@ -174,6 +362,29 @@ func to_dict() -> Dictionary:
|
||||||
d["card_mode"] = true
|
d["card_mode"] = true
|
||||||
if deck_empty != "reshuffle":
|
if deck_empty != "reshuffle":
|
||||||
d["deck_empty"] = deck_empty
|
d["deck_empty"] = deck_empty
|
||||||
|
if kind == KIND_CHOICE:
|
||||||
|
if choice != "pick":
|
||||||
|
d["choice"] = choice
|
||||||
|
if prompt != "":
|
||||||
|
d["prompt"] = prompt
|
||||||
|
if save_as != "":
|
||||||
|
d["save_as"] = save_as
|
||||||
|
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
|
||||||
return d
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -190,7 +401,31 @@ static func from_dict(d: Dictionary) -> RollTable:
|
||||||
t.dice = "1d%d" % int(d["die"])
|
t.dice = "1d%d" % int(d["die"])
|
||||||
t.card_mode = bool(d.get("card_mode", false))
|
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 = "stop" if str(d.get("deck_empty", "reshuffle")) == "stop" else "reshuffle"
|
||||||
|
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.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", ""), "")
|
||||||
for ed: Variant in d.get("entries", []):
|
for ed: Variant in d.get("entries", []):
|
||||||
if ed is Dictionary:
|
if ed is Dictionary:
|
||||||
t.entries.append(TableEntry.from_dict(ed))
|
t.entries.append(TableEntry.from_dict(ed))
|
||||||
return t
|
return t
|
||||||
|
|
||||||
|
|
||||||
|
## Expression fields may arrive as JSON numbers: 3.0 -> "3".
|
||||||
|
static func expr_text(v: Variant, fallback: String) -> String:
|
||||||
|
if v == null:
|
||||||
|
return fallback
|
||||||
|
if v is float or v is int:
|
||||||
|
return Expr.format_value(v)
|
||||||
|
return str(v)
|
||||||
|
|
|
||||||
556
core/roller.gd
556
core/roller.gd
|
|
@ -11,27 +11,56 @@ extends RefCounted
|
||||||
## "inline": true, then pipe rolls in pipe order),
|
## "inline": true, then pipe rolls in pipe order),
|
||||||
## and "stop": String when the chain couldn't continue (its summary then
|
## and "stop": String when the chain couldn't continue (its summary then
|
||||||
## explains why).
|
## explains why).
|
||||||
|
## Logic-card keys (docs/LOGIC.md), present only when they apply:
|
||||||
|
## kind: "choice" | "loop" | "sheet" (plain roll nodes have no kind)
|
||||||
|
## effects: Array of {"text": String, "error": true?}, the effect log
|
||||||
|
## answer: the player's answer on a number/text choice (int or String)
|
||||||
|
## picked: true when the player picked a pick option; random: true for Random
|
||||||
|
## passes: int, on a loop's header node ("Repeated N times"); its children
|
||||||
|
## are one node per pass ("pass": i, "value": i) and then the Afterwards
|
||||||
|
## node ("after": true)
|
||||||
|
## limit: true on the "Stopped after 10,000 actions" stop node
|
||||||
|
## cancelled: true on the "Cancelled" stop node
|
||||||
|
##
|
||||||
|
## The roller is a coroutine with an explicit work stack: pipes and loop passes
|
||||||
|
## never recurse in GDScript, so chains of thousands of steps are fine. Only
|
||||||
|
## inline [[references]] nest (at most RollContext.max_depth deep).
|
||||||
|
##
|
||||||
|
## roll_async() is the main entry point. It awaits ctx.prompt for choice cards
|
||||||
|
## and fills in ctx.root as it goes. roll() is the plain form: it never waits
|
||||||
|
## (choices get the headless answers) and returns the tree directly.
|
||||||
|
|
||||||
## Deepest level a chain can reach before it stops (matches RollContext).
|
## Deepest level inline references can nest (matches RollContext).
|
||||||
const MAX_DEPTH := RollContext.DEFAULT_MAX_DEPTH
|
const MAX_DEPTH := RollContext.DEFAULT_MAX_DEPTH
|
||||||
|
## Most actions one top-level roll may take (matches RollContext).
|
||||||
|
const MAX_ACTIONS := RollContext.DEFAULT_MAX_ACTIONS
|
||||||
|
const CANCELLED := "Cancelled"
|
||||||
|
|
||||||
|
enum { OP_ROLL, OP_PIPE, OP_LOOP }
|
||||||
|
|
||||||
|
|
||||||
## A RollContext wired to this board: it resolves [[names]] against the board's
|
## A RollContext wired to this board: it resolves [[names]] against the board's
|
||||||
## tables and rolls inline references through the roller. `persistent` is the
|
## tables and rolls inline references through the roller. `persistent` is the
|
||||||
## collection's persistent variables (name without "@" -> {value, source}),
|
## collection's persistent variables (name without "@" -> {value, source}),
|
||||||
## shared, not copied. `decks` maps table id to DeckState for card-mode tables,
|
## shared, not copied. `decks` maps table id to DeckState for card-mode tables,
|
||||||
## also shared.
|
## also shared. Set ctx.prompt to ask the player on choice cards.
|
||||||
static func new_context(board: TowerBoard, rng: RandomNumberGenerator, persistent: Dictionary = {}, decks: Dictionary = {}) -> RollContext:
|
static func new_context(board: TowerBoard, rng: RandomNumberGenerator, persistent: Dictionary = {}, decks: Dictionary = {}) -> RollContext:
|
||||||
var ctx := RollContext.new(persistent, rng)
|
var ctx := RollContext.new(persistent, rng)
|
||||||
ctx.max_depth = MAX_DEPTH
|
ctx.max_depth = MAX_DEPTH
|
||||||
|
ctx.board = board
|
||||||
ctx.set_meta("decks", decks)
|
ctx.set_meta("decks", decks)
|
||||||
# A weak reference, so the context doesn't keep itself alive through its hook.
|
# A weak reference, so the context doesn't keep itself alive through its hooks.
|
||||||
var wr: WeakRef = weakref(ctx)
|
var wr: WeakRef = weakref(ctx)
|
||||||
ctx.resolve_table = func(name_or_id: String) -> String:
|
ctx.resolve_table = func(name_or_id: String) -> String:
|
||||||
return resolve(board, name_or_id)
|
return resolve(board, name_or_id)
|
||||||
ctx.roll_table = func(id: String, depth: int) -> Dictionary:
|
ctx.roll_table = func(id: String, depth: int) -> Dictionary:
|
||||||
var c: RollContext = wr.get_ref()
|
var c: RollContext = wr.get_ref()
|
||||||
return {} if c == null else _roll(board, id, depth, c)
|
return {} if c == null else _chain_sync(board, id, depth, c)
|
||||||
|
ctx.roll_table_async = func(id: String, depth: int) -> Dictionary:
|
||||||
|
var c: RollContext = wr.get_ref()
|
||||||
|
if c == null:
|
||||||
|
return {}
|
||||||
|
return await _chain(board, id, depth, c)
|
||||||
return ctx
|
return ctx
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -50,20 +79,89 @@ static func resolve(board: TowerBoard, name_or_id: String) -> String:
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
|
||||||
## Rolls `table_id` and everything its pipes and references lead to.
|
## Rolls `table_id` and everything its pipes and references lead to, without
|
||||||
|
## ever waiting: choice cards get the headless answers (Random, min, "").
|
||||||
## `decks` maps table id to DeckState for card-mode tables; missing decks are
|
## `decks` maps table id to DeckState for card-mode tables; missing decks are
|
||||||
## created in it on demand. `ctx` carries the variables for the whole chain.
|
## created in it on demand. `ctx` carries the variables for the whole chain.
|
||||||
## Without one, a fresh context (no persistent variables) is made around
|
## Without one, a fresh context (no persistent variables) is made around
|
||||||
## `decks`; a context from new_context() brings its own decks and `decks` is
|
## `decks`; a context from new_context() brings its own decks and `decks` is
|
||||||
## then ignored. Extra node keys: "save_as" (on nodes reached through a pipe
|
## then ignored. Extra node keys: "save_as" (on nodes reached through a pipe
|
||||||
## that saves), "reshuffled" (card deck was refilled for this draw), "inline"
|
## that saves), "reshuffled" (card deck was refilled for this draw), "inline"
|
||||||
## (rolled by a [[reference]] in the parent's text).
|
## (rolled by a [[reference]] in the parent's text), and the logic-card keys
|
||||||
|
## listed at the top of this file.
|
||||||
static func roll(board: TowerBoard, table_id: String, rng: RandomNumberGenerator, depth: int = 0, decks: Dictionary = {}, ctx: RollContext = null) -> Dictionary:
|
static func roll(board: TowerBoard, table_id: String, rng: RandomNumberGenerator, depth: int = 0, decks: Dictionary = {}, ctx: RollContext = null) -> Dictionary:
|
||||||
if ctx == null:
|
if ctx == null:
|
||||||
ctx = new_context(board, rng, {}, decks)
|
ctx = new_context(board, rng, {}, decks)
|
||||||
elif not ctx.has_meta("decks"):
|
elif not ctx.has_meta("decks"):
|
||||||
ctx.set_meta("decks", decks)
|
ctx.set_meta("decks", decks)
|
||||||
return _roll(board, table_id, depth, ctx)
|
var was := ctx.no_prompt
|
||||||
|
ctx.no_prompt = true
|
||||||
|
var r: Variant = Callable(Roller, "roll_async").call(board, table_id, ctx, depth)
|
||||||
|
ctx.no_prompt = was
|
||||||
|
return r if r is Dictionary else {}
|
||||||
|
|
||||||
|
|
||||||
|
## The coroutine roll: `await Roller.roll_async(board, id, ctx)`. Choice cards
|
||||||
|
## await ctx.prompt (see ask()); with no prompt hook it finishes without
|
||||||
|
## waiting a frame. ctx.root holds the tree so far while it runs (see
|
||||||
|
## progress()). Resets the action counter, ctx.halted and ctx.root unless it's
|
||||||
|
## called from inside a running roll.
|
||||||
|
static func roll_async(board: TowerBoard, table_id: String, ctx: RollContext, depth: int = 0) -> Dictionary:
|
||||||
|
if ctx.board == null:
|
||||||
|
ctx.board = board
|
||||||
|
if not ctx.has_meta("decks"):
|
||||||
|
ctx.set_meta("decks", {})
|
||||||
|
if ctx.running == 0:
|
||||||
|
ctx.actions = 0
|
||||||
|
ctx.halted = ""
|
||||||
|
ctx.root = {}
|
||||||
|
ctx.forget_declarations()
|
||||||
|
return await _chain(board, table_id, depth, ctx)
|
||||||
|
|
||||||
|
|
||||||
|
## The steps of the tree built so far (ctx.root), e.g. while a prompt is open.
|
||||||
|
static func progress(ctx: RollContext) -> Array:
|
||||||
|
return flatten(ctx.root, [])
|
||||||
|
|
||||||
|
|
||||||
|
## "Stopped after 10,000 actions".
|
||||||
|
static func limit_text(n: int = MAX_ACTIONS) -> String:
|
||||||
|
var s := str(n)
|
||||||
|
var out := ""
|
||||||
|
while s.length() > 3:
|
||||||
|
out = "," + s.substr(s.length() - 3) + out
|
||||||
|
s = s.substr(0, s.length() - 3)
|
||||||
|
return "Stopped after %s actions" % (s + out)
|
||||||
|
|
||||||
|
|
||||||
|
static func _chain_sync(board: TowerBoard, id: String, depth: int, ctx: RollContext) -> Dictionary:
|
||||||
|
var was := ctx.no_prompt
|
||||||
|
ctx.no_prompt = true
|
||||||
|
var r: Variant = Callable(Roller, "_chain").call(board, id, depth, ctx)
|
||||||
|
ctx.no_prompt = was
|
||||||
|
return r if r is Dictionary else {}
|
||||||
|
|
||||||
|
|
||||||
|
## Runs one chain (a top-level roll, or one inline reference) on its own work
|
||||||
|
## stack. Returns its first node, or {} when the table is missing or is a
|
||||||
|
## variable card.
|
||||||
|
static func _chain(board: TowerBoard, table_id: String, depth: int, ctx: RollContext) -> Dictionary:
|
||||||
|
ctx.running += 1
|
||||||
|
var holder := {"children": []}
|
||||||
|
var stack: Array = [{"op": OP_ROLL, "id": table_id, "parent": holder, "save": "", "depth": depth,
|
||||||
|
"top": ctx.running == 1}]
|
||||||
|
while not stack.is_empty() and ctx.halted == "":
|
||||||
|
var f: Dictionary = stack.pop_back()
|
||||||
|
match int(f["op"]):
|
||||||
|
OP_ROLL:
|
||||||
|
await _do_roll(board, f, ctx, stack)
|
||||||
|
OP_PIPE:
|
||||||
|
_do_pipe(board, f, ctx, stack)
|
||||||
|
OP_LOOP:
|
||||||
|
await _do_loop(f, ctx, stack)
|
||||||
|
ctx.running -= 1
|
||||||
|
var kids: Array = holder["children"]
|
||||||
|
return kids[0] if not kids.is_empty() else {}
|
||||||
|
|
||||||
|
|
||||||
static func _stop(t: RollTable, why: String, extra: Dictionary = {}) -> Dictionary:
|
static func _stop(t: RollTable, why: String, extra: Dictionary = {}) -> Dictionary:
|
||||||
|
|
@ -72,15 +170,56 @@ static func _stop(t: RollTable, why: String, extra: Dictionary = {}) -> Dictiona
|
||||||
return node
|
return node
|
||||||
|
|
||||||
|
|
||||||
static func _roll(board: TowerBoard, table_id: String, depth: int, ctx: RollContext) -> Dictionary:
|
static func _attach(f: Dictionary, node: Dictionary, ctx: RollContext) -> void:
|
||||||
var t := board.get_table(table_id)
|
if str(f.get("save", "")) != "":
|
||||||
if t == null:
|
node["save_as"] = f["save"]
|
||||||
return {}
|
(f["parent"]["children"] as Array).append(node)
|
||||||
var rng := ctx.rng
|
if f.get("top", false):
|
||||||
if depth > MAX_DEPTH:
|
ctx.root = node
|
||||||
return _stop(t, "Chain stopped after %d tables" % MAX_DEPTH, {"summary": TextExpander.deep_marker(t.id)})
|
|
||||||
|
|
||||||
|
## Counts one action, or stops the roll at the limit (attaching the marker
|
||||||
|
## under `f.parent`). Returns false when the roll has to stop.
|
||||||
|
static func _take_action(f: Dictionary, t: RollTable, ctx: RollContext) -> bool:
|
||||||
|
if ctx.actions >= ctx.max_actions:
|
||||||
|
var msg := limit_text(ctx.max_actions)
|
||||||
|
_attach(f, _stop(t, msg, {"limit": true}), ctx)
|
||||||
|
ctx.halted = msg
|
||||||
|
return false
|
||||||
|
ctx.actions += 1
|
||||||
|
return true
|
||||||
|
|
||||||
|
|
||||||
|
static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: Array) -> void:
|
||||||
|
var t := board.get_table(str(f["id"]))
|
||||||
|
if t == null or t.kind == RollTable.KIND_VARIABLE:
|
||||||
|
return
|
||||||
|
if not _take_action(f, t, ctx):
|
||||||
|
return
|
||||||
if t.entries.is_empty():
|
if t.entries.is_empty():
|
||||||
return _stop(t, "This table has no results")
|
_attach(f, _stop(t, "This table has no results"), ctx)
|
||||||
|
return
|
||||||
|
match t.kind:
|
||||||
|
RollTable.KIND_CHOICE:
|
||||||
|
await _do_choice(t, f, ctx, stack)
|
||||||
|
RollTable.KIND_LOOP:
|
||||||
|
_start_loop(t, f, ctx, stack)
|
||||||
|
RollTable.KIND_SHEET:
|
||||||
|
var sheet := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "",
|
||||||
|
"kind": RollTable.KIND_SHEET}
|
||||||
|
_attach(f, sheet, ctx)
|
||||||
|
await _enter(sheet, f, ctx, stack, true, true)
|
||||||
|
_:
|
||||||
|
var node := _pick_node(t, ctx)
|
||||||
|
_attach(f, node, ctx)
|
||||||
|
if not node.has("stop"):
|
||||||
|
await _enter(node, f, ctx, stack)
|
||||||
|
|
||||||
|
|
||||||
|
## 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:
|
||||||
|
var rng := ctx.rng
|
||||||
var index: int
|
var index: int
|
||||||
var value: int
|
var value: int
|
||||||
var reshuffled := false
|
var reshuffled := false
|
||||||
|
|
@ -100,8 +239,11 @@ static func _roll(board: TowerBoard, table_id: String, depth: int, ctx: RollCont
|
||||||
index = int(card["index"])
|
index = int(card["index"])
|
||||||
value = int(card["value"])
|
value = int(card["value"])
|
||||||
elif t.is_ranged():
|
elif t.is_ranged():
|
||||||
value = t.dice_obj().roll(rng)
|
var rv := t.roll_value(ctx)
|
||||||
index = t.entry_index_for(value)
|
if rv["error"] != "":
|
||||||
|
return _stop(t, "Can't roll %s: %s" % [t.dice, rv["error"]])
|
||||||
|
value = int(rv["value"])
|
||||||
|
index = t.entry_index_clamped(value) if t.is_expr_dice() else t.entry_index_for(value)
|
||||||
if index < 0:
|
if index < 0:
|
||||||
return _stop(t, "No result for %s" % t.fmt(value), {"value": value})
|
return _stop(t, "No result for %s" % t.fmt(value), {"value": value})
|
||||||
else:
|
else:
|
||||||
|
|
@ -109,31 +251,225 @@ static func _roll(board: TowerBoard, table_id: String, depth: int, ctx: RollCont
|
||||||
if index < 0:
|
if index < 0:
|
||||||
return _stop(t, "No result can come up")
|
return _stop(t, "No result can come up")
|
||||||
value = index + 1
|
value = index + 1
|
||||||
var e := t.entries[index]
|
var node := {"table": t, "index": index, "value": value, "entry": t.entries[index], "children": [],
|
||||||
ctx.depth = depth + 1
|
"summary": ""}
|
||||||
var expanded := TextExpander.expand(e.text, ctx)
|
|
||||||
var children: Array = []
|
|
||||||
for c: Dictionary in expanded["children"]:
|
|
||||||
c["inline"] = true
|
|
||||||
children.append(c)
|
|
||||||
for p in e.pipes:
|
|
||||||
var save := e.save_for(p)
|
|
||||||
for k in e.count_for(p):
|
|
||||||
var child := _roll(board, p, depth + 1, ctx)
|
|
||||||
if child.is_empty():
|
|
||||||
break
|
|
||||||
if save != "":
|
|
||||||
child["save_as"] = save
|
|
||||||
if not child.has("stop"):
|
|
||||||
ctx.save(save, Formatter.to_export_bbcode(str(child.get("summary", ""))), p)
|
|
||||||
children.append(child)
|
|
||||||
var node := {"table": t, "index": index, "value": value, "entry": e, "children": children,
|
|
||||||
"summary": expanded["text"]}
|
|
||||||
if reshuffled:
|
if reshuffled:
|
||||||
node["reshuffled"] = true
|
node["reshuffled"] = true
|
||||||
return node
|
return node
|
||||||
|
|
||||||
|
|
||||||
|
## The chosen entry happens: its effects run, its text expands (unless
|
||||||
|
## `expand` is false, for answers) and its pipes are queued. `live` renders the
|
||||||
|
## text without rolling references (sheet cards).
|
||||||
|
static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Array, expand: bool = true, live: bool = false) -> void:
|
||||||
|
var t: RollTable = node["table"]
|
||||||
|
var e: TableEntry = node["entry"]
|
||||||
|
var depth := int(f.get("depth", 0))
|
||||||
|
if e.effects.strip_edges() != "":
|
||||||
|
node["effects"] = Effects.run(e.effects, ctx, t.id)
|
||||||
|
if expand:
|
||||||
|
ctx.depth = depth + 1
|
||||||
|
var ex: Dictionary = await TextExpander.expand_async(e.text, ctx, live)
|
||||||
|
ctx.depth = depth
|
||||||
|
var kids: Array = node["children"]
|
||||||
|
for c: Dictionary in ex["children"]:
|
||||||
|
c["inline"] = true
|
||||||
|
kids.append(c)
|
||||||
|
node["summary"] = ex["text"]
|
||||||
|
if ctx.halted != "":
|
||||||
|
return
|
||||||
|
var save := str(f.get("save", ""))
|
||||||
|
if save != "":
|
||||||
|
var v: Variant = node["answer"] if node.has("answer") else Formatter.to_export_bbcode(str(node["summary"]))
|
||||||
|
ctx.save(save, v, t.id)
|
||||||
|
for k in range(e.pipes.size() - 1, -1, -1):
|
||||||
|
var p := e.pipes[k]
|
||||||
|
stack.append({"op": OP_PIPE, "node": node, "entry": e, "to": p, "left": -1, "save": e.save_for(p), "depth": depth})
|
||||||
|
|
||||||
|
|
||||||
|
static func _do_pipe(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: Array) -> void:
|
||||||
|
if int(f["left"]) < 0:
|
||||||
|
var log: Array = []
|
||||||
|
f["left"] = (f["entry"] as TableEntry).count_value(str(f["to"]), ctx, log)
|
||||||
|
if not log.is_empty():
|
||||||
|
var node: Dictionary = f["node"]
|
||||||
|
if not node.has("effects"):
|
||||||
|
node["effects"] = []
|
||||||
|
(node["effects"] as Array).append_array(log)
|
||||||
|
if int(f["left"]) <= 0:
|
||||||
|
return
|
||||||
|
var t := board.get_table(str(f["to"]))
|
||||||
|
if t == null or t.kind == RollTable.KIND_VARIABLE:
|
||||||
|
return
|
||||||
|
f["left"] = int(f["left"]) - 1
|
||||||
|
stack.append(f)
|
||||||
|
stack.append({"op": OP_ROLL, "id": f["to"], "parent": f["node"], "save": f["save"], "depth": f["depth"]})
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Loops ----------
|
||||||
|
|
||||||
|
static func _repeated(n: int) -> String:
|
||||||
|
return "Repeated 1 time" if n == 1 else "Repeated %d times" % n
|
||||||
|
|
||||||
|
|
||||||
|
static func _start_loop(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
|
||||||
|
var header := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": _repeated(0),
|
||||||
|
"kind": RollTable.KIND_LOOP, "passes": 0}
|
||||||
|
_attach(f, header, ctx)
|
||||||
|
var total := 0
|
||||||
|
if t.loop_mode == "times":
|
||||||
|
var r := Expr.evaluate(t.loop_expr, ctx)
|
||||||
|
if r["error"] != "":
|
||||||
|
header["effects"] = [{"text": "Repeat %s: %s" % [t.loop_expr, r["error"]], "error": true}]
|
||||||
|
else:
|
||||||
|
total = maxi(0, Expr.as_int(r, 0))
|
||||||
|
stack.append({"op": OP_LOOP, "node": header, "table": t, "i": 0, "total": total, "depth": f.get("depth", 0),
|
||||||
|
"save": f.get("save", ""), "had_i": ctx.chain_vars.has("i"), "prev_i": ctx.chain_vars.get("i")})
|
||||||
|
|
||||||
|
|
||||||
|
## 1 true, 0 false, -1 error (logged on the header).
|
||||||
|
static func _cond(t: RollTable, header: Dictionary, ctx: RollContext) -> int:
|
||||||
|
var r := Expr.evaluate(t.loop_expr, ctx)
|
||||||
|
if r["error"] != "":
|
||||||
|
if not header.has("effects"):
|
||||||
|
header["effects"] = []
|
||||||
|
(header["effects"] as Array).append({"text": "%s %s: %s" % [t.loop_mode.capitalize(), t.loop_expr, r["error"]], "error": true})
|
||||||
|
return -1
|
||||||
|
return 1 if Expr.truthy(r["value"]) else 0
|
||||||
|
|
||||||
|
|
||||||
|
static func _do_loop(f: Dictionary, ctx: RollContext, stack: Array) -> void:
|
||||||
|
var t: RollTable = f["table"]
|
||||||
|
var header: Dictionary = f["node"]
|
||||||
|
var i := int(f["i"])
|
||||||
|
var go := false
|
||||||
|
match t.loop_mode:
|
||||||
|
"times":
|
||||||
|
go = i < int(f["total"])
|
||||||
|
"while":
|
||||||
|
go = _cond(t, header, ctx) == 1
|
||||||
|
"until":
|
||||||
|
go = i == 0 or _cond(t, header, ctx) == 0
|
||||||
|
if go:
|
||||||
|
if not _take_action({"parent": header}, t, ctx):
|
||||||
|
return
|
||||||
|
i += 1
|
||||||
|
f["i"] = i
|
||||||
|
ctx.chain_vars["i"] = i
|
||||||
|
header["passes"] = i
|
||||||
|
header["summary"] = _repeated(i)
|
||||||
|
var pass_node := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "",
|
||||||
|
"kind": RollTable.KIND_LOOP, "pass": i, "value": i}
|
||||||
|
(header["children"] as Array).append(pass_node)
|
||||||
|
stack.append(f)
|
||||||
|
await _enter(pass_node, {"depth": f["depth"]}, ctx, stack)
|
||||||
|
return
|
||||||
|
if f["had_i"]:
|
||||||
|
ctx.chain_vars["i"] = f["prev_i"]
|
||||||
|
else:
|
||||||
|
ctx.chain_vars.erase("i")
|
||||||
|
if str(f["save"]) != "":
|
||||||
|
ctx.save(str(f["save"]), i, t.id)
|
||||||
|
if t.entries.size() > 1:
|
||||||
|
var after := {"table": t, "index": 1, "entry": t.entries[1], "children": [], "summary": "",
|
||||||
|
"kind": RollTable.KIND_LOOP, "after": true}
|
||||||
|
(header["children"] as Array).append(after)
|
||||||
|
await _enter(after, {"depth": f["depth"]}, ctx, stack)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Choices ----------
|
||||||
|
|
||||||
|
## The prompt request for a choice card (docs/LOGIC.md §8):
|
||||||
|
## {table_id, kind ("pick" | "number" | "text"), title, prompt (BBCode,
|
||||||
|
## rendered), options: [{index, text, details}], min, max, default}.
|
||||||
|
static func request_for(t: RollTable, ctx: RollContext) -> Dictionary:
|
||||||
|
var options: Array = []
|
||||||
|
if t.choice == "pick":
|
||||||
|
for k in t.entries.size():
|
||||||
|
var e := t.entries[k]
|
||||||
|
options.append({"index": k, "text": TextExpander.render(e.text, ctx), "details": e.details})
|
||||||
|
var lo := Expr.eval_int(t.min_expr, ctx, 0)
|
||||||
|
var hi := maxi(lo, Expr.eval_int(t.max_expr, ctx, 99))
|
||||||
|
var def: Variant = -1
|
||||||
|
if t.choice == "number":
|
||||||
|
def = lo
|
||||||
|
elif t.choice == "text":
|
||||||
|
def = ""
|
||||||
|
return {"table_id": t.id, "kind": t.choice, "title": t.name, "prompt": TextExpander.render(t.prompt, ctx),
|
||||||
|
"options": options, "min": lo, "max": hi, "default": def}
|
||||||
|
|
||||||
|
|
||||||
|
## The headless answer to a request: Random for a pick, min for a number, ""
|
||||||
|
## for text.
|
||||||
|
static func default_reply(req: Dictionary) -> Variant:
|
||||||
|
match str(req.get("kind", "pick")):
|
||||||
|
"number":
|
||||||
|
return int(req.get("min", 0))
|
||||||
|
"text":
|
||||||
|
return ""
|
||||||
|
return -1
|
||||||
|
|
||||||
|
|
||||||
|
## Asks the player through ctx.prompt, or gives the headless answer.
|
||||||
|
static func ask(ctx: RollContext, req: Dictionary) -> Variant:
|
||||||
|
if ctx.no_prompt or not ctx.prompt.is_valid():
|
||||||
|
return default_reply(req)
|
||||||
|
return await ctx.prompt.call(req)
|
||||||
|
|
||||||
|
|
||||||
|
static func _do_choice(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
|
||||||
|
var req := request_for(t, ctx)
|
||||||
|
var reply: Variant = await ask(ctx, req)
|
||||||
|
if reply == null:
|
||||||
|
_attach(f, _stop(t, CANCELLED, {"kind": RollTable.KIND_CHOICE, "cancelled": true}), ctx)
|
||||||
|
ctx.halted = CANCELLED
|
||||||
|
return
|
||||||
|
match t.choice:
|
||||||
|
"number":
|
||||||
|
var v := int(req["min"])
|
||||||
|
if reply is int or reply is float:
|
||||||
|
v = int(reply)
|
||||||
|
elif reply is String and (reply as String).strip_edges().is_valid_int():
|
||||||
|
v = (reply as String).strip_edges().to_int()
|
||||||
|
v = clampi(v, int(req["min"]), int(req["max"]))
|
||||||
|
await _answered(t, f, ctx, stack, v, str(v))
|
||||||
|
"text":
|
||||||
|
var s := str(reply)
|
||||||
|
await _answered(t, f, ctx, stack, s, Formatter.close_open_tags(s))
|
||||||
|
_:
|
||||||
|
var idx := int(reply) if (reply is int or reply is float) else -1
|
||||||
|
var node: Dictionary
|
||||||
|
if idx >= 0 and idx < t.entries.size():
|
||||||
|
node = {"table": t, "index": idx, "entry": t.entries[idx], "children": [], "summary": "", "picked": true}
|
||||||
|
if t.card_mode:
|
||||||
|
var decks: Dictionary = ctx.get_meta("decks", {})
|
||||||
|
if not decks.has(t.id):
|
||||||
|
decks[t.id] = DeckState.new()
|
||||||
|
var deck: DeckState = decks[t.id]
|
||||||
|
var eid := t.entries[idx].id
|
||||||
|
deck.drawn[eid] = int(deck.drawn.get(eid, 0)) + 1
|
||||||
|
else:
|
||||||
|
node = _pick_node(t, ctx)
|
||||||
|
node["random"] = true
|
||||||
|
node["kind"] = RollTable.KIND_CHOICE
|
||||||
|
_attach(f, node, ctx)
|
||||||
|
if node.has("stop"):
|
||||||
|
return
|
||||||
|
await _enter(node, f, ctx, stack)
|
||||||
|
if t.save_as != "" and ctx.halted == "":
|
||||||
|
ctx.save(t.save_as, Formatter.strip_tags(str(node["summary"])).strip_edges(), t.id)
|
||||||
|
|
||||||
|
|
||||||
|
static func _answered(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array, value: Variant, summary: String) -> void:
|
||||||
|
ctx.chain_vars["answer"] = value
|
||||||
|
if t.save_as != "":
|
||||||
|
ctx.save(t.save_as, value, t.id)
|
||||||
|
var node := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": summary,
|
||||||
|
"kind": RollTable.KIND_CHOICE, "answer": value}
|
||||||
|
_attach(f, node, ctx)
|
||||||
|
await _enter(node, f, ctx, stack, false)
|
||||||
|
|
||||||
|
|
||||||
## Index of a weighted random entry, or -1 if every weight is 0.
|
## Index of a weighted random entry, or -1 if every weight is 0.
|
||||||
static func _pick_weighted(t: RollTable, rng: RandomNumberGenerator) -> int:
|
static func _pick_weighted(t: RollTable, rng: RandomNumberGenerator) -> int:
|
||||||
var total := t.total_weight()
|
var total := t.total_weight()
|
||||||
|
|
@ -149,7 +485,8 @@ static func _pick_weighted(t: RollTable, rng: RandomNumberGenerator) -> int:
|
||||||
|
|
||||||
## Ids of tables that can never finish rolling: every result they can give
|
## Ids of tables that can never finish rolling: every result they can give
|
||||||
## leads, through pipes, back into such a table. A table that loops on only
|
## leads, through pipes, back into such a table. A table that loops on only
|
||||||
## some of its entries is fine.
|
## some of its entries is fine, and so is a pipe whose count is an expression
|
||||||
|
## (it may come to 0).
|
||||||
static func endless_cycles(board: TowerBoard) -> Array[String]:
|
static func endless_cycles(board: TowerBoard) -> Array[String]:
|
||||||
var done := {}
|
var done := {}
|
||||||
var changed := true
|
var changed := true
|
||||||
|
|
@ -168,31 +505,43 @@ static func endless_cycles(board: TowerBoard) -> Array[String]:
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
static func _can_finish(t: RollTable, board: TowerBoard, done: Dictionary) -> bool:
|
static func _entry_finishes(e: TableEntry, board: TowerBoard, done: Dictionary) -> bool:
|
||||||
if t.entries.is_empty():
|
for p in e.pipes:
|
||||||
return true
|
if e.count_expr(p) != "":
|
||||||
for e in t.entries:
|
|
||||||
if t.is_ranged():
|
|
||||||
if not e.has_range or t.chance(e) <= 0.0:
|
|
||||||
continue
|
|
||||||
elif e.weight <= 0:
|
|
||||||
continue
|
continue
|
||||||
var ok := true
|
if board.get_table(p) != null and not done.has(p):
|
||||||
for p in e.pipes:
|
return false
|
||||||
if board.get_table(p) != null and not done.has(p):
|
return true
|
||||||
ok = false
|
|
||||||
break
|
|
||||||
if ok:
|
static func _can_finish(t: RollTable, board: TowerBoard, done: Dictionary) -> bool:
|
||||||
|
if t.entries.is_empty() or t.kind == RollTable.KIND_VARIABLE:
|
||||||
|
return true
|
||||||
|
if t.kind == RollTable.KIND_LOOP:
|
||||||
|
# Every entry runs (a while/until loop ends on its condition).
|
||||||
|
for e in t.entries:
|
||||||
|
if not _entry_finishes(e, board, done):
|
||||||
|
return false
|
||||||
|
return true
|
||||||
|
var player := t.kind != RollTable.KIND_ROLL
|
||||||
|
for e in t.entries:
|
||||||
|
if not player and not t.can_come_up(e):
|
||||||
|
continue
|
||||||
|
if _entry_finishes(e, board, done):
|
||||||
return true
|
return true
|
||||||
|
if player:
|
||||||
|
return false
|
||||||
# No entry can come up at all: the roll just stops.
|
# No entry can come up at all: the roll just stops.
|
||||||
for e in t.entries:
|
for e in t.entries:
|
||||||
if (t.is_ranged() and e.has_range and t.chance(e) > 0.0) or (not t.is_ranged() and e.weight > 0):
|
if t.can_come_up(e):
|
||||||
return false
|
return false
|
||||||
return true
|
return true
|
||||||
|
|
||||||
|
|
||||||
## One line of the result tray for a single node. Plain data only, because it
|
## One line of the result tray for a single node. Plain data only, because it
|
||||||
## is saved in the roll history. "text" is BBCode with internal markers.
|
## is saved in the roll history. "text" is BBCode with internal markers.
|
||||||
|
## Logic-card keys (only when they apply): kind, effects (Array of {text,
|
||||||
|
## error?}), answer, passes, pass, after, picked, random, limit, cancelled.
|
||||||
static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
|
static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
|
||||||
var t: RollTable = n["table"]
|
var t: RollTable = n["table"]
|
||||||
var step := {
|
var step := {
|
||||||
|
|
@ -214,42 +563,84 @@ static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
|
||||||
step["reshuffled"] = true
|
step["reshuffled"] = true
|
||||||
if n.has("save_as"):
|
if n.has("save_as"):
|
||||||
step["save_as"] = n["save_as"]
|
step["save_as"] = n["save_as"]
|
||||||
|
if n.has("kind"):
|
||||||
|
step["kind"] = n["kind"]
|
||||||
|
if n.has("effects"):
|
||||||
|
step["effects"] = (n["effects"] as Array).duplicate(true)
|
||||||
|
for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled"]:
|
||||||
|
if n.has(k):
|
||||||
|
step[k] = n[k]
|
||||||
return step
|
return step
|
||||||
|
|
||||||
|
|
||||||
## The whole chain in the order it was rolled.
|
## The whole chain in the order it was rolled. Iterative, so any length is
|
||||||
|
## fine; works on a partial tree (ctx.root while a roll is running) too.
|
||||||
static func flatten(n: Dictionary, out: Array = [], depth: int = 0) -> Array:
|
static func flatten(n: Dictionary, out: Array = [], depth: int = 0) -> Array:
|
||||||
if n.is_empty():
|
if n.is_empty():
|
||||||
return out
|
return out
|
||||||
out.append(step_of(n, depth))
|
var stack: Array = [[n, depth]]
|
||||||
for c in n["children"]:
|
while not stack.is_empty():
|
||||||
flatten(c, out, depth + 1)
|
var top: Array = stack.pop_back()
|
||||||
|
var node: Dictionary = top[0]
|
||||||
|
var d: int = top[1]
|
||||||
|
out.append(step_of(node, d))
|
||||||
|
var kids: Array = node.get("children", [])
|
||||||
|
for k in range(kids.size() - 1, -1, -1):
|
||||||
|
stack.append([kids[k], d + 1])
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
static func reaches(n: Dictionary, table_id: String) -> bool:
|
static func reaches(n: Dictionary, table_id: String) -> bool:
|
||||||
if n.is_empty():
|
if n.is_empty():
|
||||||
return false
|
return false
|
||||||
if (n["table"] as RollTable).id == table_id:
|
var stack: Array = [n]
|
||||||
return true
|
while not stack.is_empty():
|
||||||
for c in n["children"]:
|
var node: Dictionary = stack.pop_back()
|
||||||
if reaches(c, table_id):
|
if (node["table"] as RollTable).id == table_id:
|
||||||
return true
|
return true
|
||||||
|
stack.append_array(node.get("children", []))
|
||||||
return false
|
return false
|
||||||
|
|
||||||
|
|
||||||
|
## The last sheet node reached in a tree, or {} (the result headline when a
|
||||||
|
## chain reaches a sheet card).
|
||||||
|
static func last_sheet(n: Dictionary) -> Dictionary:
|
||||||
|
var found := {}
|
||||||
|
if n.is_empty():
|
||||||
|
return found
|
||||||
|
var stack: Array = [n]
|
||||||
|
while not stack.is_empty():
|
||||||
|
var node: Dictionary = stack.pop_back()
|
||||||
|
if str(node.get("kind", "")) == RollTable.KIND_SHEET and not node.has("stop"):
|
||||||
|
found = node
|
||||||
|
var kids: Array = node.get("children", [])
|
||||||
|
for k in range(kids.size() - 1, -1, -1):
|
||||||
|
stack.append(kids[k])
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
## Marks every entry, pipe and reference pipe along the chain as lit. When
|
## Marks every entry, pipe and reference pipe along the chain as lit. When
|
||||||
## given, `texts` gets each lit entry's expanded text (entry key -> BBCode).
|
## given, `texts` gets each lit entry's expanded text (entry key -> BBCode).
|
||||||
|
## Iterative. A loop's pass and Afterwards nodes light their entries but no
|
||||||
|
## pipe (they aren't reached through one).
|
||||||
static func collect_lit(n: Dictionary, entries: Dictionary, pipes: Dictionary, texts: Dictionary = {}) -> void:
|
static func collect_lit(n: Dictionary, entries: Dictionary, pipes: Dictionary, texts: Dictionary = {}) -> void:
|
||||||
if n.is_empty() or n.has("stop"):
|
if n.is_empty():
|
||||||
return
|
return
|
||||||
var t: RollTable = n["table"]
|
var stack: Array = [n]
|
||||||
var e: TableEntry = n["entry"]
|
while not stack.is_empty():
|
||||||
entries[entry_key(t.id, e.id)] = true
|
var node: Dictionary = stack.pop_back()
|
||||||
texts[entry_key(t.id, e.id)] = str(n.get("summary", e.text))
|
if node.is_empty() or node.has("stop"):
|
||||||
for c in n["children"]:
|
continue
|
||||||
pipes[link_key(t.id, e.id, c)] = true
|
var t: RollTable = node["table"]
|
||||||
collect_lit(c, entries, pipes, texts)
|
var e: TableEntry = node["entry"]
|
||||||
|
entries[entry_key(t.id, e.id)] = true
|
||||||
|
texts[entry_key(t.id, e.id)] = str(node.get("summary", e.text))
|
||||||
|
var kids: Array = node["children"]
|
||||||
|
for c: Dictionary in kids:
|
||||||
|
if not (c.has("pass") or c.has("after")):
|
||||||
|
pipes[link_key(t.id, e.id, c)] = true
|
||||||
|
for k in range(kids.size() - 1, -1, -1):
|
||||||
|
stack.append(kids[k])
|
||||||
|
|
||||||
|
|
||||||
static func entry_key(table_id: String, entry_id: String) -> String:
|
static func entry_key(table_id: String, entry_id: String) -> String:
|
||||||
|
|
@ -287,3 +678,30 @@ static func ref_targets(board: TowerBoard, text: String) -> Array[String]:
|
||||||
if id != "" and not out.has(id):
|
if id != "" and not out.has(id):
|
||||||
out.append(id)
|
out.append(id)
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
## A context for showing values live (variable and sheet cards, previews):
|
||||||
|
## nothing is rolled or saved through it by the caller's intent, but dice in
|
||||||
|
## expressions still roll. `persistent` is the collection's variables.
|
||||||
|
static func live_context(board: TowerBoard, persistent: Dictionary) -> RollContext:
|
||||||
|
return new_context(board, RandomNumberGenerator.new(), persistent, {})
|
||||||
|
|
||||||
|
|
||||||
|
## Live display of a variable card: its current value as text, or its
|
||||||
|
## starting value (marked) when it isn't set yet.
|
||||||
|
## Returns {"text": String, "set": bool, "error": String}.
|
||||||
|
static func variable_display(board: TowerBoard, persistent: Dictionary, t: RollTable) -> Dictionary:
|
||||||
|
var ctx := live_context(board, persistent)
|
||||||
|
var v: Variant = ctx.get_value("@" + t.var_name)
|
||||||
|
if v != null:
|
||||||
|
return {"text": Expr.format_value(v), "set": true, "error": ""}
|
||||||
|
var r := t.initial_value(ctx)
|
||||||
|
return {"text": Expr.format_value(r["value"]), "set": false, "error": str(r["error"])}
|
||||||
|
|
||||||
|
|
||||||
|
## Live rendering of a sheet card's template with current values (BBCode with
|
||||||
|
## internal markers; [[references]] read as table names, nothing is rolled).
|
||||||
|
static func render_sheet(board: TowerBoard, persistent: Dictionary, t: RollTable) -> String:
|
||||||
|
if t.entries.is_empty():
|
||||||
|
return ""
|
||||||
|
return TextExpander.render(t.entries[0].text, live_context(board, persistent))
|
||||||
|
|
|
||||||
|
|
@ -47,14 +47,25 @@ func clear_deck(cid: String, tid: String) -> void:
|
||||||
|
|
||||||
|
|
||||||
# ---------- Persistent variables ----------
|
# ---------- Persistent variables ----------
|
||||||
# {name: {"value": String, "source": table_id}}
|
# {name: {"value": Variant (int, float or String), "source": table_id}}
|
||||||
|
# Numbers stay numbers: JSON gives whole numbers back as floats, so they are
|
||||||
|
# turned back into ints here.
|
||||||
|
|
||||||
func get_variables(cid: String) -> Dictionary:
|
func get_variables(cid: String) -> Dictionary:
|
||||||
var v: Variant = _section("variables").get(cid, {})
|
var v: Variant = _section("variables").get(cid, {})
|
||||||
return (v as Dictionary).duplicate(true) if v is Dictionary else {}
|
if not (v is Dictionary):
|
||||||
|
return {}
|
||||||
|
var out := (v as Dictionary).duplicate(true)
|
||||||
|
for k: Variant in out:
|
||||||
|
var rec: Variant = out[k]
|
||||||
|
if rec is Dictionary and (rec as Dictionary).has("value"):
|
||||||
|
rec["value"] = Expr.normalize(rec["value"])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
func set_variable(cid: String, var_name: String, value: String, source: String = "") -> void:
|
func set_variable(cid: String, var_name: String, value: Variant, source: String = "") -> void:
|
||||||
|
if not (value is int or value is float or value is String):
|
||||||
|
value = str(value)
|
||||||
_bucket("variables", cid)[var_name] = {"value": value, "source": source}
|
_bucket("variables", cid)[var_name] = {"value": value, "source": source}
|
||||||
_dirty = true
|
_dirty = true
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,8 @@ extends RefCounted
|
||||||
## ranged (dice) table it covers a span of die values such as 01–30.
|
## ranged (dice) table it covers a span of die values such as 01–30.
|
||||||
|
|
||||||
const MAX_PIPE_COUNT := 99
|
const MAX_PIPE_COUNT := 99
|
||||||
|
## Most times an expression pipe count (such as "@terms") may roll.
|
||||||
|
const MAX_EXPR_COUNT := 10000
|
||||||
|
|
||||||
var id: String = ""
|
var id: String = ""
|
||||||
var text: String = ""
|
var text: String = ""
|
||||||
|
|
@ -12,9 +14,13 @@ var details: String = ""
|
||||||
## Relative chance on a plain table; also the number of copies in card mode.
|
## Relative chance on a plain table; also the number of copies in card mode.
|
||||||
## 0 means it never comes up. Ignored on ranged tables.
|
## 0 means it never comes up. Ignored on ranged tables.
|
||||||
var weight: int = 1
|
var weight: int = 1
|
||||||
|
## Effect statements run when this entry is chosen (see Effects), before its
|
||||||
|
## text expands and its pipes follow. "" for none.
|
||||||
|
var effects: String = ""
|
||||||
## IDs of the tables this entry rolls on next (unique; one pipe per target).
|
## IDs of the tables this entry rolls on next (unique; one pipe per target).
|
||||||
var pipes: Array[String] = []
|
var pipes: Array[String] = []
|
||||||
## target table id -> how many times to roll it (missing = 1).
|
## target table id -> how many times to roll it (missing = 1): an int, or a
|
||||||
|
## String expression such as "@terms" or "1d3" evaluated when the pipe runs.
|
||||||
var pipe_count: Dictionary = {}
|
var pipe_count: Dictionary = {}
|
||||||
## target table id -> variable name to save the result under (missing = none).
|
## target table id -> variable name to save the result under (missing = none).
|
||||||
var pipe_save: Dictionary = {}
|
var pipe_save: Dictionary = {}
|
||||||
|
|
@ -33,9 +39,39 @@ func span() -> int:
|
||||||
return range_hi - range_lo + 1 if has_range else 1
|
return range_hi - range_lo + 1 if has_range else 1
|
||||||
|
|
||||||
|
|
||||||
## How many times the pipe to `target` rolls.
|
## How many times the pipe to `target` rolls. An expression count reads as 1
|
||||||
|
## here; see count_expr() and count_value().
|
||||||
func count_for(target: String) -> int:
|
func count_for(target: String) -> int:
|
||||||
return clampi(int(pipe_count.get(target, 1)), 1, MAX_PIPE_COUNT)
|
var c: Variant = pipe_count.get(target, 1)
|
||||||
|
if c is String:
|
||||||
|
return 1
|
||||||
|
return clampi(int(c), 1, MAX_PIPE_COUNT)
|
||||||
|
|
||||||
|
|
||||||
|
## The pipe's count expression, or "" when the count is a plain number.
|
||||||
|
func count_expr(target: String) -> String:
|
||||||
|
var c: Variant = pipe_count.get(target, 1)
|
||||||
|
return c if c is String else ""
|
||||||
|
|
||||||
|
|
||||||
|
## The count as typed: "3", or the expression ("@terms").
|
||||||
|
func count_text(target: String) -> String:
|
||||||
|
var e := count_expr(target)
|
||||||
|
return e if e != "" else str(count_for(target))
|
||||||
|
|
||||||
|
|
||||||
|
## How many times the pipe rolls in this roll: a plain count, or the
|
||||||
|
## expression evaluated now (0 and up; errors give 0). `log` (optional) gets an
|
||||||
|
## error line when the expression fails.
|
||||||
|
func count_value(target: String, ctx: RollContext, log: Array = []) -> int:
|
||||||
|
var e := count_expr(target)
|
||||||
|
if e == "":
|
||||||
|
return count_for(target)
|
||||||
|
var r := Expr.evaluate(e, ctx)
|
||||||
|
if r["error"] != "":
|
||||||
|
log.append({"text": "Pipe count %s: %s" % [e, r["error"]], "error": true})
|
||||||
|
return 0
|
||||||
|
return clampi(Expr.as_int(r, 0), 0, MAX_EXPR_COUNT)
|
||||||
|
|
||||||
|
|
||||||
## Variable name the pipe to `target` saves into, or "".
|
## Variable name the pipe to `target` saves into, or "".
|
||||||
|
|
@ -43,12 +79,23 @@ func save_for(target: String) -> String:
|
||||||
return str(pipe_save.get(target, ""))
|
return str(pipe_save.get(target, ""))
|
||||||
|
|
||||||
|
|
||||||
func set_pipe_count(target: String, n: int) -> void:
|
## Sets the count: an int (clamped 1..99), or a String that is either a whole
|
||||||
n = clampi(n, 1, MAX_PIPE_COUNT)
|
## number or an expression.
|
||||||
if n == 1:
|
func set_pipe_count(target: String, n: Variant) -> void:
|
||||||
|
if n is String:
|
||||||
|
var s := (n as String).strip_edges()
|
||||||
|
if s == "" or s.is_valid_int():
|
||||||
|
n = s.to_int() if s != "" else 1
|
||||||
|
else:
|
||||||
|
pipe_count[target] = s
|
||||||
|
return
|
||||||
|
if n is float:
|
||||||
|
n = int(n)
|
||||||
|
var k := clampi(int(n), 1, MAX_PIPE_COUNT)
|
||||||
|
if k == 1:
|
||||||
pipe_count.erase(target)
|
pipe_count.erase(target)
|
||||||
else:
|
else:
|
||||||
pipe_count[target] = n
|
pipe_count[target] = k
|
||||||
|
|
||||||
|
|
||||||
func set_pipe_save(target: String, name: String) -> void:
|
func set_pipe_save(target: String, name: String) -> void:
|
||||||
|
|
@ -59,8 +106,8 @@ func set_pipe_save(target: String, name: String) -> void:
|
||||||
pipe_save[target] = name
|
pipe_save[target] = name
|
||||||
|
|
||||||
|
|
||||||
## Adds a pipe if it isn't there already.
|
## Adds a pipe if it isn't there already. `count` is an int or an expression.
|
||||||
func add_pipe(target: String, count: int = 1, save_as: String = "") -> void:
|
func add_pipe(target: String, count: Variant = 1, save_as: String = "") -> void:
|
||||||
if not pipes.has(target):
|
if not pipes.has(target):
|
||||||
pipes.append(target)
|
pipes.append(target)
|
||||||
set_pipe_count(target, count)
|
set_pipe_count(target, count)
|
||||||
|
|
@ -80,16 +127,21 @@ func to_dict() -> Dictionary:
|
||||||
d["details"] = details
|
d["details"] = details
|
||||||
if weight != 1:
|
if weight != 1:
|
||||||
d["weight"] = weight
|
d["weight"] = weight
|
||||||
|
if effects != "":
|
||||||
|
d["effects"] = effects
|
||||||
if not pipes.is_empty():
|
if not pipes.is_empty():
|
||||||
var list: Array = []
|
var list: Array = []
|
||||||
for p in pipes:
|
for p in pipes:
|
||||||
|
var expr := count_expr(p)
|
||||||
var n := count_for(p)
|
var n := count_for(p)
|
||||||
var s := save_for(p)
|
var s := save_for(p)
|
||||||
if n == 1 and s == "":
|
if expr == "" and n == 1 and s == "":
|
||||||
list.append(p)
|
list.append(p)
|
||||||
else:
|
else:
|
||||||
var po := {"table": p}
|
var po := {"table": p}
|
||||||
if n != 1:
|
if expr != "":
|
||||||
|
po["count"] = expr
|
||||||
|
elif n != 1:
|
||||||
po["count"] = n
|
po["count"] = n
|
||||||
if s != "":
|
if s != "":
|
||||||
po["save_as"] = s
|
po["save_as"] = s
|
||||||
|
|
@ -104,11 +156,13 @@ static func from_dict(d: Dictionary) -> TableEntry:
|
||||||
var e := TableEntry.new(str(d.get("id", "")), str(d.get("text", "")))
|
var e := TableEntry.new(str(d.get("id", "")), str(d.get("text", "")))
|
||||||
e.details = str(d.get("details", ""))
|
e.details = str(d.get("details", ""))
|
||||||
e.weight = maxi(0, int(d.get("weight", 1)))
|
e.weight = maxi(0, int(d.get("weight", 1)))
|
||||||
|
e.effects = str(d.get("effects", ""))
|
||||||
for p: Variant in d.get("pipes", []):
|
for p: Variant in d.get("pipes", []):
|
||||||
if p is Dictionary:
|
if p is Dictionary:
|
||||||
var target := str(p.get("table", ""))
|
var target := str(p.get("table", ""))
|
||||||
if target != "":
|
if target != "":
|
||||||
e.add_pipe(target, int(p.get("count", 1)), str(p.get("save_as", "")))
|
var c: Variant = p.get("count", 1)
|
||||||
|
e.add_pipe(target, c if c is String else int(c), str(p.get("save_as", "")))
|
||||||
elif str(p) != "":
|
elif str(p) != "":
|
||||||
e.add_pipe(str(p))
|
e.add_pipe(str(p))
|
||||||
var r: Variant = d.get("range")
|
var r: Variant = d.get("range")
|
||||||
|
|
|
||||||
|
|
@ -9,8 +9,11 @@ extends RefCounted
|
||||||
## [[Table -> @var]] ...and save it as persistent variable "@var"
|
## [[Table -> @var]] ...and save it as persistent variable "@var"
|
||||||
## [[3x Gems]] roll 3 times, joined with ", "
|
## [[3x Gems]] roll 3 times, joined with ", "
|
||||||
## [[1d4 Coins]] roll 1d4 for the count (NdM, NdM+K, NdM-K)
|
## [[1d4 Coins]] roll 1d4 for the count (NdM, NdM+K, NdM-K)
|
||||||
## {var} {@var} insert a saved value
|
## {var} {@var} insert a saved value (numbers without ".0")
|
||||||
## {@var|Table} use the saved value, else roll on Table, save, insert
|
## {@var|Table} use the saved value, else roll on Table, save, insert
|
||||||
|
## {@skill_*} every set variable with that prefix, sorted:
|
||||||
|
## "Gun Combat 1, Pilot 0"
|
||||||
|
## {= expr} a computed value (see Expr), e.g. {= dm(@str)}
|
||||||
##
|
##
|
||||||
## Inserted pieces are wrapped in internal url tags so the UI can show hover
|
## Inserted pieces are wrapped in internal url tags so the UI can show hover
|
||||||
## pop-ups through RichTextLabel's meta_hover_started signal:
|
## pop-ups through RichTextLabel's meta_hover_started signal:
|
||||||
|
|
@ -19,17 +22,24 @@ extends RefCounted
|
||||||
## [url=missing:<name>]⚠ <name>[/url] a table that doesn't exist
|
## [url=missing:<name>]⚠ <name>[/url] a table that doesn't exist
|
||||||
## [url=unset:<name>]{<name>?}[/url] a variable that isn't set
|
## [url=unset:<name>]{<name>?}[/url] a variable that isn't set
|
||||||
## [url=deep:<id>]⚠ chain too deep[/url] the depth limit was reached
|
## [url=deep:<id>]⚠ chain too deep[/url] the depth limit was reached
|
||||||
|
## [url=error:expr]⚠ <message>[/url] a {= expr} that couldn't be worked out
|
||||||
|
## {@prefix_*} lists and {= expr} values are inserted as plain text.
|
||||||
##
|
##
|
||||||
## BBCode is untouched: known tags (including ones with parameters such as
|
## BBCode is untouched: known tags (including ones with parameters such as
|
||||||
## [url={"a":1}]) are copied as-is, and ordinary bracket text like [x] stays text.
|
## [url={"a":1}]) are copied as-is, and ordinary bracket text like [x] stays text.
|
||||||
## A reference's name can't contain "[" or "]", so "[[b]x[/b]]" is not one.
|
## A reference's name can't contain "[" or "]", so "[[b]x[/b]]" is not one.
|
||||||
## Use [lb] to write a literal "[[".
|
## Use [lb] to write a literal "[[".
|
||||||
|
##
|
||||||
|
## expand() is the plain form. expand_async() is the coroutine form the roller
|
||||||
|
## uses, so that a reference into a choice card can wait for the player.
|
||||||
|
## render() shows text live (sheet cards, prompts) without rolling anything.
|
||||||
|
|
||||||
## Upper limit for [[Nx Table]] and [[NdM Table]] counts.
|
## Upper limit for [[Nx Table]] and [[NdM Table]] counts.
|
||||||
const MAX_REPEAT := 100
|
const MAX_REPEAT := 100
|
||||||
const DEEP_TEXT := "⚠ chain too deep"
|
const DEEP_TEXT := "⚠ chain too deep"
|
||||||
|
|
||||||
const _VAR_PATTERN := "\\{(@?[A-Za-z_][A-Za-z0-9_]*)(?:\\|([^{}\\[\\]\\n]+))?\\}"
|
const _VAR_PATTERN := "\\{(@?[A-Za-z_][A-Za-z0-9_]*)(?:\\|([^{}\\[\\]\\n]+))?\\}"
|
||||||
|
const _LIST_PATTERN := "\\{@([A-Za-z0-9_]*)\\*\\}"
|
||||||
const _COUNT_PATTERN := "^(?:(\\d+)\\s*[x×]|(\\d*)[dD](\\d+)(?:\\s*([+-])\\s*(\\d+))?)\\s+(\\S.*)$"
|
const _COUNT_PATTERN := "^(?:(\\d+)\\s*[x×]|(\\d*)[dD](\\d+)(?:\\s*([+-])\\s*(\\d+))?)\\s+(\\S.*)$"
|
||||||
const _SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$"
|
const _SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$"
|
||||||
|
|
||||||
|
|
@ -40,7 +50,26 @@ static var _res: Dictionary = {}
|
||||||
## text: String the expanded BBCode, with open tags closed at the end
|
## text: String the expanded BBCode, with open tags closed at the end
|
||||||
## children: Array the result nodes rolled inline, in order (one per roll,
|
## children: Array the result nodes rolled inline, in order (one per roll,
|
||||||
## so [[3x Gems]] adds three)
|
## so [[3x Gems]] adds three)
|
||||||
|
## References roll through ctx.roll_table (or roll_table_async when it's set
|
||||||
|
## and never has to wait).
|
||||||
static func expand(text: String, ctx: RollContext) -> Dictionary:
|
static func expand(text: String, ctx: RollContext) -> Dictionary:
|
||||||
|
var r: Variant = Callable(TextExpander, "expand_async").call(text, ctx)
|
||||||
|
if r is Dictionary:
|
||||||
|
return r
|
||||||
|
push_warning("TextExpander.expand had to wait for a prompt; use expand_async.")
|
||||||
|
return {"text": "", "children": []}
|
||||||
|
|
||||||
|
|
||||||
|
## Shows text live, without rolling: variables, {@prefix_*} lists and {= expr}
|
||||||
|
## are filled in, and a [[reference]] reads as the table's name (in a table:
|
||||||
|
## marker) instead of a roll. For sheet cards, prompts and previews.
|
||||||
|
static func render(text: String, ctx: RollContext) -> String:
|
||||||
|
var r: Variant = Callable(TextExpander, "expand_async").call(text, ctx, true)
|
||||||
|
return str((r as Dictionary)["text"]) if r is Dictionary else ""
|
||||||
|
|
||||||
|
|
||||||
|
## Coroutine form of expand(). With `live`, nothing is rolled (see render()).
|
||||||
|
static func expand_async(text: String, ctx: RollContext, live: bool = false) -> Dictionary:
|
||||||
var out: String = ""
|
var out: String = ""
|
||||||
var children: Array = []
|
var children: Array = []
|
||||||
var i: int = 0
|
var i: int = 0
|
||||||
|
|
@ -51,7 +80,10 @@ static func expand(text: String, ctx: RollContext) -> Dictionary:
|
||||||
if i + 1 < n and text[i + 1] == "[":
|
if i + 1 < n and text[i + 1] == "[":
|
||||||
var ref: Dictionary = _ref_at(text, i)
|
var ref: Dictionary = _ref_at(text, i)
|
||||||
if not ref.is_empty():
|
if not ref.is_empty():
|
||||||
out += _expand_ref(ref, ctx, children)
|
if live:
|
||||||
|
out += _live_ref(ref, ctx)
|
||||||
|
else:
|
||||||
|
out += await _expand_ref(ref, ctx, children)
|
||||||
i = ref["end"]
|
i = ref["end"]
|
||||||
continue
|
continue
|
||||||
out += c
|
out += c
|
||||||
|
|
@ -63,9 +95,23 @@ static func expand(text: String, ctx: RollContext) -> Dictionary:
|
||||||
i += (tag["raw"] as String).length()
|
i += (tag["raw"] as String).length()
|
||||||
continue
|
continue
|
||||||
elif c == "{":
|
elif c == "{":
|
||||||
|
if i + 1 < n and text[i + 1] == "=":
|
||||||
|
var close := _expr_end(text, i + 2)
|
||||||
|
if close >= 0:
|
||||||
|
out += _expand_expr(text.substr(i + 2, close - i - 2), ctx)
|
||||||
|
i = close + 1
|
||||||
|
continue
|
||||||
|
var lm: RegExMatch = _re(_LIST_PATTERN).search(text, i)
|
||||||
|
if lm != null and lm.get_start() == i:
|
||||||
|
out += Formatter.close_open_tags(ctx.list_text(lm.get_string(1)))
|
||||||
|
i = lm.get_end()
|
||||||
|
continue
|
||||||
var m: RegExMatch = _re(_VAR_PATTERN).search(text, i)
|
var m: RegExMatch = _re(_VAR_PATTERN).search(text, i)
|
||||||
if m != null and m.get_start() == i:
|
if m != null and m.get_start() == i:
|
||||||
out += _expand_var(m.get_string(1), m.get_string(2).strip_edges(), ctx, children)
|
if live:
|
||||||
|
out += _live_var(m.get_string(1), ctx)
|
||||||
|
else:
|
||||||
|
out += await _expand_var(m.get_string(1), m.get_string(2).strip_edges(), ctx, children)
|
||||||
i = m.get_end()
|
i = m.get_end()
|
||||||
continue
|
continue
|
||||||
out += c
|
out += c
|
||||||
|
|
@ -73,6 +119,59 @@ static func expand(text: String, ctx: RollContext) -> Dictionary:
|
||||||
return {"text": Formatter.close_open_tags(out), "children": children}
|
return {"text": Formatter.close_open_tags(out), "children": children}
|
||||||
|
|
||||||
|
|
||||||
|
## Index of the "}" closing a {= expr} that starts at `from`, outside quotes;
|
||||||
|
## -1 if there isn't one on the same line.
|
||||||
|
static func _expr_end(text: String, from: int) -> int:
|
||||||
|
var quote := ""
|
||||||
|
for k in range(from, text.length()):
|
||||||
|
var c := text[k]
|
||||||
|
if quote != "":
|
||||||
|
if c == quote:
|
||||||
|
quote = ""
|
||||||
|
elif c == "\"" or c == "'":
|
||||||
|
quote = c
|
||||||
|
elif c == "\n":
|
||||||
|
return -1
|
||||||
|
elif c == "}":
|
||||||
|
return k
|
||||||
|
return -1
|
||||||
|
|
||||||
|
|
||||||
|
static func _expand_expr(src: String, ctx: RollContext) -> String:
|
||||||
|
var r := Expr.evaluate(src.strip_edges(), ctx)
|
||||||
|
if r["error"] != "":
|
||||||
|
return error_marker(str(r["error"]))
|
||||||
|
return Formatter.close_open_tags(Expr.format_value(r["value"]))
|
||||||
|
|
||||||
|
|
||||||
|
## The marker for a {= expr} that failed.
|
||||||
|
static func error_marker(message: String) -> String:
|
||||||
|
return "[url=error:expr]⚠ %s[/url]" % Formatter.escape_literal(message)
|
||||||
|
|
||||||
|
|
||||||
|
static func _live_ref(ref: Dictionary, ctx: RollContext) -> String:
|
||||||
|
var name: String = ref["name"]
|
||||||
|
var id: String = ctx.resolve(name)
|
||||||
|
if id == "":
|
||||||
|
var count: Dictionary = _parse_count(name)
|
||||||
|
if not count.is_empty():
|
||||||
|
name = count["name"]
|
||||||
|
id = ctx.resolve(name)
|
||||||
|
if id == "":
|
||||||
|
return missing_marker(name)
|
||||||
|
var shown := name
|
||||||
|
if ctx.board != null and ctx.board.get_table(id) != null:
|
||||||
|
shown = ctx.board.get_table(id).name
|
||||||
|
return "[url=table:%s]%s[/url]" % [id, Formatter.close_open_tags(shown)]
|
||||||
|
|
||||||
|
|
||||||
|
static func _live_var(name: String, ctx: RollContext) -> String:
|
||||||
|
var value: Variant = ctx.lookup(name)
|
||||||
|
if value != null:
|
||||||
|
return "[url=var:%s]%s[/url]" % [name, Formatter.close_open_tags(str(value))]
|
||||||
|
return unset_marker(name)
|
||||||
|
|
||||||
|
|
||||||
## Names of the tables referenced in `text`, without rolling, in order of first
|
## Names of the tables referenced in `text`, without rolling, in order of first
|
||||||
## appearance and without duplicates. Covers [[...]] references (minus any count
|
## appearance and without duplicates. Covers [[...]] references (minus any count
|
||||||
## prefix and "-> var" part) and the table in {@var|Table}. With a resolver
|
## prefix and "-> var" part) and the table in {@var|Table}. With a resolver
|
||||||
|
|
@ -207,11 +306,13 @@ static func _expand_ref(ref: Dictionary, ctx: RollContext, children: Array) -> S
|
||||||
var pieces: PackedStringArray = []
|
var pieces: PackedStringArray = []
|
||||||
var plain: PackedStringArray = []
|
var plain: PackedStringArray = []
|
||||||
for _k in times:
|
for _k in times:
|
||||||
var piece: Dictionary = _roll_one(id, ctx, children)
|
if ctx.halted != "":
|
||||||
|
break
|
||||||
|
var piece: Dictionary = await _roll_one(id, ctx, children)
|
||||||
pieces.append(piece["text"])
|
pieces.append(piece["text"])
|
||||||
plain.append(piece["value"])
|
plain.append(piece["value"])
|
||||||
var save_as: String = ref["save"]
|
var save_as: String = ref["save"]
|
||||||
if save_as != "":
|
if save_as != "" and ctx.halted == "":
|
||||||
ctx.save(save_as, ", ".join(plain), id)
|
ctx.save(save_as, ", ".join(plain), id)
|
||||||
return ", ".join(pieces)
|
return ", ".join(pieces)
|
||||||
|
|
||||||
|
|
@ -225,7 +326,9 @@ static func _expand_var(name: String, table: String, ctx: RollContext, children:
|
||||||
var id: String = ctx.resolve(table)
|
var id: String = ctx.resolve(table)
|
||||||
if id == "":
|
if id == "":
|
||||||
return missing_marker(table)
|
return missing_marker(table)
|
||||||
var piece: Dictionary = _roll_one(id, ctx, children)
|
if ctx.halted != "":
|
||||||
|
return unset_marker(name)
|
||||||
|
var piece: Dictionary = await _roll_one(id, ctx, children)
|
||||||
if not piece["rolled"]:
|
if not piece["rolled"]:
|
||||||
return piece["text"]
|
return piece["text"]
|
||||||
ctx.save(name, piece["value"], id)
|
ctx.save(name, piece["value"], id)
|
||||||
|
|
@ -238,19 +341,23 @@ static func _roll_one(id: String, ctx: RollContext, children: Array) -> Dictiona
|
||||||
if ctx.depth > ctx.max_depth:
|
if ctx.depth > ctx.max_depth:
|
||||||
var deep: String = deep_marker(id)
|
var deep: String = deep_marker(id)
|
||||||
return {"text": deep, "value": DEEP_TEXT, "rolled": false}
|
return {"text": deep, "value": DEEP_TEXT, "rolled": false}
|
||||||
var node: Dictionary = ctx.roll(id)
|
var node: Dictionary = await ctx.roll_async(id)
|
||||||
if node.is_empty():
|
if node.is_empty():
|
||||||
var missing: String = missing_marker(id)
|
var missing: String = missing_marker(id)
|
||||||
return {"text": missing, "value": "", "rolled": false}
|
return {"text": missing, "value": "", "rolled": false}
|
||||||
children.append(node)
|
children.append(node)
|
||||||
var summary: String = Formatter.close_open_tags(str(node.get("summary", "")))
|
var summary: String = Formatter.close_open_tags(str(node.get("summary", "")))
|
||||||
|
var value: String = Formatter.to_export_bbcode(summary)
|
||||||
|
if node.has("answer"):
|
||||||
|
value = Expr.format_value(node["answer"])
|
||||||
return {
|
return {
|
||||||
"text": "[url=table:%s]%s[/url]" % [id, summary],
|
"text": "[url=table:%s]%s[/url]" % [id, summary],
|
||||||
"value": Formatter.to_export_bbcode(summary),
|
"value": value,
|
||||||
"rolled": true,
|
"rolled": true,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
static func _re(pattern: String) -> RegEx:
|
static func _re(pattern: String) -> RegEx:
|
||||||
if not _res.has(pattern):
|
if not _res.has(pattern):
|
||||||
var re := RegEx.new()
|
var re := RegEx.new()
|
||||||
|
|
|
||||||
|
|
@ -7,9 +7,13 @@ extends RefCounted
|
||||||
## Canonical collection form:
|
## Canonical collection form:
|
||||||
## {"format_version": 2, "id", "name", "tables": [table, ...]}
|
## {"format_version": 2, "id", "name", "tables": [table, ...]}
|
||||||
## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode],
|
## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode],
|
||||||
## [deck_empty], entries
|
## [deck_empty], [kind], [choice], [prompt], [save_as], [min], [max],
|
||||||
## entry: id, text, [details], [weight], [range], [pipes]
|
## [loop], [loop_expr], [var_name], [var_type], [initial], entries
|
||||||
## pipe: a table id String, or {"table": id, "count": n, "save_as": name}
|
## entry: id, text, [details], [weight], [range], [effects], [pipes]
|
||||||
|
## pipe: a table id String, or {"table": id, "count": n or "<expression>",
|
||||||
|
## "save_as": name}
|
||||||
|
## The logic-card keys (docs/LOGIC.md §9) are Strings, and are left out when
|
||||||
|
## they have their default value.
|
||||||
|
|
||||||
const FORMAT_VERSION := 2
|
const FORMAT_VERSION := 2
|
||||||
|
|
||||||
|
|
@ -118,6 +122,9 @@ static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Di
|
||||||
t5["name"] = clean.call(str(t5["name"]))
|
t5["name"] = clean.call(str(t5["name"]))
|
||||||
if t5.has("details"):
|
if t5.has("details"):
|
||||||
t5["details"] = clean.call(str(t5["details"]))
|
t5["details"] = clean.call(str(t5["details"]))
|
||||||
|
for key in ["prompt", "initial"]:
|
||||||
|
if t5.has(key):
|
||||||
|
t5[key] = clean.call(str(t5[key]))
|
||||||
if t5.has("tags"):
|
if t5.has("tags"):
|
||||||
var tags: Array = []
|
var tags: Array = []
|
||||||
for tag in t5["tags"]:
|
for tag in t5["tags"]:
|
||||||
|
|
@ -144,6 +151,8 @@ static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Di
|
||||||
ed["text"] = clean.call(str(ed["text"]))
|
ed["text"] = clean.call(str(ed["text"]))
|
||||||
if ed.has("details"):
|
if ed.has("details"):
|
||||||
ed["details"] = clean.call(str(ed["details"]))
|
ed["details"] = clean.call(str(ed["details"]))
|
||||||
|
if ed.has("effects"):
|
||||||
|
ed["effects"] = clean.call(str(ed["effects"]))
|
||||||
if ed.has("range"):
|
if ed.has("range"):
|
||||||
var r: Array = ed["range"]
|
var r: Array = ed["range"]
|
||||||
if int(r[0]) > int(r[1]):
|
if int(r[0]) > int(r[1]):
|
||||||
|
|
@ -220,6 +229,18 @@ static func _canon_table(td: Dictionary) -> Dictionary:
|
||||||
var v: Variant = td.get(key)
|
var v: Variant = td.get(key)
|
||||||
if v != null and not (v is bool and not v) and not (v is String and v == ""):
|
if v != null and not (v is bool and not v) and not (v is String and v == ""):
|
||||||
t[key] = 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 := {"choice": "pick", "prompt": "", "save_as": "", "min": "0", "max": "99",
|
||||||
|
"loop": "times", "loop_expr": "", "var_name": "", "var_type": "number", "initial": ""}
|
||||||
|
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 entries: Array = []
|
var entries: Array = []
|
||||||
var src_entries: Variant = td.get("entries", [])
|
var src_entries: Variant = td.get("entries", [])
|
||||||
if src_entries is Array:
|
if src_entries is Array:
|
||||||
|
|
@ -243,6 +264,9 @@ static func _canon_entry(ev: Variant) -> Dictionary:
|
||||||
var r: Variant = ed.get("range")
|
var r: Variant = ed.get("range")
|
||||||
if r is Array and (r as Array).size() == 2:
|
if r is Array and (r as Array).size() == 2:
|
||||||
e["range"] = [int(_num(r[0], 0)), int(_num(r[1], 0))]
|
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 src_pipes: Variant = ed.get("pipes", ed.get("triggers", []))
|
var src_pipes: Variant = ed.get("pipes", ed.get("triggers", []))
|
||||||
var pipes: Array = []
|
var pipes: Array = []
|
||||||
if src_pipes is Array:
|
if src_pipes is Array:
|
||||||
|
|
@ -252,7 +276,11 @@ static func _canon_entry(ev: Variant) -> Dictionary:
|
||||||
elif p is Dictionary and str(p.get("table", "")) != "":
|
elif p is Dictionary and str(p.get("table", "")) != "":
|
||||||
var np := {"table": str(p["table"])}
|
var np := {"table": str(p["table"])}
|
||||||
if p.has("count"):
|
if p.has("count"):
|
||||||
np["count"] = int(_num(p["count"], 1))
|
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", "")) != "":
|
if str(p.get("save_as", "")) != "":
|
||||||
np["save_as"] = str(p["save_as"])
|
np["save_as"] = str(p["save_as"])
|
||||||
pipes.append(np)
|
pipes.append(np)
|
||||||
|
|
@ -294,17 +322,26 @@ static func unique_id(base: String, used: Dictionary) -> String:
|
||||||
return id
|
return id
|
||||||
|
|
||||||
|
|
||||||
## Normalizes a pipe (String or Dictionary) to {"table", "count", "save_as"}.
|
## Normalizes a pipe (String or Dictionary) to {"table", "count", "save_as",
|
||||||
|
## "count_expr"}. An expression count ("@terms") reads as count 1, with the
|
||||||
|
## expression in "count_expr" ("" otherwise).
|
||||||
static func pipe_info(p: Variant) -> Dictionary:
|
static func pipe_info(p: Variant) -> Dictionary:
|
||||||
if p is Dictionary:
|
if p is Dictionary:
|
||||||
return {"table": str(p.get("table", "")), "count": int(_num(p.get("count", 1), 1)), "save_as": str(p.get("save_as", ""))}
|
var c: Variant = p.get("count", 1)
|
||||||
return {"table": str(p), "count": 1, "save_as": ""}
|
var expr := ""
|
||||||
|
if c is String and _num(c, null) == null and (c as String).strip_edges() != "":
|
||||||
|
expr = (c as String).strip_edges()
|
||||||
|
return {"table": str(p.get("table", "")), "count": int(_num(c, 1)), "save_as": str(p.get("save_as", "")), "count_expr": expr}
|
||||||
|
return {"table": str(p), "count": 1, "save_as": "", "count_expr": ""}
|
||||||
|
|
||||||
|
|
||||||
## Edge label for a pipe: "" (plain), "×2", "→ weapon" or "×2 → weapon".
|
## Edge label for a pipe: "" (plain), "×2", "→ weapon" or "×2 → weapon"
|
||||||
|
## ("×@terms" for an expression count).
|
||||||
static func pipe_label(info: Dictionary) -> String:
|
static func pipe_label(info: Dictionary) -> String:
|
||||||
var parts: Array[String] = []
|
var parts: Array[String] = []
|
||||||
if int(info["count"]) != 1:
|
if str(info.get("count_expr", "")) != "":
|
||||||
|
parts.append("×" + str(info["count_expr"]))
|
||||||
|
elif int(info["count"]) != 1:
|
||||||
parts.append("×%d" % int(info["count"]))
|
parts.append("×%d" % int(info["count"]))
|
||||||
if str(info["save_as"]) != "":
|
if str(info["save_as"]) != "":
|
||||||
parts.append("→ " + str(info["save_as"]))
|
parts.append("→ " + str(info["save_as"]))
|
||||||
|
|
|
||||||
|
|
@ -148,7 +148,8 @@ func _test_depth_limit() -> void:
|
||||||
var deepest: Dictionary = steps[steps.size() - 1]
|
var deepest: Dictionary = steps[steps.size() - 1]
|
||||||
_check((deepest["text"] as String).contains(TextExpander.DEEP_TEXT), "deepest text shows the chain-too-deep marker")
|
_check((deepest["text"] as String).contains(TextExpander.DEEP_TEXT), "deepest text shows the chain-too-deep marker")
|
||||||
_check(int(deepest["depth"]) == Roller.MAX_DEPTH, "deepest step is at the limit")
|
_check(int(deepest["depth"]) == Roller.MAX_DEPTH, "deepest step is at the limit")
|
||||||
# Mixed: pipes and references count the same depth.
|
# Mixed: pipes no longer count toward the depth limit, but the references
|
||||||
|
# still nest at most MAX_DEPTH deep, so the chain ends.
|
||||||
var ta := _table("ta", "TA", ["[[TB]]"])
|
var ta := _table("ta", "TA", ["[[TB]]"])
|
||||||
var tb := _table("tb", "TB", ["pipe"])
|
var tb := _table("tb", "TB", ["pipe"])
|
||||||
tb.entries[0].add_pipe("ta")
|
tb.entries[0].add_pipe("ta")
|
||||||
|
|
@ -157,7 +158,11 @@ func _test_depth_limit() -> void:
|
||||||
var worst := 0
|
var worst := 0
|
||||||
for s in Roller.flatten(n2, []):
|
for s in Roller.flatten(n2, []):
|
||||||
worst = maxi(worst, int(s["depth"]))
|
worst = maxi(worst, int(s["depth"]))
|
||||||
_check(worst <= Roller.MAX_DEPTH + 1, "mixed pipes and refs never go past the limit (%d)" % worst)
|
var inline := 0
|
||||||
|
for s in Roller.flatten(n2, []):
|
||||||
|
if s.get("inline", false):
|
||||||
|
inline += 1
|
||||||
|
_check(inline <= Roller.MAX_DEPTH and worst <= 2 * Roller.MAX_DEPTH + 1, "mixed pipes and refs stop at the reference limit (%d refs, depth %d)" % [inline, worst])
|
||||||
|
|
||||||
|
|
||||||
func _test_missing_and_unset() -> void:
|
func _test_missing_and_unset() -> void:
|
||||||
|
|
|
||||||
730
tests/test_logic.gd
Normal file
730
tests/test_logic.gd
Normal file
|
|
@ -0,0 +1,730 @@
|
||||||
|
extends SceneTree
|
||||||
|
## Headless checks for logic cards (docs/LOGIC.md): expressions, effects,
|
||||||
|
## variables, choice / loop / variable / sheet cards, the action limit, long
|
||||||
|
## chains and the file format.
|
||||||
|
## Run: godot --headless --path . -s res://tests/test_logic.gd
|
||||||
|
|
||||||
|
var _failures := 0
|
||||||
|
|
||||||
|
|
||||||
|
func _init() -> void:
|
||||||
|
_test_expressions()
|
||||||
|
_test_effects()
|
||||||
|
_test_variables()
|
||||||
|
await _test_choices()
|
||||||
|
_test_loops()
|
||||||
|
await _test_loop_from_answer()
|
||||||
|
_test_cycles()
|
||||||
|
_test_long_chain()
|
||||||
|
_test_expression_dice()
|
||||||
|
_test_sheet()
|
||||||
|
_test_json()
|
||||||
|
await _test_character()
|
||||||
|
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
|
||||||
|
quit(1 if _failures else 0)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- helpers
|
||||||
|
|
||||||
|
func _rng(seed_value: int) -> RandomNumberGenerator:
|
||||||
|
var r := RandomNumberGenerator.new()
|
||||||
|
r.seed = seed_value
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
func _board(tables: Array) -> TowerBoard:
|
||||||
|
var b := TowerBoard.new()
|
||||||
|
b.id = "logic-test"
|
||||||
|
for t in tables:
|
||||||
|
b.tables.append(t)
|
||||||
|
return b
|
||||||
|
|
||||||
|
|
||||||
|
func _table(id: String, texts: Array) -> RollTable:
|
||||||
|
var t := RollTable.new(id, id.capitalize())
|
||||||
|
for i in texts.size():
|
||||||
|
t.entries.append(TableEntry.new("e%d" % (i + 1), texts[i]))
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
|
func _ctx(vars: Dictionary = {}, board: TowerBoard = null) -> RollContext:
|
||||||
|
var ctx := RollContext.new(vars, _rng(1))
|
||||||
|
ctx.board = board
|
||||||
|
return ctx
|
||||||
|
|
||||||
|
|
||||||
|
func _ev(src: String, ctx: RollContext = null) -> Variant:
|
||||||
|
return Expr.evaluate(src, ctx)["value"]
|
||||||
|
|
||||||
|
|
||||||
|
func _var(vars: Dictionary, name: String) -> Variant:
|
||||||
|
var v: Variant = vars.get(name)
|
||||||
|
return (v as Dictionary).get("value") if v is Dictionary else null
|
||||||
|
|
||||||
|
|
||||||
|
func _vars(pairs: Dictionary) -> Dictionary:
|
||||||
|
var out := {}
|
||||||
|
for k: String in pairs:
|
||||||
|
out[k] = {"value": pairs[k], "source": ""}
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
func _texts(steps: Array) -> Array:
|
||||||
|
var out := []
|
||||||
|
for s: Dictionary in steps:
|
||||||
|
out.append(Formatter.strip_tags(str(s["text"])))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
## A prompt hook that answers from a script: kind -> reply (or a Callable
|
||||||
|
## taking the request). Records every request in `log`.
|
||||||
|
func _scripted(answers: Dictionary, log: Array) -> Callable:
|
||||||
|
return func(req: Dictionary) -> Variant:
|
||||||
|
log.append(req)
|
||||||
|
var a: Variant = answers.get(str(req["kind"]))
|
||||||
|
if a is Callable:
|
||||||
|
return (a as Callable).call(req)
|
||||||
|
return a
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- expressions
|
||||||
|
|
||||||
|
func _test_expressions() -> void:
|
||||||
|
_eq(_ev("1 + 2 * 3"), 7, "arithmetic")
|
||||||
|
_eq(_ev("7 / 2"), 3, "whole-number division")
|
||||||
|
_eq(_ev("floor(2.5) + 1"), 3, "whole float results come back as ints")
|
||||||
|
_check(_ev("floor(2.5)") is int, "floor() result is an int")
|
||||||
|
_eq(_ev("min(3, 2) + max(1, 4) + clamp(9, 0, 5) + abs(-2)"), 13, "built-in functions")
|
||||||
|
_eq(_ev("not (1 = 2) and true"), true, "a lone = means equals; not/and")
|
||||||
|
_eq(Expr.rewrite("@a = 1"), "_v0 == 1", "rewrite turns = into ==")
|
||||||
|
_eq(_ev("1 == 1 && !false || false"), true, "&& || !")
|
||||||
|
_eq(_ev("\"ps\" in \"Psionic\""), false, "in is case-sensitive text contains")
|
||||||
|
_eq(_ev("\"Psi\" in \"Psionic\""), true, "in finds text")
|
||||||
|
# Dice.
|
||||||
|
var rng_ctx := _ctx()
|
||||||
|
var specs := {"2d6": [2, 12], "d20": [1, 20], "3D": [3, 18], "D3": [1, 3], "2D": [2, 12], "1d6 + 10": [11, 16]}
|
||||||
|
for src: String in specs:
|
||||||
|
var lo := 999
|
||||||
|
var hi := -999
|
||||||
|
for k in 400:
|
||||||
|
var v: int = _ev(src, rng_ctx)
|
||||||
|
lo = mini(lo, v)
|
||||||
|
hi = maxi(hi, v)
|
||||||
|
_check(lo == specs[src][0] and hi == specs[src][1], "%s rolls %d..%d (saw %d..%d)" % [src, specs[src][0], specs[src][1], lo, hi])
|
||||||
|
var seen := {}
|
||||||
|
for k in 50:
|
||||||
|
seen[_ev("2d6 - 2d6", rng_ctx)] = true
|
||||||
|
_check(seen.size() > 3, "every die in an expression is rolled fresh")
|
||||||
|
_check(Expr.check("1000d6") != "", "an absurd dice count is an error, not a hang")
|
||||||
|
# dm().
|
||||||
|
var dms := {0: -3, 1: -2, 2: -2, 3: -1, 5: -1, 6: 0, 8: 0, 9: 1, 11: 1, 12: 2, 14: 2, 15: 3, 20: 3}
|
||||||
|
for x: int in dms:
|
||||||
|
_eq(_ev("dm(%d)" % x), dms[x], "dm(%d)" % x)
|
||||||
|
var vars := _vars({"str": 9, "traits": "Psionic, Gun Combat", "skill_pilot": 0, "skill_gun_combat": 1, "name": "Aslan", "num_text": "12"})
|
||||||
|
var ctx := _ctx(vars)
|
||||||
|
_eq(_ev("dm(@str)", ctx), 1, "dm(@str)")
|
||||||
|
_eq(_ev("has(@traits, \"gun combat\")", ctx), true, "has() matches items case-insensitively")
|
||||||
|
_eq(_ev("has(@traits, \"Gun\")", ctx), false, "has() matches whole items")
|
||||||
|
_eq(_ev("count(\"skill_\")", ctx), 2, "count(prefix)")
|
||||||
|
_eq(_ev("count(@skill_*)", ctx), 2, "count(@prefix_*)")
|
||||||
|
_eq(_ev("@str = 9", ctx), true, "@var = n")
|
||||||
|
_eq(_ev("@STR >= 9 and @str < 10", ctx), true, "@names are case-insensitive")
|
||||||
|
_eq(_ev("@name == \"Aslan\"", ctx), true, "text comparison")
|
||||||
|
_eq(_ev("@num_text + 1", ctx), 13, "number-like text reads as a number")
|
||||||
|
# Unset variables.
|
||||||
|
_eq(_ev("@nope + 1", ctx), 1, "unset reads as 0 in arithmetic")
|
||||||
|
_eq(_ev("@nope + \"x\"", ctx), "x", "unset reads as \"\" next to text")
|
||||||
|
_eq(_ev("@nope == \"\"", ctx), true, "unset equals \"\"")
|
||||||
|
_eq(_ev("@nope == 0", ctx), true, "unset equals 0")
|
||||||
|
_eq(_ev("missing_chain + 2", ctx), 2, "an unset chain variable reads as 0")
|
||||||
|
ctx.chain_vars["answer"] = 4
|
||||||
|
_eq(_ev("answer * 2", ctx), 8, "bare names read chain variables")
|
||||||
|
# Errors are values.
|
||||||
|
for bad in ["1 +", "\"abc", "(1", "@", "nosuchfn(1)", "\"a\" - 1", ""]:
|
||||||
|
var r := Expr.evaluate(bad, ctx)
|
||||||
|
_check(r["error"] != "" and r["value"] == null, "error reported for %s (%s)" % [bad, r["error"]])
|
||||||
|
_check(Expr.check("2d6 + dm(@end)") == "", "check() accepts a good expression")
|
||||||
|
_check(Expr._cache.has("2d6 + dm(@end)"), "parsed expressions are cached")
|
||||||
|
_eq(Expr.format_value(9.0), "9", "format: no .0")
|
||||||
|
_eq(Expr.format_value(2.5), "2.5", "format: decimals kept")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- effects
|
||||||
|
|
||||||
|
func _test_effects() -> void:
|
||||||
|
var str_card := RollTable.create(RollTable.KIND_VARIABLE, "v_str", "STR")
|
||||||
|
str_card.var_name = "str"
|
||||||
|
str_card.initial = "7"
|
||||||
|
var vacc := RollTable.create(RollTable.KIND_VARIABLE, "v_vacc", "Vacc Suit")
|
||||||
|
vacc.var_name = "skill_vacc_suit"
|
||||||
|
var board := _board([str_card, vacc])
|
||||||
|
var vars := {}
|
||||||
|
var ctx := _ctx(vars, board)
|
||||||
|
var log := Effects.run("@str = 9", ctx, "src")
|
||||||
|
_eq(_var(vars, "str"), 9, "= sets a number")
|
||||||
|
_check(_var(vars, "str") is int, "the value is an int")
|
||||||
|
_eq(Effects.log_text(log), PackedStringArray(["STR = 9"]), "log uses the variable card's name")
|
||||||
|
_eq(vars["str"]["source"], "src", "source table is kept")
|
||||||
|
_check(ctx.persistent_changed, "persistent_changed is set")
|
||||||
|
log = Effects.run("@n += 2; @n -= 5\n@n *= 3", ctx)
|
||||||
|
_eq(_var(vars, "n"), -9, "+= -= *= on numbers (unset counts as 0)")
|
||||||
|
_eq(Effects.log_text(log), PackedStringArray(["N +2 → 2", "N -5 → -3", "N ×3 → -9"]), "number log lines")
|
||||||
|
Effects.run("@n /= 2", ctx)
|
||||||
|
_eq(_var(vars, "n"), -5, "/= rounds down")
|
||||||
|
Effects.run("@m = 7; @m /= 2", ctx)
|
||||||
|
_eq(_var(vars, "m"), 3, "7 /= 2 is 3")
|
||||||
|
log = Effects.run("@skill_pilot += 1", ctx)
|
||||||
|
_eq(Effects.log_text(log), PackedStringArray(["Skill Pilot +1 → 1"]), "unset += 1 gives 1")
|
||||||
|
Effects.run("@skill_vacc_suit = max(@skill_vacc_suit, 0)", ctx)
|
||||||
|
_eq(_var(vars, "skill_vacc_suit"), 0, "gain at level 0")
|
||||||
|
# Text and lists.
|
||||||
|
Effects.run("@traits += \"Psionic\"", ctx)
|
||||||
|
_eq(_var(vars, "traits"), "Psionic", "+= text on unset")
|
||||||
|
Effects.run("@traits += \"psionic\"", ctx)
|
||||||
|
_eq(_var(vars, "traits"), "Psionic", "+= doesn't add an item twice")
|
||||||
|
log = Effects.run("@traits += \"Brave\"", ctx)
|
||||||
|
_eq(_var(vars, "traits"), "Psionic, Brave", "+= appends \", item\"")
|
||||||
|
_eq(Effects.log_text(log), PackedStringArray(["Traits + Brave → Psionic, Brave"]), "list log line")
|
||||||
|
Effects.run("@traits -= \"PSIONIC\"", ctx)
|
||||||
|
_eq(_var(vars, "traits"), "Brave", "-= removes the item")
|
||||||
|
Effects.run("@traits -= \"Brave\"", ctx)
|
||||||
|
_eq(_var(vars, "traits"), "", "-= the last item leaves empty text")
|
||||||
|
Effects.run("@name = \"Aslan\"", ctx)
|
||||||
|
_eq(_var(vars, "name"), "Aslan", "= sets text")
|
||||||
|
log = Effects.run("@name *= 2", ctx)
|
||||||
|
_check(log[0].get("error", false), "*= on text is an error")
|
||||||
|
Effects.run("hero = \"Mira\"", ctx)
|
||||||
|
_eq(ctx.chain_vars.get("hero"), "Mira", "a target without @ is a chain variable")
|
||||||
|
# reset.
|
||||||
|
Effects.run("@str = 12; reset @str", ctx)
|
||||||
|
_eq(_var(vars, "str"), 7, "reset goes back to the starting value")
|
||||||
|
Effects.run("@tmp = 1; reset @tmp", ctx)
|
||||||
|
_check(not vars.has("tmp"), "reset deletes an undeclared variable")
|
||||||
|
Effects.run("@skill_gun = 2; @skill_vacc_suit = 3", ctx)
|
||||||
|
log = Effects.run("reset @skill_*", ctx)
|
||||||
|
_check(not vars.has("skill_pilot") and not vars.has("skill_gun"), "reset @prefix_* deletes undeclared ones")
|
||||||
|
_eq(_var(vars, "skill_vacc_suit"), 0, "reset @prefix_* resets declared ones")
|
||||||
|
_check(not log[0].get("error", false) and str(log[0]["text"]).begins_with("Reset @skill_*"), "reset log: %s" % str(log))
|
||||||
|
# Bad statements don't stop the rest.
|
||||||
|
log = Effects.run("@x == 3; garbage; @y = (1; @z = 5", ctx)
|
||||||
|
_eq(log.size(), 4, "one log line per statement")
|
||||||
|
_check(log[0].get("error", false) and log[1].get("error", false) and log[2].get("error", false), "bad statements are errors")
|
||||||
|
_eq(_var(vars, "z"), 5, "statements after an error still run")
|
||||||
|
# Validation for the editor.
|
||||||
|
var probs := Effects.validate("@a = 1\n@b += (\nreset @c;reset c")
|
||||||
|
_eq(probs.size(), 2, "validate finds the two bad statements: %s" % str(probs))
|
||||||
|
_check(probs.size() == 2 and probs[0]["index"] == 1 and probs[1]["index"] == 3, "validate reports statement indexes")
|
||||||
|
_check(Effects.validate("@str = 2d6; @age *= 2; reset @skill_*").is_empty(), "good effects validate clean")
|
||||||
|
_eq(Effects.split("@a = \"x;y\"; @b = 1"), ["@a = \"x;y\"", "@b = 1"] as Array[String], "; inside quotes doesn't split")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- variables
|
||||||
|
|
||||||
|
func _test_variables() -> void:
|
||||||
|
var ctx := _ctx(_vars({"skill_pilot": 0, "skill_gun_combat": 1, "skill_zero_g": 2, "str": 7}))
|
||||||
|
var list := ctx.list_vars("@skill_*")
|
||||||
|
_eq(list.size(), 3, "list_vars by prefix")
|
||||||
|
_check(list.size() == 3 and list[0]["label"] == "Gun Combat" and list[2]["label"] == "Zero G", "labels are title-cased and sorted")
|
||||||
|
_eq(ctx.list_text("skill_"), "Gun Combat 1, Pilot 0, Zero G 2", "list_text")
|
||||||
|
_eq(RollContext.vars_with_prefix(ctx.persistent_vars, "s").size(), 4, "vars_with_prefix works on plain dictionaries")
|
||||||
|
# StateStore keeps numbers as numbers.
|
||||||
|
var dir := "user://test_logic_state"
|
||||||
|
var st := StateStore.new(dir)
|
||||||
|
st.reload()
|
||||||
|
st.set_variable("c", "str", 9, "t")
|
||||||
|
st.set_variable("c", "ratio", 2.5)
|
||||||
|
st.set_variable("c", "name", "Aslan")
|
||||||
|
st.save()
|
||||||
|
var back := StateStore.new(dir).get_variables("c")
|
||||||
|
_check(back["str"]["value"] is int and back["str"]["value"] == 9, "an int survives the state file")
|
||||||
|
_check(back["ratio"]["value"] is float and back["ratio"]["value"] == 2.5, "a float survives")
|
||||||
|
_check(back["name"]["value"] is String, "text survives")
|
||||||
|
DirAccess.remove_absolute(st.state_path())
|
||||||
|
DirAccess.remove_absolute(dir.path_join("state"))
|
||||||
|
DirAccess.remove_absolute(dir)
|
||||||
|
# Variable cards.
|
||||||
|
var card := RollTable.create(RollTable.KIND_VARIABLE, "v", "Species", "text")
|
||||||
|
card.var_name = "species"
|
||||||
|
card.initial = "Aslan"
|
||||||
|
var b := _board([card])
|
||||||
|
var shown := Roller.variable_display(b, {}, card)
|
||||||
|
_check(shown["text"] == "Aslan" and not shown["set"], "variable card shows its starting value when unset")
|
||||||
|
shown = Roller.variable_display(b, _vars({"species": "Vargr"}), card)
|
||||||
|
_check(shown["text"] == "Vargr" and shown["set"], "variable card shows the live value")
|
||||||
|
_check(Roller.roll(b, "v", _rng(1)).is_empty(), "a variable card is never rolled")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- choices
|
||||||
|
|
||||||
|
func _choice_board() -> TowerBoard:
|
||||||
|
var career := RollTable.create(RollTable.KIND_CHOICE, "career", "Career", "pick")
|
||||||
|
career.prompt = "Your EDU is {@edu}. Which career?"
|
||||||
|
career.save_as = "@career"
|
||||||
|
career.entries[0].text = "Navy"
|
||||||
|
career.entries[1].text = "Army"
|
||||||
|
career.entries[1].effects = "@branch = \"ground\""
|
||||||
|
career.entries[1].details = "Boots on the ground."
|
||||||
|
career.entries[2].text = "Scouts"
|
||||||
|
var after := _table("after", ["Then {@career}"])
|
||||||
|
for e in career.entries:
|
||||||
|
e.add_pipe("after")
|
||||||
|
var terms := RollTable.create(RollTable.KIND_CHOICE, "terms_q", "Terms", "number")
|
||||||
|
terms.min_expr = "1"
|
||||||
|
terms.max_expr = "@max_terms"
|
||||||
|
terms.save_as = "@terms"
|
||||||
|
terms.entries[0].effects = "@total += answer"
|
||||||
|
terms.entries[0].add_pipe("term", "answer")
|
||||||
|
var term := _table("term", ["A term"])
|
||||||
|
var hero := RollTable.create(RollTable.KIND_CHOICE, "hero_q", "Hero", "text")
|
||||||
|
hero.save_as = "hero"
|
||||||
|
hero.entries[0].add_pipe("greet")
|
||||||
|
var greet := _table("greet", ["Hello {hero} ({answer})"])
|
||||||
|
return _board([career, after, terms, term, hero, greet])
|
||||||
|
|
||||||
|
|
||||||
|
func _test_choices() -> void:
|
||||||
|
var b := _choice_board()
|
||||||
|
# pick: a scripted index.
|
||||||
|
var vars := _vars({"edu": 9})
|
||||||
|
var ctx := Roller.new_context(b, _rng(2), vars, {})
|
||||||
|
var reqs: Array = []
|
||||||
|
ctx.prompt = _scripted({"pick": 1}, reqs)
|
||||||
|
var n: Dictionary = await Roller.roll_async(b, "career", ctx)
|
||||||
|
_eq(reqs.size(), 1, "one prompt")
|
||||||
|
var req: Dictionary = reqs[0] if not reqs.is_empty() else {}
|
||||||
|
_check(req.get("kind") == "pick" and req.get("table_id") == "career" and (req.get("options", []) as Array).size() == 3, "pick request shape: %s" % str(req))
|
||||||
|
_eq(Formatter.strip_tags(str(req.get("prompt", ""))), "Your EDU is 9. Which career?", "prompt expands {@var}")
|
||||||
|
_check(req.has("min") and req.has("max") and req.get("default") == -1, "request has min, max and default")
|
||||||
|
_check((req.get("options", [{}, {}]) as Array)[1].get("details") == "Boots on the ground." and (req["options"] as Array)[1].get("index") == 1, "options carry index and details")
|
||||||
|
_check(n.get("picked", false) and (n["entry"] as TableEntry).text == "Army" and n.get("kind") == "choice", "picked entry is the node's entry")
|
||||||
|
_eq(_var(vars, "branch"), "ground", "picked entry's effects run")
|
||||||
|
_eq(_var(vars, "career"), "Army", "save_as gets the picked text")
|
||||||
|
_check((n["children"] as Array).size() == 1 and Formatter.strip_tags((n["children"] as Array)[0]["summary"]) == "Then Army", "picked entry's pipes follow")
|
||||||
|
_check(not n.has("value"), "a picked entry has no die value")
|
||||||
|
# pick: Random.
|
||||||
|
var randoms := {}
|
||||||
|
for k in 30:
|
||||||
|
var c2 := Roller.new_context(b, ctx.rng, _vars({"edu": 9}), {})
|
||||||
|
c2.prompt = _scripted({"pick": -1}, [])
|
||||||
|
var r: Dictionary = await Roller.roll_async(b, "career", c2)
|
||||||
|
_check(r.get("random", false) and r.has("value"), "Random rolls the card")
|
||||||
|
randoms[(r["entry"] as TableEntry).text] = true
|
||||||
|
_eq(randoms.size(), 3, "Random can give every option")
|
||||||
|
# number with save_as, answer, the Answer entry's effects and pipes.
|
||||||
|
vars = _vars({"max_terms": 4, "total": 10})
|
||||||
|
ctx = Roller.new_context(b, _rng(3), vars, {})
|
||||||
|
reqs = []
|
||||||
|
ctx.prompt = _scripted({"number": 99}, reqs)
|
||||||
|
n = await Roller.roll_async(b, "terms_q", ctx)
|
||||||
|
_check(not reqs.is_empty() and reqs[0]["min"] == 1 and reqs[0]["max"] == 4 and reqs[0]["default"] == 1, "number request min/max/default from expressions")
|
||||||
|
_eq(n.get("answer"), 4, "number answer is clamped to max")
|
||||||
|
_eq(Formatter.strip_tags(str(n["summary"])), "4", "number result text is the number")
|
||||||
|
_eq(_var(vars, "terms"), 4, "save_as gets the number")
|
||||||
|
_check(_var(vars, "terms") is int, "...as an int")
|
||||||
|
_eq(ctx.chain_vars.get("answer"), 4, "chain variable answer")
|
||||||
|
_eq(_var(vars, "total"), 14, "the Answer entry's effects see answer")
|
||||||
|
_eq((n["children"] as Array).size(), 4, "the Answer entry's pipe count can be an expression")
|
||||||
|
_check(n.has("effects") and Effects.log_text(n["effects"]) == PackedStringArray(["Total +4 → 14"]), "effects log on the node: %s" % str(n.get("effects")))
|
||||||
|
var steps := Roller.flatten(n, [])
|
||||||
|
_check(steps[0].get("answer") == 4 and steps[0].get("kind") == "choice" and steps[0].has("effects"), "steps carry kind, answer and effects")
|
||||||
|
# Headless: number answers min.
|
||||||
|
var hn := Roller.roll(b, "terms_q", _rng(4), 0, {}, Roller.new_context(b, _rng(4), _vars({"max_terms": 4}), {}))
|
||||||
|
_eq(hn.get("answer"), 1, "headless number answers min")
|
||||||
|
# text.
|
||||||
|
ctx = Roller.new_context(b, _rng(5), {}, {})
|
||||||
|
ctx.prompt = _scripted({"text": "Zed"}, [])
|
||||||
|
n = await Roller.roll_async(b, "hero_q", ctx)
|
||||||
|
_check(n.get("answer") == "Zed" and Formatter.strip_tags(str(n["summary"])) == "Zed", "text answer")
|
||||||
|
_eq(ctx.chain_vars.get("hero"), "Zed", "text save_as to a chain variable")
|
||||||
|
_eq(Formatter.strip_tags((n["children"] as Array)[0]["summary"]), "Hello Zed (Zed)", "later tables use the answer")
|
||||||
|
var ht := Roller.roll(b, "hero_q", _rng(5))
|
||||||
|
_eq(ht.get("answer"), "", "headless text answers \"\"")
|
||||||
|
# Cancel.
|
||||||
|
ctx = Roller.new_context(b, _rng(6), _vars({"edu": 9}), {})
|
||||||
|
ctx.prompt = _scripted({"pick": null}, [])
|
||||||
|
n = await Roller.roll_async(b, "career", ctx)
|
||||||
|
_check(n.get("stop") == "Cancelled" and n.get("cancelled", false), "Cancel gives a Cancelled stop node")
|
||||||
|
_eq(ctx.halted, "Cancelled", "ctx.halted says Cancelled")
|
||||||
|
# Cancel deeper in a chain keeps what came before and stops the rest.
|
||||||
|
var start := _table("start", ["Begin"])
|
||||||
|
start.entries[0].add_pipe("career")
|
||||||
|
start.entries[0].add_pipe("after")
|
||||||
|
b.tables.append(start)
|
||||||
|
ctx = Roller.new_context(b, _rng(7), _vars({"edu": 9}), {})
|
||||||
|
ctx.prompt = _scripted({"pick": null}, [])
|
||||||
|
n = await Roller.roll_async(b, "start", ctx)
|
||||||
|
_eq(_texts(Roller.flatten(n, [])), ["Begin", "Cancelled"], "nothing runs after Cancel")
|
||||||
|
# A prompt that really waits: the steps so far can be read meanwhile.
|
||||||
|
ctx = Roller.new_context(b, _rng(8), _vars({"edu": 9}), {})
|
||||||
|
var seen := {}
|
||||||
|
ctx.prompt = func(_r: Dictionary) -> Variant:
|
||||||
|
seen["steps"] = _texts(Roller.progress(ctx))
|
||||||
|
await process_frame
|
||||||
|
seen["resumed"] = true
|
||||||
|
return 2
|
||||||
|
seen["resumed"] = false
|
||||||
|
n = await Roller.roll_async(b, "start", ctx)
|
||||||
|
_eq(seen.get("steps"), ["Begin"], "progress() shows the steps before the question")
|
||||||
|
_check(seen.get("resumed", false), "the roll waited for the prompt")
|
||||||
|
ctx.prompt = Callable()
|
||||||
|
_eq(_texts(Roller.flatten(n, [])), ["Begin", "Scouts", "Then Scouts", "Then Scouts"], "the roll finishes after the answer")
|
||||||
|
# A [[reference]] into a choice card prompts too.
|
||||||
|
var ask := _table("ask", ["You chose [[Career]]!"])
|
||||||
|
b.tables.append(ask)
|
||||||
|
ctx = Roller.new_context(b, _rng(9), _vars({"edu": 9}), {})
|
||||||
|
reqs = []
|
||||||
|
ctx.prompt = _scripted({"pick": 0}, reqs)
|
||||||
|
n = await Roller.roll_async(b, "ask", ctx)
|
||||||
|
_check(reqs.size() == 1 and Formatter.strip_tags(str(n["summary"])) == "You chose Navy!", "a reference into a choice card prompts: %s" % Formatter.strip_tags(str(n["summary"])))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- loops
|
||||||
|
|
||||||
|
func _test_loops() -> void:
|
||||||
|
# times
|
||||||
|
var loop := RollTable.create(RollTable.KIND_LOOP, "loop", "Loop", "times")
|
||||||
|
loop.loop_expr = "3"
|
||||||
|
loop.entries[0].effects = "@sum += i"
|
||||||
|
loop.entries[0].text = "Pass {i}"
|
||||||
|
loop.entries[1].add_pipe("done")
|
||||||
|
var done := _table("done", ["Done after {= @sum}"])
|
||||||
|
var b := _board([loop, done])
|
||||||
|
var vars := {}
|
||||||
|
var ctx := Roller.new_context(b, _rng(1), vars, {})
|
||||||
|
var n := Roller.roll(b, "loop", ctx.rng, 0, {}, ctx)
|
||||||
|
_check(n.get("kind") == "loop" and n.get("passes") == 3, "times runs 3 passes")
|
||||||
|
_eq(n.get("summary"), "Repeated 3 times", "loop node text")
|
||||||
|
_eq(_var(vars, "sum"), 6, "i is 1, 2, 3")
|
||||||
|
_eq(_texts(Roller.flatten(n, [])), ["Repeated 3 times", "Pass 1", "Pass 2", "Pass 3", "Afterwards", "Done after 6"], "loop steps")
|
||||||
|
_check(not ctx.chain_vars.has("i"), "i is gone after the loop")
|
||||||
|
var steps := Roller.flatten(n, [])
|
||||||
|
_check(steps[1].get("pass") == 1 and steps[1]["num"] == "1" and steps[4].get("after", false) and steps[0].get("passes") == 3, "pass and Afterwards steps are marked")
|
||||||
|
var le := {}
|
||||||
|
var lp := {}
|
||||||
|
Roller.collect_lit(n, le, lp)
|
||||||
|
_check(lp.has(Roller.pipe_key("loop", "e2", "done")) and not lp.has(Roller.pipe_key("loop", "e1", "loop")), "passes light no pipe; Afterwards' pipe is lit")
|
||||||
|
loop.loop_expr = "0"
|
||||||
|
n = Roller.roll(b, "loop", _rng(2))
|
||||||
|
_check(n.get("passes") == 0 and (n["children"] as Array).size() == 1, "times 0 runs only Afterwards")
|
||||||
|
loop.loop_expr = "1d3"
|
||||||
|
for k in 20:
|
||||||
|
var p: int = Roller.roll(b, "loop", _rng(k)).get("passes", -1)
|
||||||
|
_check(p >= 1 and p <= 3, "times 1d3")
|
||||||
|
loop.loop_expr = "nope("
|
||||||
|
n = Roller.roll(b, "loop", _rng(2))
|
||||||
|
_check(n.get("passes") == 0 and n.has("effects") and n["effects"][0].get("error", false), "a bad loop rule is logged, not fatal")
|
||||||
|
# while
|
||||||
|
loop.loop_mode = "while"
|
||||||
|
loop.loop_expr = "@hp > 0"
|
||||||
|
loop.entries[0].effects = "@hp -= 3"
|
||||||
|
vars = _vars({"hp": 10})
|
||||||
|
n = Roller.roll(b, "loop", _rng(3), 0, {}, Roller.new_context(b, _rng(3), vars, {}))
|
||||||
|
_check(n.get("passes") == 4 and _var(vars, "hp") == -2, "while stops when the condition is false (%s passes)" % str(n.get("passes")))
|
||||||
|
vars = _vars({"hp": 0})
|
||||||
|
n = Roller.roll(b, "loop", _rng(3), 0, {}, Roller.new_context(b, _rng(3), vars, {}))
|
||||||
|
_eq(n.get("passes"), 0, "while can run 0 times")
|
||||||
|
# until
|
||||||
|
loop.loop_mode = "until"
|
||||||
|
loop.loop_expr = "@n >= 5"
|
||||||
|
loop.entries[0].effects = "@n += 2"
|
||||||
|
vars = _vars({"n": 0})
|
||||||
|
n = Roller.roll(b, "loop", _rng(4), 0, {}, Roller.new_context(b, _rng(4), vars, {}))
|
||||||
|
_check(n.get("passes") == 3 and _var(vars, "n") == 6, "until stops when the condition is true")
|
||||||
|
vars = _vars({"n": 10})
|
||||||
|
n = Roller.roll(b, "loop", _rng(4), 0, {}, Roller.new_context(b, _rng(4), vars, {}))
|
||||||
|
_eq(n.get("passes"), 1, "until runs at least once")
|
||||||
|
# An endless while stops at the action limit.
|
||||||
|
loop.loop_mode = "while"
|
||||||
|
loop.loop_expr = "true"
|
||||||
|
loop.entries[0].effects = ""
|
||||||
|
ctx = Roller.new_context(b, _rng(5), {}, {})
|
||||||
|
n = Roller.roll(b, "loop", ctx.rng, 0, {}, ctx)
|
||||||
|
var last: Dictionary = (n["children"] as Array).back()
|
||||||
|
_check(last.get("limit", false) and n.get("passes") == RollContext.DEFAULT_MAX_ACTIONS - 1, "an endless loop stops at the limit (%s passes)" % str(n.get("passes")))
|
||||||
|
|
||||||
|
|
||||||
|
func _test_loop_from_answer() -> void:
|
||||||
|
var q := RollTable.create(RollTable.KIND_CHOICE, "q", "How many?", "number")
|
||||||
|
q.max_expr = "10"
|
||||||
|
q.entries[0].add_pipe("loop")
|
||||||
|
var loop := RollTable.create(RollTable.KIND_LOOP, "loop", "Loop", "times")
|
||||||
|
loop.loop_expr = "answer"
|
||||||
|
loop.entries[0].effects = "@count += 1"
|
||||||
|
var b := _board([q, loop])
|
||||||
|
var vars := {}
|
||||||
|
var ctx := Roller.new_context(b, _rng(1), vars, {})
|
||||||
|
ctx.prompt = _scripted({"number": 4}, [])
|
||||||
|
var n: Dictionary = await Roller.roll_async(b, "q", ctx)
|
||||||
|
var header: Dictionary = (n["children"] as Array)[0] if not (n["children"] as Array).is_empty() else {}
|
||||||
|
_check(header.get("passes") == 4 and _var(vars, "count") == 4, "a loop driven by a number answer")
|
||||||
|
n = Roller.roll(b, "q", _rng(2))
|
||||||
|
_eq(((n["children"] as Array)[0] as Dictionary).get("passes"), 0, "headless answer 0 runs no passes")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- cycles
|
||||||
|
|
||||||
|
func _test_cycles() -> void:
|
||||||
|
# A pipe cycle that ends on a condition (the count is 1 while @k < 5).
|
||||||
|
var a := _table("a", ["Step {@k}"])
|
||||||
|
a.entries[0].effects = "@k += 1"
|
||||||
|
a.entries[0].add_pipe("a", "@k < 5")
|
||||||
|
var b := _board([a])
|
||||||
|
var vars := {}
|
||||||
|
var n := Roller.roll(b, "a", _rng(1), 0, {}, Roller.new_context(b, _rng(1), vars, {}))
|
||||||
|
_eq(_texts(Roller.flatten(n, [])), ["Step 1", "Step 2", "Step 3", "Step 4", "Step 5"], "a cycle ends on its condition")
|
||||||
|
_check(Roller.endless_cycles(b).is_empty(), "an expression-count cycle isn't flagged as endless")
|
||||||
|
# An endless cycle stops at exactly 10,000 actions.
|
||||||
|
var loop := _table("loop", ["Again"])
|
||||||
|
loop.entries[0].add_pipe("loop")
|
||||||
|
var b2 := _board([loop])
|
||||||
|
var ctx := Roller.new_context(b2, _rng(2), {}, {})
|
||||||
|
var t0 := Time.get_ticks_msec()
|
||||||
|
n = Roller.roll(b2, "loop", ctx.rng, 0, {}, ctx)
|
||||||
|
var ms := Time.get_ticks_msec() - t0
|
||||||
|
var steps := Roller.flatten(n, [])
|
||||||
|
_eq(steps.size(), 10001, "10,000 tables plus the marker")
|
||||||
|
_eq(ctx.actions, 10000, "exactly 10,000 actions")
|
||||||
|
_eq(str(steps.back()["text"]), "Stopped after 10,000 actions", "the limit marker")
|
||||||
|
_check(steps.back().get("stop", false) and steps.back().get("limit", false), "the marker is a stop step")
|
||||||
|
_eq(ctx.halted, "Stopped after 10,000 actions", "ctx.halted")
|
||||||
|
_check(ms < 15000, "the endless cycle stops in reasonable time (%d ms)" % ms)
|
||||||
|
_eq(Roller.endless_cycles(b2), ["loop"] as Array[String], "a plain self-pipe is still flagged")
|
||||||
|
# Mixed with inline references.
|
||||||
|
var r := _table("r", ["[[Loop]] and on"])
|
||||||
|
b2.tables.append(r)
|
||||||
|
ctx = Roller.new_context(b2, _rng(3), {}, {})
|
||||||
|
n = Roller.roll(b2, "r", ctx.rng, 0, {}, ctx)
|
||||||
|
_check(ctx.actions == 10000 and ctx.halted != "", "the limit holds inside a reference")
|
||||||
|
|
||||||
|
|
||||||
|
func _test_long_chain() -> void:
|
||||||
|
var a := _table("a", ["Link {@k}"])
|
||||||
|
a.entries[0].effects = "@k += 1"
|
||||||
|
a.entries[0].add_pipe("a", "@k < 5000")
|
||||||
|
var b := _board([a])
|
||||||
|
var ctx := Roller.new_context(b, _rng(1), {}, {})
|
||||||
|
var n := Roller.roll(b, "a", ctx.rng, 0, {}, ctx)
|
||||||
|
var steps := Roller.flatten(n, [])
|
||||||
|
_eq(steps.size(), 5000, "a 5,000-step chain")
|
||||||
|
_eq(int(steps.back()["depth"]), 4999, "it nests 5,000 deep")
|
||||||
|
var le := {}
|
||||||
|
var lp := {}
|
||||||
|
var lt := {}
|
||||||
|
Roller.collect_lit(n, le, lp, lt)
|
||||||
|
_check(le.size() == 1 and lp.size() == 1, "collect_lit walks it")
|
||||||
|
_check(Roller.reaches(n, "a") and not Roller.reaches(n, "zzz"), "reaches walks it")
|
||||||
|
_check(JSON.stringify(steps).length() > 0, "its steps serialize")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- dice
|
||||||
|
|
||||||
|
func _ranged(dice: String, ranges: Array) -> RollTable:
|
||||||
|
var t := RollTable.new("check", "Check")
|
||||||
|
t.dice = dice
|
||||||
|
for i in ranges.size():
|
||||||
|
var e := TableEntry.new("e%d" % (i + 1), ranges[i][2])
|
||||||
|
e.has_range = true
|
||||||
|
e.range_lo = ranges[i][0]
|
||||||
|
e.range_hi = ranges[i][1]
|
||||||
|
t.entries.append(e)
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
|
func _test_expression_dice() -> void:
|
||||||
|
var t := _ranged("2d6 + dm(@end)", [[2, 6, "Fail"], [7, 12, "Pass"]])
|
||||||
|
var b := _board([t])
|
||||||
|
_check(t.is_expr_dice() and not t.has_chances(), "an expression dice table")
|
||||||
|
_eq(t.num_label(t.entries[0], 0), "≤6", "low end label")
|
||||||
|
_eq(t.num_label(t.entries[1], 1), "7+", "high end label")
|
||||||
|
_check(t.chance(t.entries[0]) == 0.0, "no chances for expression dice")
|
||||||
|
_eq(t.range_problems(), "", "no gap warnings past the ends")
|
||||||
|
_check(t.min_value() == 2 and t.die_size() == 12, "span is the ranges' span")
|
||||||
|
_eq(t.dice_label(), "2d6 + dm(@end)", "the label is the expression")
|
||||||
|
var high := 0
|
||||||
|
for k in 200:
|
||||||
|
var n := Roller.roll(b, "check", _rng(k), 0, {}, Roller.new_context(b, _rng(k), _vars({"end": 15}), {}))
|
||||||
|
_check(not n.has("stop"), "high values clamp to the top range")
|
||||||
|
if int(n.get("value", 0)) > 12:
|
||||||
|
high += 1
|
||||||
|
_eq((n["entry"] as TableEntry).text, "Pass", "a 13+ lands on 7+")
|
||||||
|
_check(high > 0, "values past 12 happened (%d)" % high)
|
||||||
|
for k in 50:
|
||||||
|
var n := Roller.roll(b, "check", _rng(k), 0, {}, Roller.new_context(b, _rng(k), _vars({"end": 0}), {}))
|
||||||
|
if int(n.get("value", 99)) < 2:
|
||||||
|
_eq((n["entry"] as TableEntry).text, "Fail", "values under 2 clamp to ≤6")
|
||||||
|
t.dice = "@terms"
|
||||||
|
var n2 := Roller.roll(b, "check", _rng(1), 0, {}, Roller.new_context(b, _rng(1), _vars({"terms": 20}), {}))
|
||||||
|
_check(n2.get("value") == 20 and (n2["entry"] as TableEntry).text == "Pass", "a plain variable as dice")
|
||||||
|
var gap := _ranged("1d6 + @x", [[2, 5, "Low"], [7, 12, "High"]])
|
||||||
|
_eq(gap.range_problems(), "No result for 6.", "a gap between ranges is still reported")
|
||||||
|
var plain := _ranged("2d6", [[2, 6, "Fail"], [7, 12, "Pass"]])
|
||||||
|
_check(not plain.is_expr_dice() and plain.num_label(plain.entries[0], 0) == "2–6" and plain.has_chances(), "plain dice are unchanged")
|
||||||
|
t.dice = "2d6 +"
|
||||||
|
var bad := Roller.roll(b, "check", _rng(1))
|
||||||
|
_check(bad.has("stop"), "a broken dice expression stops with a message: %s" % str(bad.get("stop")))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- sheet
|
||||||
|
|
||||||
|
func _test_sheet() -> void:
|
||||||
|
var sheet := RollTable.create(RollTable.KIND_SHEET, "sheet", "Sheet")
|
||||||
|
sheet.entries[0].text = "STR {@str} ({= dm(@str)})\nSkills: {@skill_*}\n{= 1 +}"
|
||||||
|
var start := _table("start", ["Go"])
|
||||||
|
start.entries[0].add_pipe("sheet")
|
||||||
|
var b := _board([sheet, start])
|
||||||
|
var vars := _vars({"str": 9, "skill_gun_combat": 1, "skill_pilot": 0})
|
||||||
|
var live := Roller.render_sheet(b, vars, sheet)
|
||||||
|
var lines := Formatter.strip_tags(live).split("\n")
|
||||||
|
_eq(lines[0], "STR 9 (1)", "sheet: {@str} and {= dm(@str)}")
|
||||||
|
_eq(lines[1], "Skills: Gun Combat 1, Pilot 0", "sheet: {@skill_*}")
|
||||||
|
_check(live.contains("[url=error:expr]"), "a bad {= } shows an error marker")
|
||||||
|
_eq(Formatter.to_export_bbcode(live).contains("url="), false, "the error marker is internal")
|
||||||
|
var n := Roller.roll(b, "start", _rng(1), 0, {}, Roller.new_context(b, _rng(1), vars, {}))
|
||||||
|
var s := Roller.last_sheet(n)
|
||||||
|
_check(s.get("kind") == "sheet" and Formatter.strip_tags(str(s.get("summary"))).begins_with("STR 9 (1)"), "the chain's sheet node is its rendered template")
|
||||||
|
_eq(Roller.flatten(n, [])[1].get("kind"), "sheet", "sheet steps are marked")
|
||||||
|
var ctx := _ctx(_vars({"n": 3.0, "t": "x"}))
|
||||||
|
_eq(Formatter.strip_tags(TextExpander.expand("{@n} {@t} {@none} {= @n * 2}", ctx)["text"]), "3 x {@none?} 6", "{@n} shows numbers without .0")
|
||||||
|
_eq(Formatter.strip_tags(TextExpander.expand("{@zz_*}.", ctx)["text"]), ".", "an empty list shows nothing")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- JSON
|
||||||
|
|
||||||
|
func _test_json() -> void:
|
||||||
|
var roll := RollTable.create(RollTable.KIND_ROLL, "roll", "Roll")
|
||||||
|
roll.entries[0].effects = "@a = 2d6\nreset @skill_*"
|
||||||
|
roll.entries[0].add_pipe("loop", "@terms")
|
||||||
|
roll.entries[1].add_pipe("choice", 2, "@picked")
|
||||||
|
var pick := RollTable.create(RollTable.KIND_CHOICE, "choice", "Choice", "pick")
|
||||||
|
pick.save_as = "@career"
|
||||||
|
var num := RollTable.create(RollTable.KIND_CHOICE, "num", "Num", "number")
|
||||||
|
num.min_expr = "1"
|
||||||
|
num.max_expr = "@max"
|
||||||
|
var txt := RollTable.create(RollTable.KIND_CHOICE, "txt", "Txt", "text")
|
||||||
|
var loop := RollTable.create(RollTable.KIND_LOOP, "loop", "Loop", "until")
|
||||||
|
var vcard := RollTable.create(RollTable.KIND_VARIABLE, "var", "STR", "list")
|
||||||
|
vcard.initial = "\"a, b\""
|
||||||
|
var sheet := RollTable.create(RollTable.KIND_SHEET, "sheet", "Sheet")
|
||||||
|
var ranged := _ranged("2d6 + dm(@end)", [[2, 6, "Fail"], [7, 12, "Pass"]])
|
||||||
|
var b := _board([roll, pick, num, txt, loop, vcard, sheet, ranged])
|
||||||
|
b.name = "Logic"
|
||||||
|
# Factory shapes.
|
||||||
|
_check(num.entries.size() == 1 and num.entries[0].text == "Answer", "a number choice has one Answer entry")
|
||||||
|
_check(txt.entries.size() == 1 and txt.entries[0].text == "Answer", "a text choice has one Answer entry")
|
||||||
|
_check(pick.entries.size() >= 2, "a pick choice has options")
|
||||||
|
_check(loop.entries.size() == 2 and loop.entries[0].text == "Each time" and loop.entries[1].text == "Afterwards", "a loop has Each time and Afterwards")
|
||||||
|
_check(vcard.entries.is_empty() and vcard.var_name == "str" and vcard.var_type == "list", "a variable card")
|
||||||
|
_check(sheet.entries.size() == 1 and sheet.kind == "sheet", "a sheet card has one template entry")
|
||||||
|
# Defaults are left out.
|
||||||
|
var plain := _table("p", ["x"]).to_dict()
|
||||||
|
for k in ["kind", "choice", "prompt", "save_as", "min", "max", "loop", "loop_expr", "var_name", "var_type", "initial"]:
|
||||||
|
_check(not plain.has(k), "a plain table has no %s key" % k)
|
||||||
|
_check(not plain["entries"][0].has("effects"), "an entry without effects has no effects key")
|
||||||
|
var d := num.to_dict()
|
||||||
|
_check(d["kind"] == "choice" and d["choice"] == "number" and d["min"] == "1" and d["max"] == "@max" and not d.has("save_as"), "choice keys: %s" % str(d))
|
||||||
|
_eq(roll.to_dict()["entries"][0]["pipes"], [{"table": "loop", "count": "@terms"}], "an expression pipe count")
|
||||||
|
# RollTable round trip through JSON text.
|
||||||
|
var text := b.to_json()
|
||||||
|
var b2 := TowerBoard.new()
|
||||||
|
_check(b2.load_json(text), "board JSON loads")
|
||||||
|
_eq(b2.to_json(), text, "board JSON round-trips unchanged")
|
||||||
|
_eq(b2.get_table("roll").entries[0].count_expr("loop"), "@terms", "expression count survives")
|
||||||
|
# JsonIO canonical/import keep every new key.
|
||||||
|
var exported := JsonIO.export_json(b.to_dict())
|
||||||
|
var imp := JsonIO.import_json(exported)
|
||||||
|
_check(imp["ok"], "import ok: %s" % str(imp["errors"]))
|
||||||
|
var b3 := TowerBoard.new()
|
||||||
|
b3.load_dict(imp["collection"])
|
||||||
|
for t in b.tables:
|
||||||
|
var t3 := b3.get_table(t.id)
|
||||||
|
_check(t3 != null and t3.to_dict() == t.to_dict(), "%s survives export and import\n got: %s\n want: %s" % [t.id, str(t3.to_dict() if t3 else {}), str(t.to_dict())])
|
||||||
|
var canon := JsonIO.canonical({"tables": [{"id": "x", "kind": "choice", "choice": "number", "min": 2.0, "max": 99,
|
||||||
|
"entries": [{"id": "e1", "text": "Answer", "effects": "@a += 1", "pipes": [{"table": "y", "count": "@n"}, {"table": "z", "count": 3.0}]}]}]})
|
||||||
|
var ct: Dictionary = canon["tables"][0]
|
||||||
|
_check(ct["kind"] == "choice" and ct["min"] == "2" and not ct.has("max"), "canonical keeps kind keys, numbers as text, drops defaults: %s" % str(ct))
|
||||||
|
_check(ct["entries"][0]["effects"] == "@a += 1" and ct["entries"][0]["pipes"] == [{"table": "y", "count": "@n"}, {"table": "z", "count": 3}], "canonical keeps effects and counts: %s" % str(ct["entries"][0]))
|
||||||
|
_eq(JsonIO.pipe_label(JsonIO.pipe_info({"table": "y", "count": "@n"})), "×@n", "pipe label for an expression count")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- scenario
|
||||||
|
|
||||||
|
func _character_board() -> TowerBoard:
|
||||||
|
var chargen := _table("chargen", ["Create a Traveller"])
|
||||||
|
chargen.entries[0].effects = "reset @skill_*; @str = 2d6; @dex = 2d6; @end = 2d6\n@edu = 2d6; @terms = 0; @age = 18; @injuries = 0"
|
||||||
|
chargen.entries[0].add_pipe("career")
|
||||||
|
var str_card := RollTable.create(RollTable.KIND_VARIABLE, "v_str", "STR")
|
||||||
|
str_card.var_name = "str"
|
||||||
|
var career := RollTable.create(RollTable.KIND_CHOICE, "career", "Career", "pick")
|
||||||
|
career.prompt = "EDU {@edu}. Which career?"
|
||||||
|
career.save_as = "@career"
|
||||||
|
var names := ["Navy", "Army", "Scouts"]
|
||||||
|
for i in 3:
|
||||||
|
career.entries[i].text = names[i]
|
||||||
|
career.entries[i].add_pipe("terms_q")
|
||||||
|
career.entries[0].effects = "@skill_pilot = max(@skill_pilot, 0)"
|
||||||
|
var terms_q := RollTable.create(RollTable.KIND_CHOICE, "terms_q", "Terms", "number")
|
||||||
|
terms_q.min_expr = "1"
|
||||||
|
terms_q.max_expr = "7"
|
||||||
|
terms_q.save_as = "@want"
|
||||||
|
terms_q.entries[0].add_pipe("terms")
|
||||||
|
var terms := RollTable.create(RollTable.KIND_LOOP, "terms", "Terms", "times")
|
||||||
|
terms.loop_expr = "@want"
|
||||||
|
terms.entries[0].text = "Term {i}"
|
||||||
|
terms.entries[0].effects = "@terms += 1; @age += 4"
|
||||||
|
terms.entries[0].add_pipe("survival")
|
||||||
|
terms.entries[1].add_pipe("sheet")
|
||||||
|
var survival := _ranged("2d6 + dm(@end)", [[2, 5, "Injured"], [6, 12, "Survived"]])
|
||||||
|
survival.id = "survival"
|
||||||
|
survival.name = "Survival"
|
||||||
|
survival.entries[0].effects = "@injuries += 1"
|
||||||
|
survival.entries[1].effects = "@skill_pilot += 1"
|
||||||
|
var sheet := RollTable.create(RollTable.KIND_SHEET, "sheet", "Traveller")
|
||||||
|
sheet.entries[0].text = "[b]{@career}[/b], age {@age}\nSTR {@str} ({= dm(@str)}) END {@end}\nTerms {@terms}, injuries {@injuries}\nSkills: {@skill_*}"
|
||||||
|
return _board([chargen, str_card, career, terms_q, terms, survival, sheet])
|
||||||
|
|
||||||
|
|
||||||
|
func _test_character() -> void:
|
||||||
|
var b := _character_board()
|
||||||
|
var vars := _vars({"skill_old": 5})
|
||||||
|
var ctx := Roller.new_context(b, _rng(42), vars, {})
|
||||||
|
var reqs: Array = []
|
||||||
|
ctx.prompt = _scripted({"pick": 0, "number": 3}, reqs)
|
||||||
|
var n: Dictionary = await Roller.roll_async(b, "chargen", ctx)
|
||||||
|
var steps := Roller.flatten(n, [])
|
||||||
|
_eq(reqs.size(), 2, "two questions: career and terms")
|
||||||
|
_check(not vars.has("skill_old"), "reset @skill_* cleared old skills")
|
||||||
|
var log := Effects.log_text(steps[0].get("effects", []))
|
||||||
|
_check(log.size() == 8 and log[1].begins_with("STR = "), "characteristics rolled by effects: %s" % str(log))
|
||||||
|
var s: int = _var(vars, "str")
|
||||||
|
_check(s >= 2 and s <= 12, "STR is 2d6")
|
||||||
|
_eq(_var(vars, "career"), "Navy", "career picked")
|
||||||
|
_check(_var(vars, "terms") == 3 and _var(vars, "age") == 30, "three terms age the Traveller to 30")
|
||||||
|
var surv := 0
|
||||||
|
var survived := 0
|
||||||
|
for st: Dictionary in steps:
|
||||||
|
if st["table_id"] == "survival":
|
||||||
|
surv += 1
|
||||||
|
if Formatter.strip_tags(str(st["text"])) == "Survived":
|
||||||
|
survived += 1
|
||||||
|
_eq(surv, 3, "a survival check each term")
|
||||||
|
_eq(_var(vars, "skill_pilot"), survived, "each survival raised Pilot (Navy starts it at 0)")
|
||||||
|
_eq(_var(vars, "injuries"), 3 - survived, "each failure is an injury")
|
||||||
|
var sheet := Roller.last_sheet(n)
|
||||||
|
var text := Formatter.strip_tags(str(sheet.get("summary", "")))
|
||||||
|
_check(text.begins_with("Navy, age 30\nSTR %d (%d) END " % [s, Expr.dm(s)]), "the sheet shows the character:\n%s" % text)
|
||||||
|
_check(text.contains("Skills: Pilot %d" % survived), "the sheet lists skills:\n%s" % text)
|
||||||
|
_check(steps.back()["table_id"] == "sheet", "the sheet is the last step")
|
||||||
|
_check(ctx.actions < 30, "a few dozen actions (%d)" % ctx.actions)
|
||||||
|
_check(JSON.parse_string(JSON.stringify(steps)) is Array, "steps are plain data")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- checks
|
||||||
|
|
||||||
|
func _eq(got: Variant, want: Variant, what: String) -> void:
|
||||||
|
_check(typeof(got) == typeof(want) and got == want or (got is Array and want is Array and str(got) == str(want)), "%s\n got: %s\n want: %s" % [what, str(got), str(want)])
|
||||||
|
|
||||||
|
|
||||||
|
func _check(ok: bool, what: String) -> void:
|
||||||
|
if not ok:
|
||||||
|
_failures += 1
|
||||||
|
print(" ✗ ", what)
|
||||||
1
tests/test_logic.gd.uid
Normal file
1
tests/test_logic.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
uid://ce2yfyfufj47e
|
||||||
|
|
@ -68,7 +68,7 @@ func _init() -> void:
|
||||||
stops += 1
|
stops += 1
|
||||||
_check(stops > 50 and stops < 150, "rolls into a gap stop with a message (%d/200)" % stops)
|
_check(stops > 50 and stops < 150, "rolls into a gap stop with a message (%d/200)" % stops)
|
||||||
|
|
||||||
# A self-pipe stops at the depth limit instead of looping forever.
|
# A self-pipe stops at the action limit (docs/LOGIC.md §7) instead of looping forever.
|
||||||
var loop := RollTable.new("loop", "Loop")
|
var loop := RollTable.new("loop", "Loop")
|
||||||
var again := TableEntry.new("e1", "Again")
|
var again := TableEntry.new("e1", "Again")
|
||||||
again.pipes.append("loop")
|
again.pipes.append("loop")
|
||||||
|
|
@ -76,7 +76,7 @@ func _init() -> void:
|
||||||
var b3 := TowerBoard.new()
|
var b3 := TowerBoard.new()
|
||||||
b3.tables.append(loop)
|
b3.tables.append(loop)
|
||||||
var steps := Roller.flatten(Roller.roll(b3, "loop", rng), [])
|
var steps := Roller.flatten(Roller.roll(b3, "loop", rng), [])
|
||||||
_check(steps.size() == Roller.MAX_DEPTH + 2, "self-pipe stops after the depth limit (%d steps)" % steps.size())
|
_check(steps.size() == Roller.MAX_ACTIONS + 1 and str(steps[steps.size() - 1]["text"]) == Roller.limit_text(), "self-pipe stops at the action limit (%d steps)" % steps.size())
|
||||||
|
|
||||||
# JSON round trip keeps everything.
|
# JSON round trip keeps everything.
|
||||||
var copy := TowerBoard.new()
|
var copy := TowerBoard.new()
|
||||||
|
|
|
||||||
75
ui/main.gd
75
ui/main.gd
|
|
@ -51,6 +51,14 @@ var lit_texts: Dictionary = {} # "tid:eid" -> expanded BBCode from the la
|
||||||
var _details_popup: DetailsPopup
|
var _details_popup: DetailsPopup
|
||||||
var _pipe_popover: PipePopover
|
var _pipe_popover: PipePopover
|
||||||
var _ref_cache: Dictionary = {} # entry text -> Array[String] of referenced table ids
|
var _ref_cache: Dictionary = {} # entry text -> Array[String] of referenced table ids
|
||||||
|
## Choice cards: func(request: Dictionary) -> Variant, awaited by the roller
|
||||||
|
## (docs/LOGIC.md §8). Until the pop-up exists this gives the headless answers.
|
||||||
|
var prompt_hook: Callable = func(req: Dictionary) -> Variant: return Roller.default_reply(req)
|
||||||
|
## The context of the roll in progress, or null; its root is the tree so far
|
||||||
|
## (Roller.progress()).
|
||||||
|
var rolling_ctx: RollContext = null
|
||||||
|
## Chains longer than this show at once instead of animating.
|
||||||
|
const LONG_CHAIN := 40
|
||||||
|
|
||||||
|
|
||||||
func _ready() -> void:
|
func _ready() -> void:
|
||||||
|
|
@ -535,7 +543,7 @@ func _card_under_mouse() -> TableCard:
|
||||||
## whole result at once.
|
## whole result at once.
|
||||||
func start_roll(tid: String, fast: bool = false) -> void:
|
func start_roll(tid: String, fast: bool = false) -> void:
|
||||||
var t := data.get_table(tid)
|
var t := data.get_table(tid)
|
||||||
if t == null:
|
if t == null or t.kind == RollTable.KIND_VARIABLE:
|
||||||
return
|
return
|
||||||
fast = fast or Input.is_key_pressed(KEY_SHIFT)
|
fast = fast or Input.is_key_pressed(KEY_SHIFT)
|
||||||
_archive_current()
|
_archive_current()
|
||||||
|
|
@ -548,7 +556,17 @@ func start_roll(tid: String, fast: bool = false) -> void:
|
||||||
(c as TableCard).set_rolling(false)
|
(c as TableCard).set_rolling(false)
|
||||||
(c as TableCard).clear_flick()
|
(c as TableCard).clear_flick()
|
||||||
var ctx := Roller.new_context(data, rng, persistent_vars, decks)
|
var ctx := Roller.new_context(data, rng, persistent_vars, decks)
|
||||||
var tree := Roller.roll(data, tid, rng, 0, decks, ctx)
|
ctx.prompt = prompt_hook
|
||||||
|
rolling_ctx = ctx
|
||||||
|
var tree: Dictionary = await Roller.roll_async(data, tid, ctx)
|
||||||
|
if rolling_ctx == ctx:
|
||||||
|
rolling_ctx = null
|
||||||
|
if my != _token:
|
||||||
|
# Another roll started while this one waited for an answer.
|
||||||
|
_store_decks()
|
||||||
|
if ctx.persistent_changed:
|
||||||
|
_store_variables()
|
||||||
|
return
|
||||||
lit_entries.clear()
|
lit_entries.clear()
|
||||||
lit_pipes.clear()
|
lit_pipes.clear()
|
||||||
lit_texts.clear()
|
lit_texts.clear()
|
||||||
|
|
@ -556,7 +574,7 @@ func start_roll(tid: String, fast: bool = false) -> void:
|
||||||
current = {"collection": data.id, "root": tid, "root_name": t.name, "time": Time.get_unix_time_from_system(),
|
current = {"collection": data.id, "root": tid, "root_name": t.name, "time": Time.get_unix_time_from_system(),
|
||||||
"steps": [], "all": Roller.flatten(tree, []), "done": false, "chain_vars": ctx.chain_vars.duplicate()}
|
"steps": [], "all": Roller.flatten(tree, []), "done": false, "chain_vars": ctx.chain_vars.duplicate()}
|
||||||
_store_roll(ctx)
|
_store_roll(ctx)
|
||||||
if fast:
|
if fast or (current["all"] as Array).size() > LONG_CHAIN:
|
||||||
_finish_fast_roll()
|
_finish_fast_roll()
|
||||||
return
|
return
|
||||||
tray.render()
|
tray.render()
|
||||||
|
|
@ -567,13 +585,42 @@ func start_roll(tid: String, fast: bool = false) -> void:
|
||||||
tray.render()
|
tray.render()
|
||||||
|
|
||||||
|
|
||||||
func _play_node(n: Dictionary, my: int, depth: int = 0) -> void:
|
## Plays a result tree step by step. Iterative (an explicit stack), so long
|
||||||
if my != _token or n.is_empty():
|
## chains don't recurse.
|
||||||
return
|
func _play_node(root_node: Dictionary, my: int) -> void:
|
||||||
|
var stack: Array = [[root_node, 0, ""]] # node, depth, pipe key that led to it
|
||||||
|
while not stack.is_empty():
|
||||||
|
var top: Array = stack.pop_back()
|
||||||
|
var n: Dictionary = top[0]
|
||||||
|
if my != _token or n.is_empty():
|
||||||
|
return
|
||||||
|
var key: String = top[2]
|
||||||
|
if key != "":
|
||||||
|
lit_pipes[key] = true
|
||||||
|
await _pulse(key, my)
|
||||||
|
if my != _token:
|
||||||
|
return
|
||||||
|
await _play_one(n, my, int(top[1]))
|
||||||
|
if my != _token:
|
||||||
|
return
|
||||||
|
if n.has("stop"):
|
||||||
|
continue
|
||||||
|
var kids: Array = n["children"]
|
||||||
|
var eid := (n["entry"] as TableEntry).id
|
||||||
|
var tid := (n["table"] as RollTable).id
|
||||||
|
for k in range(kids.size() - 1, -1, -1):
|
||||||
|
var c: Dictionary = kids[k]
|
||||||
|
var ck := "" if (c.has("pass") or c.has("after")) else Roller.link_key(tid, eid, c)
|
||||||
|
stack.append([c, int(top[1]) + 1, ck])
|
||||||
|
|
||||||
|
|
||||||
|
## Animates one node: the card tumbles (plain rolls only), then the result lights.
|
||||||
|
func _play_one(n: Dictionary, my: int, depth: int) -> void:
|
||||||
var t: RollTable = n["table"]
|
var t: RollTable = n["table"]
|
||||||
var stopped := n.has("stop")
|
var stopped := n.has("stop")
|
||||||
var card := card_for(t.id)
|
var card := card_for(t.id)
|
||||||
if not stopped and card:
|
var tumble: bool = not n.has("kind") or bool(n.get("random", false))
|
||||||
|
if not stopped and card and tumble:
|
||||||
card.set_rolling(true)
|
card.set_rolling(true)
|
||||||
for k in 8:
|
for k in 8:
|
||||||
card = card_for(t.id)
|
card = card_for(t.id)
|
||||||
|
|
@ -600,11 +647,6 @@ func _play_node(n: Dictionary, my: int, depth: int = 0) -> void:
|
||||||
card.reveal(e.id)
|
card.reveal(e.id)
|
||||||
(current["steps"] as Array).append(Roller.step_of(n, depth))
|
(current["steps"] as Array).append(Roller.step_of(n, depth))
|
||||||
tray.render()
|
tray.render()
|
||||||
for c in n["children"]:
|
|
||||||
var key := Roller.link_key(t.id, (n["entry"] as TableEntry).id, c)
|
|
||||||
lit_pipes[key] = true
|
|
||||||
await _pulse(key, my)
|
|
||||||
await _play_node(c, my, depth + 1)
|
|
||||||
|
|
||||||
|
|
||||||
## Shows the whole current roll at once: every result and pipe on its path lit,
|
## Shows the whole current roll at once: every result and pipe on its path lit,
|
||||||
|
|
@ -1020,7 +1062,7 @@ func _light_steps(steps: Array) -> void:
|
||||||
var ek := Roller.entry_key(tid, str(s["entry_id"]))
|
var ek := Roller.entry_key(tid, str(s["entry_id"]))
|
||||||
lit_entries[ek] = true
|
lit_entries[ek] = true
|
||||||
lit_texts[ek] = str(s.get("text", ""))
|
lit_texts[ek] = str(s.get("text", ""))
|
||||||
if d > 0 and stack[d - 1] is Dictionary and (stack[d - 1] as Dictionary).has("entry_id"):
|
if d > 0 and not (s.has("pass") or s.has("after")) and stack[d - 1] is Dictionary and (stack[d - 1] as Dictionary).has("entry_id"):
|
||||||
var p: Dictionary = stack[d - 1]
|
var p: Dictionary = stack[d - 1]
|
||||||
var ptid := str(p.get("table_id", ""))
|
var ptid := str(p.get("table_id", ""))
|
||||||
var peid := str(p["entry_id"])
|
var peid := str(p["entry_id"])
|
||||||
|
|
@ -1054,7 +1096,7 @@ func _store_variables() -> void:
|
||||||
for n: String in persistent_vars:
|
for n: String in persistent_vars:
|
||||||
var v: Variant = persistent_vars[n]
|
var v: Variant = persistent_vars[n]
|
||||||
if v is Dictionary:
|
if v is Dictionary:
|
||||||
state.set_variable(data.id, n, str(v.get("value", "")), str(v.get("source", "")))
|
state.set_variable(data.id, n, v.get("value", ""), str(v.get("source", "")))
|
||||||
else:
|
else:
|
||||||
state.set_variable(data.id, n, str(v))
|
state.set_variable(data.id, n, str(v))
|
||||||
|
|
||||||
|
|
@ -1113,7 +1155,10 @@ func ref_targets_for(e: TableEntry) -> Array[String]:
|
||||||
func set_variable(name: String, value: String) -> void:
|
func set_variable(name: String, value: String) -> void:
|
||||||
var old: Variant = persistent_vars.get(name)
|
var old: Variant = persistent_vars.get(name)
|
||||||
var source := str(old.get("source", "")) if old is Dictionary else ""
|
var source := str(old.get("source", "")) if old is Dictionary else ""
|
||||||
persistent_vars[name] = {"value": value, "source": source}
|
# A number stays a number when the new text is one too.
|
||||||
|
var was: Variant = old.get("value") if old is Dictionary else null
|
||||||
|
var typed: Variant = Expr.to_value(value) if Expr.is_number(was) and Expr.is_number(value) else value
|
||||||
|
persistent_vars[name] = {"value": typed, "source": source}
|
||||||
_store_variables()
|
_store_variables()
|
||||||
if state:
|
if state:
|
||||||
state.save()
|
state.save()
|
||||||
|
|
|
||||||
|
|
@ -401,7 +401,7 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
|
||||||
RichText.hook_hover(text, main)
|
RichText.hook_hover(text, main)
|
||||||
h.add_child(text)
|
h.add_child(text)
|
||||||
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
|
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
|
||||||
if ranged:
|
if ranged and table.has_chances():
|
||||||
var pct := Style.make_label("%d%%" % roundi(table.chance(e) * 100.0), Style.body(true), 12, Style.MUTED)
|
var pct := Style.make_label("%d%%" % roundi(table.chance(e) * 100.0), Style.body(true), 12, Style.MUTED)
|
||||||
pct.size_flags_vertical = SIZE_SHRINK_CENTER
|
pct.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||||
h.add_child(pct)
|
h.add_child(pct)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue