Compare commits
No commits in common. "2ddf8c7c42154cc31fad8de10d21b649a5a383bb" and "667ee1d9f0c5a669a166bb529b0262a046c184fa" have entirely different histories.
2ddf8c7c42
...
667ee1d9f0
43 changed files with 321 additions and 5851 deletions
22
README.md
22
README.md
|
|
@ -16,9 +16,8 @@ godot --path .
|
|||
## Using it
|
||||
|
||||
- **Play mode** is for the game table. Click a die to roll. The results flicker, one lands,
|
||||
and a bead runs down any pipe into the next table. Hold **Shift** while clicking to fast
|
||||
roll: no animation, just the result. The tray at the bottom shows the whole chain and the
|
||||
last few rolls.
|
||||
and a bead runs down any pipe into the next table. The tray at the bottom shows the whole
|
||||
chain and the last few rolls.
|
||||
- **Build mode** is for setting up tables. Edit names, results, weights and details in place,
|
||||
add or delete results and tables, and drag a card by its header. Drag from a result's ●
|
||||
onto another table to lay a pipe. Click a pipe to set how many times it rolls, save its
|
||||
|
|
@ -28,14 +27,6 @@ godot --path .
|
|||
`[[Names -> hero]]` (saves the result as `{hero}` for the rest of the roll). `{@town|Towns}`
|
||||
keeps a value across rolls until you clear it in the tray's Variables tab. BBCode such as
|
||||
`[b]bold[/b]` works anywhere you type.
|
||||
- **Logic cards** (see `docs/LOGIC.md`): Build mode's **+ Table ▾** also adds choice cards
|
||||
(which option, how many, open ended), loops, variables and sheets. A choice card pauses the
|
||||
roll with a pop-up (1–9 pick, R for Random, Enter confirms, Esc cancels); the steps so far
|
||||
light up behind it. Loops show their rule (`× @rooms`, `while @hp > 0`); variable cards show
|
||||
their live value; sheet cards show their template filled in, and become the tray's
|
||||
headline when a chain reaches them. Results can carry effects (`@hp -= 2`), edited with
|
||||
the **ƒ** button in Build mode. The tray's Variables tab lists every variable, with
|
||||
**Reset all…**. Try `examples/logic_demo.json` (Board ▾ → Import).
|
||||
- **Collections:** the switcher in the top bar holds separate sets of tables. Build mode's
|
||||
**Board ▾** menu imports and exports TableTower JSON, JSON Canvas, Mermaid, DOT and GraphML.
|
||||
- **Ranged tables** (like *Wilderness Travel*) roll a d100 where each range's size sets its
|
||||
|
|
@ -64,21 +55,16 @@ docs/ design document
|
|||
## Tests
|
||||
|
||||
```sh
|
||||
for t in tests/test_*.gd; do godot --headless --path . -s "res://$t" -- --sample; done
|
||||
for t in tests/test_*.gd; do godot --headless --path . -s "res://$t"; done
|
||||
```
|
||||
|
||||
## Screenshots from the command line
|
||||
|
||||
```sh
|
||||
tools/test_window.sh -- --screenshot=/tmp/board.png [--build] [--expand-all] [--collapse-all] \
|
||||
[--roll=wilderness] [--fast] [--shot-delay=0.75]
|
||||
[--roll=wilderness] [--shot-delay=0.75]
|
||||
```
|
||||
|
||||
Logic-card views: `--board=examples/logic_demo.json --roll=start "--answers=Brin|3"` answers
|
||||
the first questions and leaves the next pop-up open; `--menu=add`, `--open-settings=<id>`,
|
||||
`--edit-effects=<id>`, `--demo-long=<n>` (a chain of n steps) and `--confirm-reset` show the
|
||||
rest.
|
||||
|
||||
This uses the sample board and doesn't save anything. `tools/test_window.sh` runs the game
|
||||
under the window class "TableTower Test" (via a temporary `override.cfg`), which a KWin
|
||||
window rule keeps in the background without focus.
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ func reshuffle() -> void:
|
|||
## Copies of this entry that are in the deck in total.
|
||||
static func copies_of(table: RollTable, e: TableEntry) -> int:
|
||||
if table.is_ranged():
|
||||
return 1 if table.can_come_up(e) else 0
|
||||
return 1 if e.has_range and table.chance(e) > 0.0 else 0
|
||||
return maxi(0, e.weight)
|
||||
|
||||
|
||||
|
|
@ -60,7 +60,7 @@ func draw(table: RollTable, rng: RandomNumberGenerator) -> Dictionary:
|
|||
for e in table.entries:
|
||||
var w := float(_remaining(table, e))
|
||||
if table.is_ranged():
|
||||
w *= 1.0 if table.is_expr_dice() else table.chance(e)
|
||||
w *= table.chance(e)
|
||||
weights.append(w)
|
||||
sum += w
|
||||
if sum <= 0.0:
|
||||
|
|
@ -84,8 +84,6 @@ func draw(table: RollTable, rng: RandomNumberGenerator) -> Dictionary:
|
|||
|
||||
## A die value inside the entry's range, weighted by the dice distribution.
|
||||
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 vals: Array[int] = []
|
||||
var mass := 0.0
|
||||
|
|
|
|||
237
core/effects.gd
237
core/effects.gd
|
|
@ -1,237 +0,0 @@
|
|||
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 +0,0 @@
|
|||
uid://doevsgi5ip72d
|
||||
410
core/expr.gd
410
core/expr.gd
|
|
@ -1,410 +0,0 @@
|
|||
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 word == "if" and is_call:
|
||||
# Spreadsheet-style if(condition, then, else). Both branches
|
||||
# are evaluated, so dice in either one are rolled.
|
||||
out += "_if"
|
||||
toks.append(["other", word])
|
||||
elif word == "if" or word == "else":
|
||||
# Godot's Expression parses "a if c else b" but returns the
|
||||
# wrong branch, so refuse it rather than give silent nonsense.
|
||||
return {"text": "", "inputs": [], "vars": [], "text_side": [],
|
||||
"error": "Write if(condition, then, else) instead of \"… if … else …\""}
|
||||
elif 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 _if(cond: Variant, then_value: Variant, else_value: Variant) -> Variant:
|
||||
return then_value if Expr.truthy(cond) else else_value
|
||||
|
||||
func has(list: Variant, item: Variant) -> bool:
|
||||
return Expr.has_item(list, item)
|
||||
|
||||
func count(prefix: Variant) -> int:
|
||||
if ctx == null:
|
||||
return 0
|
||||
return ctx.count_vars(str(prefix))
|
||||
|
|
@ -1 +0,0 @@
|
|||
uid://2r7dds243gsc
|
||||
|
|
@ -36,7 +36,7 @@ const IMPORT_ALLOWED_TAGS: Array[String] = [
|
|||
]
|
||||
|
||||
## url parameters with these prefixes are TextExpander's internal markers.
|
||||
const INTERNAL_META_PREFIXES: Array[String] = ["table:", "var:", "missing:", "unset:", "deep:", "error:"]
|
||||
const INTERNAL_META_PREFIXES: Array[String] = ["table:", "var:", "missing:", "unset:", "deep:"]
|
||||
|
||||
## Matches one tag: [name], [/name], [name=param] or [name key=value ...].
|
||||
## Parameters may contain quoted strings, so [url={"a":1}] is one tag.
|
||||
|
|
|
|||
|
|
@ -25,22 +25,13 @@ extends RefCounted
|
|||
## - When the roller itself stops (depth limit, empty table), it still returns a
|
||||
## node whose summary explains why, for example [method TextExpander.deep_marker].
|
||||
## - 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
|
||||
## 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 "@") -> value (String, int or float). Fresh for
|
||||
## every top-level roll. The roller sets "answer" and "i".
|
||||
## Chain variables: name (no "@") -> String value. Fresh for every top-level roll.
|
||||
var chain_vars: Dictionary = {}
|
||||
## The collection's persistent variables, owned and saved elsewhere:
|
||||
## name (without the "@") -> {"value": Variant, "source": table_id}.
|
||||
## name (without the "@") -> {"value": String, "source": table_id}.
|
||||
## This is the caller's Dictionary itself, not a copy, so saves show up there.
|
||||
var persistent_vars: Dictionary = {}
|
||||
## True once save() has written a persistent variable in this roll, so the caller
|
||||
|
|
@ -56,32 +47,6 @@ var rng: RandomNumberGenerator = null
|
|||
var resolve_table: Callable = Callable()
|
||||
## func(table_id: String, depth: int) -> Dictionary (a result node).
|
||||
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:
|
||||
|
|
@ -96,10 +61,8 @@ static func is_persistent(name: String) -> bool:
|
|||
|
||||
## Saves a value. Names starting with "@" go to the persistent variables
|
||||
## (stored without the "@", with the source table id); others to the chain.
|
||||
## Whole floats are stored as ints.
|
||||
func save(name: String, value: Variant, source_id: String = "") -> void:
|
||||
func save(name: String, value: String, source_id: String = "") -> void:
|
||||
var n: String = name.strip_edges()
|
||||
value = Expr.normalize(value)
|
||||
if n.begins_with("@"):
|
||||
n = n.substr(1)
|
||||
if n == "":
|
||||
|
|
@ -110,129 +73,20 @@ func save(name: String, value: Variant, source_id: String = "") -> void:
|
|||
chain_vars[n] = value
|
||||
|
||||
|
||||
## Returns the saved value as display text (numbers without ".0"), or null
|
||||
## when the variable isn't set. "@name" reads a persistent variable, "name" a
|
||||
## chain variable.
|
||||
## Returns the saved String value, or null when the variable isn't set.
|
||||
## "@name" reads a persistent variable, "name" a chain variable.
|
||||
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()
|
||||
if n.begins_with("@"):
|
||||
var entry: Variant = persistent_vars.get(n.substr(1))
|
||||
if entry is Dictionary:
|
||||
return Expr.normalize((entry as Dictionary).get("value", ""))
|
||||
return Expr.normalize(entry)
|
||||
if chain_vars.has(n):
|
||||
return Expr.normalize(chain_vars[n])
|
||||
return str((entry as Dictionary).get("value", ""))
|
||||
if entry != null:
|
||||
return str(entry)
|
||||
return null
|
||||
if chain_vars.has(n):
|
||||
return str(chain_vars[n])
|
||||
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.
|
||||
|
|
@ -254,17 +108,6 @@ func roll(table_id: String) -> Dictionary:
|
|||
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
|
||||
## [[references]] against names: normalize_name("[b]Gems[/b] ") == "gems".
|
||||
static func normalize_name(name: String) -> String:
|
||||
|
|
|
|||
|
|
@ -5,28 +5,9 @@ extends RefCounted
|
|||
## 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
|
||||
## 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 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 name: String = ""
|
||||
var position: Vector2 = Vector2.ZERO
|
||||
|
|
@ -34,8 +15,7 @@ var collapsed: bool = false
|
|||
## Longer description (may contain BBCode).
|
||||
var details: String = ""
|
||||
var tags: Array[String] = []
|
||||
## Dice expression for ranged tables, e.g. "1d100", "2d6", "1d8+2", or any
|
||||
## expression such as "2d6 + dm(@end)".
|
||||
## Dice expression for ranged tables, e.g. "1d100", "2d6", "1d8+2".
|
||||
var dice: String = DEFAULT_DICE
|
||||
## Card mode: entries are drawn without replacement until the deck is empty.
|
||||
var card_mode: bool = false
|
||||
|
|
@ -43,29 +23,8 @@ var card_mode: bool = false
|
|||
var deck_empty: String = "reshuffle"
|
||||
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_text: String = ""
|
||||
var _dice_plain: bool = true
|
||||
|
||||
|
||||
func _init(p_id: String = "", p_name: String = "") -> void:
|
||||
|
|
@ -73,50 +32,6 @@ func _init(p_id: String = "", p_name: String = "") -> void:
|
|||
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:
|
||||
for e in entries:
|
||||
if e.has_range:
|
||||
|
|
@ -124,79 +39,34 @@ func is_ranged() -> bool:
|
|||
return false
|
||||
|
||||
|
||||
## 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()).
|
||||
## The parsed dice expression (falls back to 1d100 if `dice` is invalid).
|
||||
func dice_obj() -> Dice:
|
||||
if _dice_cache == null or _dice_cache_text != 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_text = dice
|
||||
return _dice_cache
|
||||
|
||||
|
||||
## 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.
|
||||
## Label for the dice: "d100", "2d6", "1d8+2". Plain tables label by entry count.
|
||||
func dice_label() -> String:
|
||||
if is_ranged():
|
||||
return dice.strip_edges() if is_expr_dice() else dice_obj().label()
|
||||
return dice_obj().label()
|
||||
return "d%d" % die_size()
|
||||
|
||||
|
||||
## Lowest value that can be rolled (1 on plain tables). For expression dice,
|
||||
## the lowest range start.
|
||||
## Lowest value that can be rolled (1 on plain tables).
|
||||
func min_value() -> int:
|
||||
if not is_ranged():
|
||||
return 1
|
||||
if is_expr_dice():
|
||||
return _range_span().x
|
||||
return dice_obj().min_value()
|
||||
return dice_obj().min_value() if is_ranged() else 1
|
||||
|
||||
|
||||
## Highest value that can be rolled. Plain tables: the entry count. For
|
||||
## expression dice, the highest range end.
|
||||
## Highest value that can be rolled. Plain tables: the entry count.
|
||||
func die_size() -> int:
|
||||
if is_ranged():
|
||||
if is_expr_dice():
|
||||
return _range_span().y
|
||||
return dice_obj().max_value()
|
||||
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:
|
||||
var w := 0
|
||||
for e in entries:
|
||||
|
|
@ -207,7 +77,7 @@ func total_weight() -> int:
|
|||
## Formats a die value the way printed tables do: d100 values are two digits
|
||||
## and 100 is written "00".
|
||||
func fmt(value: int) -> String:
|
||||
var two_digit := (dice_obj().is_d100() and not is_expr_dice()) if is_ranged() else entries.size() == 100
|
||||
var two_digit := dice_obj().is_d100() if is_ranged() else entries.size() == 100
|
||||
if two_digit:
|
||||
return "00" if value == 100 else "%02d" % value
|
||||
return str(value)
|
||||
|
|
@ -216,45 +86,21 @@ func fmt(value: int) -> String:
|
|||
func num_label(e: TableEntry, index: int) -> String:
|
||||
if not e.has_range:
|
||||
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:
|
||||
return fmt(e.range_lo)
|
||||
return "%s–%s" % [fmt(e.range_lo), fmt(e.range_hi)]
|
||||
|
||||
|
||||
## 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()).
|
||||
## Chance (0–1) that a roll lands on this entry.
|
||||
func chance(e: TableEntry) -> float:
|
||||
if is_ranged():
|
||||
if not e.has_range or is_expr_dice():
|
||||
if not e.has_range:
|
||||
return 0.0
|
||||
return dice_obj().probability_between(e.range_lo, e.range_hi)
|
||||
var total := total_weight()
|
||||
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:
|
||||
for i in entries.size():
|
||||
var e := entries[i]
|
||||
|
|
@ -263,13 +109,6 @@ func entry_index_for(value: int) -> int:
|
|||
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:
|
||||
for e in entries:
|
||||
if e.id == eid:
|
||||
|
|
@ -278,23 +117,19 @@ func find_entry(eid: String) -> TableEntry:
|
|||
|
||||
|
||||
## 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:
|
||||
if not is_ranged():
|
||||
return ""
|
||||
var lo := min_value()
|
||||
var hi := die_size()
|
||||
if hi - lo > 100000:
|
||||
return "The ranges span too many values to check."
|
||||
var hits := PackedInt32Array()
|
||||
hits.resize(maxi(0, hi - lo + 1))
|
||||
hits.resize(hi + 1)
|
||||
var outside := PackedStringArray()
|
||||
for e in entries:
|
||||
if not e.has_range:
|
||||
continue
|
||||
for v in range(maxi(lo, e.range_lo), mini(hi, e.range_hi) + 1):
|
||||
hits[v - lo] += 1
|
||||
hits[v] += 1
|
||||
if e.range_lo < lo or e.range_hi > 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)
|
||||
|
|
@ -313,7 +148,7 @@ func _runs(hits: PackedInt32Array, lo: int, n: int, test: Callable) -> String:
|
|||
var out := PackedStringArray()
|
||||
var start := -1
|
||||
for v in range(lo, n + 2):
|
||||
var on: bool = v <= n and test.call(hits[v - lo])
|
||||
var on: bool = v <= n and test.call(hits[v])
|
||||
if on and start < 0:
|
||||
start = v
|
||||
elif not on and start >= 0:
|
||||
|
|
@ -322,34 +157,11 @@ func _runs(hits: PackedInt32Array, lo: int, n: int, test: Callable) -> String:
|
|||
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:
|
||||
var list: Array = []
|
||||
for e in entries:
|
||||
list.append(e.to_dict())
|
||||
var d := {"id": id, "name": name, "x": roundi(position.x), "y": roundi(position.y), "entries": list}
|
||||
if kind != KIND_ROLL:
|
||||
d["kind"] = kind
|
||||
if collapsed:
|
||||
d["collapsed"] = true
|
||||
if details != "":
|
||||
|
|
@ -362,29 +174,6 @@ func to_dict() -> Dictionary:
|
|||
d["card_mode"] = true
|
||||
if deck_empty != "reshuffle":
|
||||
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
|
||||
|
||||
|
||||
|
|
@ -401,31 +190,7 @@ static func from_dict(d: Dictionary) -> RollTable:
|
|||
t.dice = "1d%d" % int(d["die"])
|
||||
t.card_mode = bool(d.get("card_mode", false))
|
||||
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", []):
|
||||
if ed is Dictionary:
|
||||
t.entries.append(TableEntry.from_dict(ed))
|
||||
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)
|
||||
|
|
|
|||
546
core/roller.gd
546
core/roller.gd
|
|
@ -11,56 +11,27 @@ extends RefCounted
|
|||
## "inline": true, then pipe rolls in pipe order),
|
||||
## and "stop": String when the chain couldn't continue (its summary then
|
||||
## 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 inline references can nest (matches RollContext).
|
||||
## Deepest level a chain can reach before it stops (matches RollContext).
|
||||
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
|
||||
## tables and rolls inline references through the roller. `persistent` is the
|
||||
## collection's persistent variables (name without "@" -> {value, source}),
|
||||
## shared, not copied. `decks` maps table id to DeckState for card-mode tables,
|
||||
## also shared. Set ctx.prompt to ask the player on choice cards.
|
||||
## also shared.
|
||||
static func new_context(board: TowerBoard, rng: RandomNumberGenerator, persistent: Dictionary = {}, decks: Dictionary = {}) -> RollContext:
|
||||
var ctx := RollContext.new(persistent, rng)
|
||||
ctx.max_depth = MAX_DEPTH
|
||||
ctx.board = board
|
||||
ctx.set_meta("decks", decks)
|
||||
# A weak reference, so the context doesn't keep itself alive through its hooks.
|
||||
# A weak reference, so the context doesn't keep itself alive through its hook.
|
||||
var wr: WeakRef = weakref(ctx)
|
||||
ctx.resolve_table = func(name_or_id: String) -> String:
|
||||
return resolve(board, name_or_id)
|
||||
ctx.roll_table = func(id: String, depth: int) -> Dictionary:
|
||||
var c: RollContext = wr.get_ref()
|
||||
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 {} if c == null else _roll(board, id, depth, c)
|
||||
return ctx
|
||||
|
||||
|
||||
|
|
@ -79,89 +50,20 @@ static func resolve(board: TowerBoard, name_or_id: String) -> String:
|
|||
return ""
|
||||
|
||||
|
||||
## Rolls `table_id` and everything its pipes and references lead to, without
|
||||
## ever waiting: choice cards get the headless answers (Random, min, "").
|
||||
## Rolls `table_id` and everything its pipes and references lead to.
|
||||
## `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.
|
||||
## Without one, a fresh context (no persistent variables) is made around
|
||||
## `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
|
||||
## that saves), "reshuffled" (card deck was refilled for this draw), "inline"
|
||||
## (rolled by a [[reference]] in the parent's text), and the logic-card keys
|
||||
## listed at the top of this file.
|
||||
## (rolled by a [[reference]] in the parent's text).
|
||||
static func roll(board: TowerBoard, table_id: String, rng: RandomNumberGenerator, depth: int = 0, decks: Dictionary = {}, ctx: RollContext = null) -> Dictionary:
|
||||
if ctx == null:
|
||||
ctx = new_context(board, rng, {}, decks)
|
||||
elif not ctx.has_meta("decks"):
|
||||
ctx.set_meta("decks", decks)
|
||||
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 {}
|
||||
return _roll(board, table_id, depth, ctx)
|
||||
|
||||
|
||||
static func _stop(t: RollTable, why: String, extra: Dictionary = {}) -> Dictionary:
|
||||
|
|
@ -170,56 +72,15 @@ static func _stop(t: RollTable, why: String, extra: Dictionary = {}) -> Dictiona
|
|||
return node
|
||||
|
||||
|
||||
static func _attach(f: Dictionary, node: Dictionary, ctx: RollContext) -> void:
|
||||
if str(f.get("save", "")) != "":
|
||||
node["save_as"] = f["save"]
|
||||
(f["parent"]["children"] as Array).append(node)
|
||||
if f.get("top", false):
|
||||
ctx.root = node
|
||||
|
||||
|
||||
## 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():
|
||||
_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:
|
||||
static func _roll(board: TowerBoard, table_id: String, depth: int, ctx: RollContext) -> Dictionary:
|
||||
var t := board.get_table(table_id)
|
||||
if t == null:
|
||||
return {}
|
||||
var rng := ctx.rng
|
||||
if depth > MAX_DEPTH:
|
||||
return _stop(t, "Chain stopped after %d tables" % MAX_DEPTH, {"summary": TextExpander.deep_marker(t.id)})
|
||||
if t.entries.is_empty():
|
||||
return _stop(t, "This table has no results")
|
||||
var index: int
|
||||
var value: int
|
||||
var reshuffled := false
|
||||
|
|
@ -239,11 +100,8 @@ static func _pick_node(t: RollTable, ctx: RollContext) -> Dictionary:
|
|||
index = int(card["index"])
|
||||
value = int(card["value"])
|
||||
elif t.is_ranged():
|
||||
var rv := t.roll_value(ctx)
|
||||
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)
|
||||
value = t.dice_obj().roll(rng)
|
||||
index = t.entry_index_for(value)
|
||||
if index < 0:
|
||||
return _stop(t, "No result for %s" % t.fmt(value), {"value": value})
|
||||
else:
|
||||
|
|
@ -251,225 +109,31 @@ static func _pick_node(t: RollTable, ctx: RollContext) -> Dictionary:
|
|||
if index < 0:
|
||||
return _stop(t, "No result can come up")
|
||||
value = index + 1
|
||||
var node := {"table": t, "index": index, "value": value, "entry": t.entries[index], "children": [],
|
||||
"summary": ""}
|
||||
var e := t.entries[index]
|
||||
ctx.depth = depth + 1
|
||||
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:
|
||||
node["reshuffled"] = true
|
||||
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.
|
||||
static func _pick_weighted(t: RollTable, rng: RandomNumberGenerator) -> int:
|
||||
var total := t.total_weight()
|
||||
|
|
@ -485,8 +149,7 @@ static func _pick_weighted(t: RollTable, rng: RandomNumberGenerator) -> int:
|
|||
|
||||
## 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
|
||||
## some of its entries is fine, and so is a pipe whose count is an expression
|
||||
## (it may come to 0).
|
||||
## some of its entries is fine.
|
||||
static func endless_cycles(board: TowerBoard) -> Array[String]:
|
||||
var done := {}
|
||||
var changed := true
|
||||
|
|
@ -505,43 +168,31 @@ static func endless_cycles(board: TowerBoard) -> Array[String]:
|
|||
return out
|
||||
|
||||
|
||||
static func _entry_finishes(e: TableEntry, board: TowerBoard, done: Dictionary) -> bool:
|
||||
for p in e.pipes:
|
||||
if e.count_expr(p) != "":
|
||||
continue
|
||||
if board.get_table(p) != null and not done.has(p):
|
||||
return false
|
||||
return true
|
||||
|
||||
|
||||
static func _can_finish(t: RollTable, board: TowerBoard, done: Dictionary) -> bool:
|
||||
if t.entries.is_empty() or t.kind == RollTable.KIND_VARIABLE:
|
||||
if t.entries.is_empty():
|
||||
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):
|
||||
if t.is_ranged():
|
||||
if not e.has_range or t.chance(e) <= 0.0:
|
||||
continue
|
||||
if _entry_finishes(e, board, done):
|
||||
elif e.weight <= 0:
|
||||
continue
|
||||
var ok := true
|
||||
for p in e.pipes:
|
||||
if board.get_table(p) != null and not done.has(p):
|
||||
ok = false
|
||||
break
|
||||
if ok:
|
||||
return true
|
||||
if player:
|
||||
return false
|
||||
# No entry can come up at all: the roll just stops.
|
||||
for e in t.entries:
|
||||
if t.can_come_up(e):
|
||||
if (t.is_ranged() and e.has_range and t.chance(e) > 0.0) or (not t.is_ranged() and e.weight > 0):
|
||||
return false
|
||||
return true
|
||||
|
||||
|
||||
## 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.
|
||||
## 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:
|
||||
var t: RollTable = n["table"]
|
||||
var step := {
|
||||
|
|
@ -563,84 +214,42 @@ static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
|
|||
step["reshuffled"] = true
|
||||
if n.has("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
|
||||
|
||||
|
||||
## 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.
|
||||
## The whole chain in the order it was rolled.
|
||||
static func flatten(n: Dictionary, out: Array = [], depth: int = 0) -> Array:
|
||||
if n.is_empty():
|
||||
return out
|
||||
var stack: Array = [[n, depth]]
|
||||
while not stack.is_empty():
|
||||
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])
|
||||
out.append(step_of(n, depth))
|
||||
for c in n["children"]:
|
||||
flatten(c, out, depth + 1)
|
||||
return out
|
||||
|
||||
|
||||
static func reaches(n: Dictionary, table_id: String) -> bool:
|
||||
if n.is_empty():
|
||||
return false
|
||||
var stack: Array = [n]
|
||||
while not stack.is_empty():
|
||||
var node: Dictionary = stack.pop_back()
|
||||
if (node["table"] as RollTable).id == table_id:
|
||||
if (n["table"] as RollTable).id == table_id:
|
||||
return true
|
||||
for c in n["children"]:
|
||||
if reaches(c, table_id):
|
||||
return true
|
||||
stack.append_array(node.get("children", []))
|
||||
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
|
||||
## 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:
|
||||
if n.is_empty():
|
||||
if n.is_empty() or n.has("stop"):
|
||||
return
|
||||
var stack: Array = [n]
|
||||
while not stack.is_empty():
|
||||
var node: Dictionary = stack.pop_back()
|
||||
if node.is_empty() or node.has("stop"):
|
||||
continue
|
||||
var t: RollTable = node["table"]
|
||||
var e: TableEntry = node["entry"]
|
||||
var t: RollTable = n["table"]
|
||||
var e: TableEntry = n["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")):
|
||||
texts[entry_key(t.id, e.id)] = str(n.get("summary", e.text))
|
||||
for c in n["children"]:
|
||||
pipes[link_key(t.id, e.id, c)] = true
|
||||
for k in range(kids.size() - 1, -1, -1):
|
||||
stack.append(kids[k])
|
||||
collect_lit(c, entries, pipes, texts)
|
||||
|
||||
|
||||
static func entry_key(table_id: String, entry_id: String) -> String:
|
||||
|
|
@ -678,30 +287,3 @@ static func ref_targets(board: TowerBoard, text: String) -> Array[String]:
|
|||
if id != "" and not out.has(id):
|
||||
out.append(id)
|
||||
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,25 +47,14 @@ func clear_deck(cid: String, tid: String) -> void:
|
|||
|
||||
|
||||
# ---------- Persistent variables ----------
|
||||
# {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.
|
||||
# {name: {"value": String, "source": table_id}}
|
||||
|
||||
func get_variables(cid: String) -> Dictionary:
|
||||
var v: Variant = _section("variables").get(cid, {})
|
||||
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
|
||||
return (v as Dictionary).duplicate(true) if v is Dictionary else {}
|
||||
|
||||
|
||||
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)
|
||||
func set_variable(cid: String, var_name: String, value: String, source: String = "") -> void:
|
||||
_bucket("variables", cid)[var_name] = {"value": value, "source": source}
|
||||
_dirty = true
|
||||
|
||||
|
|
|
|||
|
|
@ -4,8 +4,6 @@ extends RefCounted
|
|||
## ranged (dice) table it covers a span of die values such as 01–30.
|
||||
|
||||
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 text: String = ""
|
||||
|
|
@ -14,13 +12,9 @@ var details: String = ""
|
|||
## Relative chance on a plain table; also the number of copies in card mode.
|
||||
## 0 means it never comes up. Ignored on ranged tables.
|
||||
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).
|
||||
var pipes: Array[String] = []
|
||||
## 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.
|
||||
## target table id -> how many times to roll it (missing = 1).
|
||||
var pipe_count: Dictionary = {}
|
||||
## target table id -> variable name to save the result under (missing = none).
|
||||
var pipe_save: Dictionary = {}
|
||||
|
|
@ -39,39 +33,9 @@ func span() -> int:
|
|||
return range_hi - range_lo + 1 if has_range else 1
|
||||
|
||||
|
||||
## How many times the pipe to `target` rolls. An expression count reads as 1
|
||||
## here; see count_expr() and count_value().
|
||||
## How many times the pipe to `target` rolls.
|
||||
func count_for(target: String) -> int:
|
||||
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)
|
||||
return clampi(int(pipe_count.get(target, 1)), 1, MAX_PIPE_COUNT)
|
||||
|
||||
|
||||
## Variable name the pipe to `target` saves into, or "".
|
||||
|
|
@ -79,23 +43,12 @@ func save_for(target: String) -> String:
|
|||
return str(pipe_save.get(target, ""))
|
||||
|
||||
|
||||
## Sets the count: an int (clamped 1..99), or a String that is either a whole
|
||||
## number or an expression.
|
||||
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:
|
||||
func set_pipe_count(target: String, n: int) -> void:
|
||||
n = clampi(n, 1, MAX_PIPE_COUNT)
|
||||
if n == 1:
|
||||
pipe_count.erase(target)
|
||||
else:
|
||||
pipe_count[target] = k
|
||||
pipe_count[target] = n
|
||||
|
||||
|
||||
func set_pipe_save(target: String, name: String) -> void:
|
||||
|
|
@ -106,8 +59,8 @@ func set_pipe_save(target: String, name: String) -> void:
|
|||
pipe_save[target] = name
|
||||
|
||||
|
||||
## Adds a pipe if it isn't there already. `count` is an int or an expression.
|
||||
func add_pipe(target: String, count: Variant = 1, save_as: String = "") -> void:
|
||||
## Adds a pipe if it isn't there already.
|
||||
func add_pipe(target: String, count: int = 1, save_as: String = "") -> void:
|
||||
if not pipes.has(target):
|
||||
pipes.append(target)
|
||||
set_pipe_count(target, count)
|
||||
|
|
@ -127,21 +80,16 @@ func to_dict() -> Dictionary:
|
|||
d["details"] = details
|
||||
if weight != 1:
|
||||
d["weight"] = weight
|
||||
if effects != "":
|
||||
d["effects"] = effects
|
||||
if not pipes.is_empty():
|
||||
var list: Array = []
|
||||
for p in pipes:
|
||||
var expr := count_expr(p)
|
||||
var n := count_for(p)
|
||||
var s := save_for(p)
|
||||
if expr == "" and n == 1 and s == "":
|
||||
if n == 1 and s == "":
|
||||
list.append(p)
|
||||
else:
|
||||
var po := {"table": p}
|
||||
if expr != "":
|
||||
po["count"] = expr
|
||||
elif n != 1:
|
||||
if n != 1:
|
||||
po["count"] = n
|
||||
if s != "":
|
||||
po["save_as"] = s
|
||||
|
|
@ -156,13 +104,11 @@ static func from_dict(d: Dictionary) -> TableEntry:
|
|||
var e := TableEntry.new(str(d.get("id", "")), str(d.get("text", "")))
|
||||
e.details = str(d.get("details", ""))
|
||||
e.weight = maxi(0, int(d.get("weight", 1)))
|
||||
e.effects = str(d.get("effects", ""))
|
||||
for p: Variant in d.get("pipes", []):
|
||||
if p is Dictionary:
|
||||
var target := str(p.get("table", ""))
|
||||
if target != "":
|
||||
var c: Variant = p.get("count", 1)
|
||||
e.add_pipe(target, c if c is String else int(c), str(p.get("save_as", "")))
|
||||
e.add_pipe(target, int(p.get("count", 1)), str(p.get("save_as", "")))
|
||||
elif str(p) != "":
|
||||
e.add_pipe(str(p))
|
||||
var r: Variant = d.get("range")
|
||||
|
|
|
|||
|
|
@ -9,11 +9,8 @@ extends RefCounted
|
|||
## [[Table -> @var]] ...and save it as persistent variable "@var"
|
||||
## [[3x Gems]] roll 3 times, joined with ", "
|
||||
## [[1d4 Coins]] roll 1d4 for the count (NdM, NdM+K, NdM-K)
|
||||
## {var} {@var} insert a saved value (numbers without ".0")
|
||||
## {var} {@var} insert a saved value
|
||||
## {@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
|
||||
## pop-ups through RichTextLabel's meta_hover_started signal:
|
||||
|
|
@ -22,24 +19,17 @@ extends RefCounted
|
|||
## [url=missing:<name>]⚠ <name>[/url] a table that doesn't exist
|
||||
## [url=unset:<name>]{<name>?}[/url] a variable that isn't set
|
||||
## [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
|
||||
## [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.
|
||||
## 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.
|
||||
const MAX_REPEAT := 100
|
||||
const DEEP_TEXT := "⚠ chain too deep"
|
||||
|
||||
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 _SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$"
|
||||
|
||||
|
|
@ -50,26 +40,7 @@ static var _res: Dictionary = {}
|
|||
## text: String the expanded BBCode, with open tags closed at the end
|
||||
## children: Array the result nodes rolled inline, in order (one per roll,
|
||||
## 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:
|
||||
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 children: Array = []
|
||||
var i: int = 0
|
||||
|
|
@ -80,10 +51,7 @@ static func expand_async(text: String, ctx: RollContext, live: bool = false) ->
|
|||
if i + 1 < n and text[i + 1] == "[":
|
||||
var ref: Dictionary = _ref_at(text, i)
|
||||
if not ref.is_empty():
|
||||
if live:
|
||||
out += _live_ref(ref, ctx)
|
||||
else:
|
||||
out += await _expand_ref(ref, ctx, children)
|
||||
out += _expand_ref(ref, ctx, children)
|
||||
i = ref["end"]
|
||||
continue
|
||||
out += c
|
||||
|
|
@ -95,23 +63,9 @@ static func expand_async(text: String, ctx: RollContext, live: bool = false) ->
|
|||
i += (tag["raw"] as String).length()
|
||||
continue
|
||||
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)
|
||||
if m != null and m.get_start() == i:
|
||||
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)
|
||||
out += _expand_var(m.get_string(1), m.get_string(2).strip_edges(), ctx, children)
|
||||
i = m.get_end()
|
||||
continue
|
||||
out += c
|
||||
|
|
@ -119,59 +73,6 @@ static func expand_async(text: String, ctx: RollContext, live: bool = false) ->
|
|||
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
|
||||
## appearance and without duplicates. Covers [[...]] references (minus any count
|
||||
## prefix and "-> var" part) and the table in {@var|Table}. With a resolver
|
||||
|
|
@ -306,13 +207,11 @@ static func _expand_ref(ref: Dictionary, ctx: RollContext, children: Array) -> S
|
|||
var pieces: PackedStringArray = []
|
||||
var plain: PackedStringArray = []
|
||||
for _k in times:
|
||||
if ctx.halted != "":
|
||||
break
|
||||
var piece: Dictionary = await _roll_one(id, ctx, children)
|
||||
var piece: Dictionary = _roll_one(id, ctx, children)
|
||||
pieces.append(piece["text"])
|
||||
plain.append(piece["value"])
|
||||
var save_as: String = ref["save"]
|
||||
if save_as != "" and ctx.halted == "":
|
||||
if save_as != "":
|
||||
ctx.save(save_as, ", ".join(plain), id)
|
||||
return ", ".join(pieces)
|
||||
|
||||
|
|
@ -326,9 +225,7 @@ static func _expand_var(name: String, table: String, ctx: RollContext, children:
|
|||
var id: String = ctx.resolve(table)
|
||||
if id == "":
|
||||
return missing_marker(table)
|
||||
if ctx.halted != "":
|
||||
return unset_marker(name)
|
||||
var piece: Dictionary = await _roll_one(id, ctx, children)
|
||||
var piece: Dictionary = _roll_one(id, ctx, children)
|
||||
if not piece["rolled"]:
|
||||
return piece["text"]
|
||||
ctx.save(name, piece["value"], id)
|
||||
|
|
@ -341,23 +238,19 @@ static func _roll_one(id: String, ctx: RollContext, children: Array) -> Dictiona
|
|||
if ctx.depth > ctx.max_depth:
|
||||
var deep: String = deep_marker(id)
|
||||
return {"text": deep, "value": DEEP_TEXT, "rolled": false}
|
||||
var node: Dictionary = await ctx.roll_async(id)
|
||||
var node: Dictionary = ctx.roll(id)
|
||||
if node.is_empty():
|
||||
var missing: String = missing_marker(id)
|
||||
return {"text": missing, "value": "", "rolled": false}
|
||||
children.append(node)
|
||||
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 {
|
||||
"text": "[url=table:%s]%s[/url]" % [id, summary],
|
||||
"value": value,
|
||||
"value": Formatter.to_export_bbcode(summary),
|
||||
"rolled": true,
|
||||
}
|
||||
|
||||
|
||||
|
||||
static func _re(pattern: String) -> RegEx:
|
||||
if not _res.has(pattern):
|
||||
var re := RegEx.new()
|
||||
|
|
|
|||
166
docs/LOGIC.md
166
docs/LOGIC.md
|
|
@ -1,166 +0,0 @@
|
|||
# TableTower — Logic Cards
|
||||
|
||||
**Status:** Draft spec · **Applies to:** branch `logic-cards` · **Extends:** `docs/DESIGN.md`
|
||||
|
||||
Plain roll tables answer "what happens?". Logic cards let a board also ask the player,
|
||||
remember state, repeat steps and print a summary, so a whole procedure such as rolling a
|
||||
Traveller character can run as one chain.
|
||||
|
||||
## 1. Card kinds
|
||||
|
||||
Every table has a `kind`. Existing tables are `roll`.
|
||||
|
||||
| Kind | What it does when the chain reaches it | Card shows |
|
||||
|---|---|---|
|
||||
| `roll` | Rolls an entry (weighted, or ranged with a dice expression). Unchanged, except ranged tables now accept full expressions (§4) | Entries, die button |
|
||||
| `choice` | Pauses the roll and asks the player (§2) | The question and its options |
|
||||
| `loop` | Runs its **Each time** entry repeatedly, then its **Afterwards** entry once (§3) | The loop rule and two rows |
|
||||
| `variable` | Never rolled. Declares a variable with a type, a starting value and a description (§5) | The variable's live value |
|
||||
| `sheet` | Prints its template with current values (§6) | The template, rendered live |
|
||||
|
||||
Every kind except `variable` can be the start of a roll and can be the target of a pipe.
|
||||
Every entry, of any kind, can carry **effects** (§5.2) and pipes. Pipes keep their count and
|
||||
"save as" options, and a pipe count may now be an expression (`@terms`, `1d3`).
|
||||
|
||||
## 2. Choice cards
|
||||
|
||||
A choice card pauses the chain and shows a pop-up. Its `prompt` is BBCode with `{@var}`
|
||||
expansion, so a question can say "Your EDU is {@edu}. Which career?".
|
||||
|
||||
| `choice` | The player… | Result text | Stored as |
|
||||
|---|---|---|---|
|
||||
| `pick` (which option) | picks one of the card's entries, or **Random** (always offered) | the picked entry, exactly as if it had been rolled: its effects run, its text expands, its pipes follow | `save_as` (optional) gets the entry's plain text |
|
||||
| `number` (how many) | types a whole number between `min` and `max` (expressions; defaults 0 and 99) | the number | `save_as`, and the chain variable `answer` |
|
||||
| `text` (open ended) | types any text | the text | `save_as`, and the chain variable `answer` |
|
||||
|
||||
`number` and `text` cards have exactly one entry, named **Answer**. Its effects and pipes run
|
||||
after the player answers, so `@terms += @answer` style bookkeeping and "go on to the next
|
||||
step" pipes live there. Random on a `pick` card rolls the card normally, honouring weights
|
||||
or ranges.
|
||||
|
||||
The pop-up also has **Cancel**, which stops the whole roll with a visible "Cancelled" marker.
|
||||
Fast roll (Shift-click) still asks questions, because they are the player's decisions.
|
||||
|
||||
## 3. Loop cards
|
||||
|
||||
A loop card has a `loop` mode and a `loop_expr` expression, plus two fixed entries:
|
||||
**Each time** (index 0) and **Afterwards** (index 1).
|
||||
|
||||
| `loop` | Behaviour |
|
||||
|---|---|
|
||||
| `times` | Evaluates `loop_expr` once (e.g. `@answer`, `3`, `1d3`) and runs Each time that many times (0 is allowed) |
|
||||
| `while` | Before each pass, evaluates the condition; stops when it's false |
|
||||
| `until` | Runs Each time, then evaluates the condition; stops when it's true (runs at least once) |
|
||||
|
||||
The chain variable `i` holds the pass number (1, 2, …) during Each time. A loop's node text
|
||||
reads "Repeated N times". Pipes may also form cycles (a table piping back to an earlier one).
|
||||
Both are bounded only by the action limit.
|
||||
|
||||
## 4. Expressions
|
||||
|
||||
Expressions appear in loop rules, pipe counts, `min`/`max`, dice fields and effects. They are
|
||||
evaluated with Godot's `Expression`, after a small rewrite.
|
||||
|
||||
- **Numbers and text:** `12`, `-3`, `"Aslan"`
|
||||
- **Operators:** `+ - * / %`, comparisons `= == != < <= > >=` (a lone `=` in a condition means
|
||||
equals), `and or not` (also `&& || !`), parentheses, and `in` for "text contains".
|
||||
- **Variables:**
|
||||
- `@name` reads a board variable (§5). If it's unset, it reads as `0` in arithmetic and as
|
||||
`""` next to text.
|
||||
- A bare `name` reads a chain variable (`answer`, `i`, or anything saved with `-> name`).
|
||||
- **Dice:** `2d6`, `d20`, `3D`, `D3`, `2D`. A missing count means 1, and missing sides mean 6, so
|
||||
`2D` is 2d6. Every die in an expression is rolled fresh.
|
||||
- **Functions:** `min max clamp abs floor ceil round`, plus:
|
||||
- `dm(x)`: the 2D-game characteristic modifier. It gives -3 for 0, -2 for 1–2, -1 for 3–5,
|
||||
0 for 6–8, +1 for 9–11, +2 for 12–14, and +3 for 15 or more.
|
||||
- `has(list, item)`: whether a comma-separated list contains an item.
|
||||
- `count(prefix)`: the number of set variables whose names start with `prefix`.
|
||||
- `if(condition, then, else)`: picks a value. Both branches are evaluated, so dice in
|
||||
either are rolled. The inline `a if c else b` form is refused, because Godot's
|
||||
Expression returns the wrong branch for it.
|
||||
|
||||
Ranged `roll` tables keep plain dice (`2d6`) and also accept any expression, such as
|
||||
`2d6 + dm(@end)` or `@terms`. Values beyond the lowest or highest range clamp to that range,
|
||||
so a check table only needs "2–6 fail" and "7–12 pass". The card labels the ends `≤6` and `7+`
|
||||
when the expression has modifiers.
|
||||
|
||||
## 5. Variables
|
||||
|
||||
### 5.1 Board variables (`@name`)
|
||||
- They belong to the collection and are kept between rolls in local state, never exported.
|
||||
Values are numbers or text.
|
||||
- Names are lowercase letters, digits and `_`. A variable exists once it's assigned; no
|
||||
declaration is needed. A **variable card** (`kind: variable`) is optional and gives a
|
||||
variable a label, a type (`number`, `text` or `list`), a starting value (an expression) and
|
||||
details.
|
||||
- `reset @name` sets a declared variable back to its starting value, or deletes an undeclared
|
||||
one. `reset @skill_*` resets every variable with that prefix.
|
||||
- Chain variables (no `@`, e.g. `answer`, `i`, `-> hero`) last for one top-level roll, as
|
||||
before.
|
||||
|
||||
### 5.2 Effects
|
||||
An entry's `effects` field holds statements, one per line or separated by `;`. They run when
|
||||
the entry is chosen (rolled, picked or answered), before its text expands and its pipes
|
||||
follow.
|
||||
|
||||
```
|
||||
@str = 2d6 set
|
||||
@terms += 1 add (number) · append ", item" if not present (text/list)
|
||||
@credits -= 1000 subtract (number) · remove the item (text/list)
|
||||
@age *= 2 multiply (/= divides, rounding down)
|
||||
@skill_pilot += 1 unset counts as 0, so this gives Pilot 1 or raises it
|
||||
@skill_vacc_suit = max(@skill_vacc_suit, 0) gain at level 0
|
||||
@traits += "Psionic"
|
||||
reset @skill_*
|
||||
```
|
||||
|
||||
Each statement that runs is listed under its step in the result tray (e.g. "STR = 9"). A bad
|
||||
statement shows a red marker in the tray and in Build mode rather than stopping the roll.
|
||||
|
||||
### 5.3 Text
|
||||
- `{@name}` shows a value. If it's unset, it shows the `{@name?}` marker.
|
||||
- `{@skill_*}` lists every set variable with that prefix, sorted, as `Gun Combat 1, Pilot 0`.
|
||||
The name after the prefix is title-cased, with `_` read as a space.
|
||||
- `{= expr}` shows a computed value, e.g. `STR {@str} ({= dm(@str)})`.
|
||||
- The existing `{@var|Table}`, `{hero}` and `[[refs]]` work as before.
|
||||
|
||||
## 6. Sheet cards
|
||||
A sheet card holds one template (its single entry's text, multi-line BBCode). On the board it
|
||||
always shows the template rendered with current values, so a character sheet stays up to
|
||||
date while the chain runs. When the chain reaches it, the rendered template becomes that
|
||||
step's result.
|
||||
|
||||
## 7. Limits
|
||||
- **Actions:** one top-level roll may take at most **10,000 actions**. One action is a table
|
||||
being rolled or answered, or one loop pass. Past that, the roll stops with "Stopped after
|
||||
10,000 actions", and everything up to that point is kept.
|
||||
- **Inline references:** `[[refs]]` inside text still nest at most 32 deep.
|
||||
- **Implementation:** pipes and loops must not use GDScript recursion proportional to chain
|
||||
length. Long chains (thousands of steps) must not overflow the call stack. That applies to
|
||||
the roller and to everything that walks a result (flatten, lighting, history).
|
||||
|
||||
## 8. Rolling, prompts and display
|
||||
- The roller is a coroutine. It `await`s `ctx.prompt.call(request)` whenever a choice card is
|
||||
reached. With no prompt hook (tests, headless), `pick` chooses Random, `number` answers
|
||||
`min`, and `text` answers `""`.
|
||||
- **Request:** `{table_id, kind, prompt, options: [{index, text, details}], min, max, default}`.
|
||||
- **Reply:** `pick` returns an entry index or `-1` for Random. `number` returns an int.
|
||||
`text` returns a String. `null` means Cancel.
|
||||
- In the UI, when a prompt is needed, the steps so far appear instantly (lit on the board and
|
||||
in the tray) before the pop-up opens, so the player can see what led to the question.
|
||||
After the last answer the rest of the roll is shown at once. A roll with no questions
|
||||
animates as before, unless it's long (more than 40 steps), when it shows at once.
|
||||
- The tray shows the last 12 steps of a long chain behind a "+N earlier steps" note. If the
|
||||
chain reached a sheet card, the result headline is that sheet.
|
||||
|
||||
## 9. File format additions
|
||||
Table keys:
|
||||
- `kind` (`roll` is the default and is omitted)
|
||||
- `choice`, `prompt`, `save_as`, `min`, `max` (choice cards)
|
||||
- `loop`, `loop_expr` (loop cards)
|
||||
- `var_name`, `var_type`, `initial` (variable cards)
|
||||
|
||||
Entry keys:
|
||||
- `effects` (String)
|
||||
|
||||
Pipe objects may have `"count": "<expression>"`.
|
||||
|
|
@ -1,144 +0,0 @@
|
|||
{
|
||||
"format_version": 2,
|
||||
"id": "logic-demo",
|
||||
"name": "Logic demo",
|
||||
"tables": [
|
||||
{
|
||||
"id": "start",
|
||||
"name": "Start a delve",
|
||||
"x": 40,
|
||||
"y": 40,
|
||||
"details": "Click the die to send a new delver down the stairs. It resets the variables, then asks two questions.",
|
||||
"entries": [
|
||||
{
|
||||
"id": "e1",
|
||||
"text": "A new delver steps up",
|
||||
"effects": "reset @hp; reset @gold; reset @luck; reset @loot",
|
||||
"pipes": ["name_q"]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "v_hp",
|
||||
"name": "Hit points",
|
||||
"kind": "variable",
|
||||
"x": 40,
|
||||
"y": 640,
|
||||
"details": "Traps and fights take these away.",
|
||||
"var_name": "hp",
|
||||
"initial": "10",
|
||||
"entries": []
|
||||
},
|
||||
{
|
||||
"id": "v_gold",
|
||||
"name": "Gold",
|
||||
"kind": "variable",
|
||||
"x": 360,
|
||||
"y": 640,
|
||||
"var_name": "gold",
|
||||
"initial": "0",
|
||||
"entries": []
|
||||
},
|
||||
{
|
||||
"id": "v_luck",
|
||||
"name": "Luck",
|
||||
"kind": "variable",
|
||||
"x": 680,
|
||||
"y": 640,
|
||||
"details": "Added to every room check.",
|
||||
"var_name": "luck",
|
||||
"initial": "0",
|
||||
"entries": []
|
||||
},
|
||||
{
|
||||
"id": "v_loot",
|
||||
"name": "Loot",
|
||||
"kind": "variable",
|
||||
"x": 1000,
|
||||
"y": 640,
|
||||
"var_name": "loot",
|
||||
"var_type": "list",
|
||||
"entries": []
|
||||
},
|
||||
{
|
||||
"id": "name_q",
|
||||
"name": "Name your delver",
|
||||
"kind": "choice",
|
||||
"choice": "text",
|
||||
"prompt": "Who goes down the stairs?",
|
||||
"save_as": "@name",
|
||||
"x": 360,
|
||||
"y": 40,
|
||||
"entries": [
|
||||
{ "id": "e1", "text": "Answer", "pipes": ["rooms_q"] }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "rooms_q",
|
||||
"name": "How many rooms?",
|
||||
"kind": "choice",
|
||||
"choice": "number",
|
||||
"prompt": "[b]{@name}[/b] studies the map. How many rooms will they try?",
|
||||
"save_as": "@rooms",
|
||||
"min": "1",
|
||||
"max": "5",
|
||||
"x": 360,
|
||||
"y": 270,
|
||||
"entries": [
|
||||
{ "id": "e1", "text": "Answer", "pipes": ["explore"] }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "explore",
|
||||
"name": "Explore",
|
||||
"kind": "loop",
|
||||
"loop_expr": "@rooms",
|
||||
"x": 680,
|
||||
"y": 40,
|
||||
"details": "One room check per room the player chose, then the way out.",
|
||||
"entries": [
|
||||
{ "id": "e1", "text": "Room {i}", "pipes": ["room_check"] },
|
||||
{ "id": "e2", "text": "Head back up", "pipes": ["way_out"] }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "room_check",
|
||||
"name": "Room check",
|
||||
"x": 1000,
|
||||
"y": 40,
|
||||
"dice": "2d6 + @luck",
|
||||
"details": "2d6 plus Luck. Low rolls hurt, high rolls pay.",
|
||||
"entries": [
|
||||
{ "id": "e1", "text": "A trap snaps shut", "effects": "@hp -= 2", "range": [2, 6] },
|
||||
{ "id": "e2", "text": "Dust and echoes", "range": [7, 9] },
|
||||
{ "id": "e3", "text": "A glinting cache", "effects": "@gold += 2d6\n@loot += \"gem\"", "range": [10, 12] }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "way_out",
|
||||
"name": "Way out",
|
||||
"kind": "choice",
|
||||
"prompt": "{@name} has {@gold} gold and {@hp} HP left. How do they leave?",
|
||||
"x": 680,
|
||||
"y": 330,
|
||||
"entries": [
|
||||
{ "id": "e1", "text": "Sneak past the guard", "details": "Quiet and slow. Luck grows.", "effects": "@luck += 1", "pipes": ["report"] },
|
||||
{ "id": "e2", "text": "Fight through", "details": "Costs some blood.", "effects": "@hp -= 1d3", "pipes": ["report"] },
|
||||
{ "id": "e3", "text": "Pay the toll", "details": "Ten gold, if they have it.", "effects": "@gold -= min(@gold, 10)", "pipes": ["report"] }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "report",
|
||||
"name": "Delve report",
|
||||
"kind": "sheet",
|
||||
"x": 1000,
|
||||
"y": 330,
|
||||
"entries": [
|
||||
{
|
||||
"id": "e1",
|
||||
"text": "[b]{@name}[/b] the delver\nRooms tried: {@rooms}\nHP {@hp} · Gold {@gold} · Luck {@luck}\nLoot: {@loot}\nScore: {= @gold + @hp * 5}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -7,13 +7,9 @@ extends RefCounted
|
|||
## Canonical collection form:
|
||||
## {"format_version": 2, "id", "name", "tables": [table, ...]}
|
||||
## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode],
|
||||
## [deck_empty], [kind], [choice], [prompt], [save_as], [min], [max],
|
||||
## [loop], [loop_expr], [var_name], [var_type], [initial], entries
|
||||
## 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.
|
||||
## [deck_empty], entries
|
||||
## entry: id, text, [details], [weight], [range], [pipes]
|
||||
## pipe: a table id String, or {"table": id, "count": n, "save_as": name}
|
||||
|
||||
const FORMAT_VERSION := 2
|
||||
|
||||
|
|
@ -122,9 +118,6 @@ static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Di
|
|||
t5["name"] = clean.call(str(t5["name"]))
|
||||
if t5.has("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"):
|
||||
var tags: Array = []
|
||||
for tag in t5["tags"]:
|
||||
|
|
@ -151,8 +144,6 @@ static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Di
|
|||
ed["text"] = clean.call(str(ed["text"]))
|
||||
if ed.has("details"):
|
||||
ed["details"] = clean.call(str(ed["details"]))
|
||||
if ed.has("effects"):
|
||||
ed["effects"] = clean.call(str(ed["effects"]))
|
||||
if ed.has("range"):
|
||||
var r: Array = ed["range"]
|
||||
if int(r[0]) > int(r[1]):
|
||||
|
|
@ -229,18 +220,6 @@ static func _canon_table(td: Dictionary) -> Dictionary:
|
|||
var v: Variant = td.get(key)
|
||||
if v != null and not (v is bool and not v) and not (v is String and v == ""):
|
||||
t[key] = v
|
||||
# Logic cards (docs/LOGIC.md §9). Defaults are left out.
|
||||
var kind := str(td.get("kind", "roll"))
|
||||
if RollTable.KINDS.has(kind) and kind != "roll":
|
||||
t["kind"] = kind
|
||||
var defaults := {"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 src_entries: Variant = td.get("entries", [])
|
||||
if src_entries is Array:
|
||||
|
|
@ -264,9 +243,6 @@ static func _canon_entry(ev: Variant) -> Dictionary:
|
|||
var r: Variant = ed.get("range")
|
||||
if r is Array and (r as Array).size() == 2:
|
||||
e["range"] = [int(_num(r[0], 0)), int(_num(r[1], 0))]
|
||||
var effects := str(ed.get("effects", "")) if ed.get("effects") != null else ""
|
||||
if effects.strip_edges() != "":
|
||||
e["effects"] = effects
|
||||
var src_pipes: Variant = ed.get("pipes", ed.get("triggers", []))
|
||||
var pipes: Array = []
|
||||
if src_pipes is Array:
|
||||
|
|
@ -276,11 +252,7 @@ static func _canon_entry(ev: Variant) -> Dictionary:
|
|||
elif p is Dictionary and str(p.get("table", "")) != "":
|
||||
var np := {"table": str(p["table"])}
|
||||
if p.has("count"):
|
||||
var cnt: Variant = _num(p["count"], null)
|
||||
if cnt == null and p["count"] is String and (p["count"] as String).strip_edges() != "":
|
||||
np["count"] = (p["count"] as String).strip_edges() # an expression
|
||||
else:
|
||||
np["count"] = int(cnt if cnt != null else 1)
|
||||
np["count"] = int(_num(p["count"], 1))
|
||||
if str(p.get("save_as", "")) != "":
|
||||
np["save_as"] = str(p["save_as"])
|
||||
pipes.append(np)
|
||||
|
|
@ -322,26 +294,17 @@ static func unique_id(base: String, used: Dictionary) -> String:
|
|||
return id
|
||||
|
||||
|
||||
## 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).
|
||||
## Normalizes a pipe (String or Dictionary) to {"table", "count", "save_as"}.
|
||||
static func pipe_info(p: Variant) -> Dictionary:
|
||||
if p is Dictionary:
|
||||
var c: Variant = p.get("count", 1)
|
||||
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": ""}
|
||||
return {"table": str(p.get("table", "")), "count": int(_num(p.get("count", 1), 1)), "save_as": str(p.get("save_as", ""))}
|
||||
return {"table": str(p), "count": 1, "save_as": ""}
|
||||
|
||||
|
||||
## Edge label for a pipe: "" (plain), "×2", "→ weapon" or "×2 → weapon"
|
||||
## ("×@terms" for an expression count).
|
||||
## Edge label for a pipe: "" (plain), "×2", "→ weapon" or "×2 → weapon".
|
||||
static func pipe_label(info: Dictionary) -> String:
|
||||
var parts: Array[String] = []
|
||||
if str(info.get("count_expr", "")) != "":
|
||||
parts.append("×" + str(info["count_expr"]))
|
||||
elif int(info["count"]) != 1:
|
||||
if int(info["count"]) != 1:
|
||||
parts.append("×%d" % int(info["count"]))
|
||||
if str(info["save_as"]) != "":
|
||||
parts.append("→ " + str(info["save_as"]))
|
||||
|
|
|
|||
|
|
@ -1,31 +0,0 @@
|
|||
extends SceneTree
|
||||
## if(condition, then, else) in expressions, and the refused inline ternary.
|
||||
## Run: godot --headless --path . -s res://tests/test_expr_if.gd -- --sample
|
||||
|
||||
var _failures := 0
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
_value("if(1 > 2, 10, 20)", 20)
|
||||
_value("if(3 > 2, 10, 20)", 10)
|
||||
_value("if(1 = 1, \"yes\", \"no\")", "yes")
|
||||
_value("if(0, 1, if(1, 2, 3))", 2)
|
||||
_value("5 + if(2 >= 2, 1, 0)", 6)
|
||||
for src in ["10 if 1 > 2 else 20", "1 if true else 2"]:
|
||||
var r := Expr.evaluate(src, null)
|
||||
_check(str(r.get("error", "")).contains("if(condition"), "\"%s\" is refused with a hint (got %s)" % [src, r])
|
||||
_check(Expr.check(src) != "", "Expr.check flags \"%s\"" % src)
|
||||
_check(Expr.check("if(@str > 8, 1, 0)") == "", "if() with a variable passes the check")
|
||||
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
|
||||
quit(1 if _failures else 0)
|
||||
|
||||
|
||||
func _value(src: String, want: Variant) -> void:
|
||||
var r := Expr.evaluate(src, null)
|
||||
_check(str(r.get("error", "")) == "" and r.get("value") == want, "%s = %s (got %s)" % [src, want, r])
|
||||
|
||||
|
||||
func _check(ok: bool, what: String) -> void:
|
||||
if not ok:
|
||||
_failures += 1
|
||||
print(" ✗ ", what)
|
||||
|
|
@ -1 +0,0 @@
|
|||
uid://b7jjpn8bqosv7
|
||||
|
|
@ -1,61 +0,0 @@
|
|||
extends SceneTree
|
||||
## Fast roll (Shift-click): the whole result shows at once, with no animation.
|
||||
## Run: godot --headless --path . -s res://tests/test_fast_roll.gd -- --sample
|
||||
## (--sample keeps the app from reading or writing saved collections.)
|
||||
|
||||
var _failures := 0
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
if not OS.get_cmdline_user_args().has("--sample"):
|
||||
print("Run with -- --sample so the test can't touch saved data.")
|
||||
quit(2)
|
||||
return
|
||||
var main: Main = load("res://ui/main.tscn").instantiate()
|
||||
root.add_child(main)
|
||||
for i in 5:
|
||||
await process_frame
|
||||
if main._saving_enabled:
|
||||
print("Saving is enabled; refusing to roll.")
|
||||
quit(2)
|
||||
return
|
||||
main.rng.seed = 7
|
||||
|
||||
# A fast roll finishes in the same frame it starts.
|
||||
for i in 20:
|
||||
main.start_roll("wilderness", true)
|
||||
var all: Array = main.current["all"]
|
||||
_check(main.current.get("done", false), "fast roll is done immediately")
|
||||
_check(main.current["steps"].size() == all.size(), "fast roll shows every step at once")
|
||||
_check(main.board.pipes.pulse_key == "", "fast roll sends no bead down the pipes")
|
||||
var lit_steps := 0
|
||||
for s: Dictionary in all:
|
||||
if s.has("entry_id") and not s.get("stop", false):
|
||||
lit_steps += 1
|
||||
_check(main.is_entry_lit(str(s["table_id"]), str(s["entry_id"])), "every result on the path is lit")
|
||||
_check(main.lit_entries.size() == lit_steps, "only the path's results are lit")
|
||||
# Chains from Wilderness Travel are a single line, so n results have n - 1 pipes.
|
||||
_check(main.lit_pipes.size() == maxi(0, lit_steps - 1),
|
||||
"each link in the chain lights its pipe (%d pipes, %d results)" % [main.lit_pipes.size(), lit_steps])
|
||||
for c in main.cards.values():
|
||||
_check(not (c as TableCard)._rolling, "no card is left tumbling")
|
||||
|
||||
# A normal roll still animates: it isn't finished in the same frame.
|
||||
main.start_roll("wilderness")
|
||||
_check(not main.current.get("done", false), "a normal roll still animates")
|
||||
|
||||
# A fast roll started mid-animation takes over cleanly.
|
||||
main.start_roll("wilderness", true)
|
||||
_check(main.current.get("done", false), "a fast roll interrupts an animating one")
|
||||
for i in 90:
|
||||
await process_frame
|
||||
_check(main.current.get("done", false) and main.current.get("fast", false), "the interrupted roll doesn't overwrite the fast result")
|
||||
|
||||
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
|
||||
quit(1 if _failures else 0)
|
||||
|
||||
|
||||
func _check(ok: bool, what: String) -> void:
|
||||
if not ok:
|
||||
_failures += 1
|
||||
print(" ✗ ", what)
|
||||
|
|
@ -1 +0,0 @@
|
|||
uid://c6ewfdklnuf1r
|
||||
|
|
@ -148,8 +148,7 @@ func _test_depth_limit() -> void:
|
|||
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(int(deepest["depth"]) == Roller.MAX_DEPTH, "deepest step is at the limit")
|
||||
# Mixed: pipes no longer count toward the depth limit, but the references
|
||||
# still nest at most MAX_DEPTH deep, so the chain ends.
|
||||
# Mixed: pipes and references count the same depth.
|
||||
var ta := _table("ta", "TA", ["[[TB]]"])
|
||||
var tb := _table("tb", "TB", ["pipe"])
|
||||
tb.entries[0].add_pipe("ta")
|
||||
|
|
@ -158,11 +157,7 @@ func _test_depth_limit() -> void:
|
|||
var worst := 0
|
||||
for s in Roller.flatten(n2, []):
|
||||
worst = maxi(worst, int(s["depth"]))
|
||||
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])
|
||||
_check(worst <= Roller.MAX_DEPTH + 1, "mixed pipes and refs never go past the limit (%d)" % worst)
|
||||
|
||||
|
||||
func _test_missing_and_unset() -> void:
|
||||
|
|
|
|||
|
|
@ -1,730 +0,0 @@
|
|||
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 +0,0 @@
|
|||
uid://ce2yfyfufj47e
|
||||
|
|
@ -1,440 +0,0 @@
|
|||
extends SceneTree
|
||||
## Logic cards in the app: the choice pop-up, progress while it's open,
|
||||
## cancelling, a new roll replacing an open question, live variable and sheet
|
||||
## cards, the long-chain tray and the Build-mode settings rules.
|
||||
## Run: godot --headless --path . -s res://tests/test_logic_ui.gd -- --sample
|
||||
## (--sample keeps the app from reading or writing saved collections.)
|
||||
|
||||
const DEMO := "res://examples/logic_demo.json"
|
||||
|
||||
var _failures := 0
|
||||
var main: Main
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
if not OS.get_cmdline_user_args().has("--sample"):
|
||||
print("Run with -- --sample so the test can't touch saved data.")
|
||||
quit(2)
|
||||
return
|
||||
main = load("res://ui/main.tscn").instantiate()
|
||||
root.add_child(main)
|
||||
for i in 5:
|
||||
await process_frame
|
||||
if main._saving_enabled:
|
||||
print("Saving is enabled; refusing to roll.")
|
||||
quit(2)
|
||||
return
|
||||
main.rng.seed = 11
|
||||
|
||||
_test_demo_file()
|
||||
await _load_demo()
|
||||
_test_cards()
|
||||
await _test_scripted()
|
||||
await _test_dialog_answers()
|
||||
await _test_cancel()
|
||||
await _test_replace()
|
||||
await _test_keys()
|
||||
await _test_live_edits()
|
||||
_test_settings_rules()
|
||||
_test_add_kinds()
|
||||
await _test_long_chain()
|
||||
await _test_action_limit()
|
||||
|
||||
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
|
||||
quit(1 if _failures else 0)
|
||||
|
||||
|
||||
func _load_demo() -> void:
|
||||
main.prompt_hook = main._ask_player
|
||||
await main._load_board_file(DEMO)
|
||||
for i in 3:
|
||||
await process_frame
|
||||
|
||||
|
||||
## A prompt hook answering from a script by kind (scripts can be Callables).
|
||||
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
|
||||
|
||||
|
||||
func _var(name: String) -> Variant:
|
||||
var v: Variant = main.persistent_vars.get(name)
|
||||
return (v as Dictionary).get("value") if v is Dictionary else null
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- demo file
|
||||
|
||||
func _test_demo_file() -> void:
|
||||
var text := FileAccess.get_file_as_string(DEMO)
|
||||
var r := IoMenu.parse_import(text, IoMenu.detect_format("logic_demo.json", text))
|
||||
_check(r["ok"] and (r["errors"] as Array).is_empty(), "the demo imports through Board ▾ → Import: %s" % str(r["errors"]))
|
||||
var b := TowerBoard.new()
|
||||
_check(b.load_json(text), "the demo loads as a board")
|
||||
var kinds := {}
|
||||
for t in b.tables:
|
||||
kinds[t.kind + ("/" + t.choice if t.kind == "choice" else "")] = true
|
||||
for k in ["roll", "choice/pick", "choice/number", "choice/text", "loop", "variable", "sheet"]:
|
||||
_check(kinds.has(k), "the demo has a %s card" % k)
|
||||
var check := b.get_table("room_check")
|
||||
_check(check != null and check.is_expr_dice(), "the demo has an expression check table")
|
||||
_check(not b.to_json().to_lower().contains("traveller"), "the demo is original")
|
||||
|
||||
|
||||
func _test_cards() -> void:
|
||||
var check := main.card_for("room_check")
|
||||
_check(check != null and check.rows.size() == 3, "the check table shows its three ranges")
|
||||
var nums: Array = []
|
||||
for eid: String in check._row_parts:
|
||||
var num: Label = check._row_parts[eid]["num"]
|
||||
nums.append(num.text if num else "")
|
||||
_eq(nums, ["≤6", "7–9", "10+"], "expression dice label the ends ≤N and N+")
|
||||
var loop := main.card_for("explore")
|
||||
_check(loop.rows.size() == 2 and loop.anchor_for("e1").size() > 0 and loop.anchor_for("e2").size() > 0,
|
||||
"a loop card has Each time and Afterwards rows with outlets")
|
||||
_eq(TableCard.loop_rule(loop.table), "× @rooms", "the loop rule reads × @rooms")
|
||||
var hp := main.card_for("v_hp")
|
||||
_check(hp.rows.is_empty() and hp.anchor_for("x").is_empty(), "a variable card has no outlets")
|
||||
var sheet := main.card_for("report")
|
||||
_check(sheet.rows.size() == 1 and not sheet.anchor_for("e1").is_empty(), "a sheet card has one outlet")
|
||||
_eq(TableCard.effect_summary("@hp -= 2\n@gold += 1; @luck = 3", main.data), "Hit points -= 2 · Gold += 1 · +1",
|
||||
"effect summaries use the variable card's name")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- prompts
|
||||
|
||||
func _test_scripted() -> void:
|
||||
var log: Array = []
|
||||
main.prompt_hook = _scripted({"text": "Brin", "number": 3, "pick": 1}, log)
|
||||
main.start_roll("start")
|
||||
_eq(log.size(), 3, "three questions: name, rooms, way out")
|
||||
var kinds: Array = []
|
||||
for r: Dictionary in log:
|
||||
kinds.append(r["kind"])
|
||||
_eq(kinds, ["text", "number", "pick"], "asked in chain order")
|
||||
_check(main.current.get("done", false), "a roll with questions shows at once after the last answer")
|
||||
_eq(_var("name"), "Brin", "text answer saved")
|
||||
_eq(_var("rooms"), 3, "number answer saved")
|
||||
var passes := 0
|
||||
for s: Dictionary in main.current["all"]:
|
||||
if s.has("pass"):
|
||||
passes += 1
|
||||
_eq(passes, 3, "the number answer drives the loop")
|
||||
var last: Dictionary = (main.current["all"] as Array).back()
|
||||
_eq(last.get("table_id"), "report", "the chain ends at the sheet")
|
||||
_check(main.tray._headline.visible and Formatter.strip_tags(main.tray._headline_text.text).begins_with("Brin the delver"),
|
||||
"the tray headline is the rendered sheet")
|
||||
# Option 1 is "Fight through", which costs 1d3 HP.
|
||||
var picked := false
|
||||
for s: Dictionary in main.current["all"]:
|
||||
if s.get("table_id") == "way_out" and s.get("picked", false) and Formatter.strip_tags(str(s["text"])) == "Fight through":
|
||||
picked = true
|
||||
_check(picked, "the picked option is the step")
|
||||
# Live cards after the roll.
|
||||
var hp := main.card_for("v_hp")
|
||||
_eq(hp._var_value.text, Expr.format_value(_var("hp")), "the HP card shows the new value after the roll")
|
||||
var sheet := main.card_for("report")
|
||||
_check(Formatter.strip_tags(sheet._sheet_label.text).contains("HP %s" % Expr.format_value(_var("hp"))), "the sheet card is up to date")
|
||||
_check(Formatter.strip_tags(sheet._sheet_label.text).begins_with("Brin the delver"), "the sheet shows the name")
|
||||
main.prompt_hook = main._ask_player
|
||||
|
||||
|
||||
func _test_dialog_answers() -> void:
|
||||
main.start_roll("start", true)
|
||||
await process_frame
|
||||
var d := main.pending_choice()
|
||||
_check(d != null and d.kind == "text", "the text pop-up opens (fast roll still asks)")
|
||||
if d == null:
|
||||
return
|
||||
_eq(d.title_label.text, "Name your delver", "pop-up title")
|
||||
# Partial progress is lit before the pop-up: the start card's result.
|
||||
_check(main.is_entry_lit("start", "e1"), "steps so far are lit while the question is open")
|
||||
_check(not main.is_entry_lit("name_q", "e1"), "the question's own row isn't lit yet")
|
||||
_check((main.current["steps"] as Array).size() == 1 and str(main.current.get("asking", "")) == "Name your delver",
|
||||
"the tray shows the steps so far and the open question")
|
||||
d._text.text = "Ann"
|
||||
d._confirm()
|
||||
await process_frame
|
||||
d = main.pending_choice()
|
||||
_check(d != null and d.kind == "number", "then the number pop-up")
|
||||
if d == null:
|
||||
return
|
||||
_check(main.is_entry_lit("name_q", "e1") and main.is_entry_lit("start", "e1"), "progress grows with each answer")
|
||||
_check(d._spin.min_value == 1 and d._spin.max_value == 5 and int(d._spin.value) == 1, "number pop-up has min, max and default")
|
||||
d._spin.value = 2
|
||||
d._confirm()
|
||||
await process_frame
|
||||
d = main.pending_choice()
|
||||
_check(d != null and d.kind == "pick" and d._options.size() == 3, "then the pick pop-up with three options")
|
||||
if d == null:
|
||||
return
|
||||
_check(main.is_entry_lit("explore", "e1") and main.is_entry_lit("explore", "e2"), "the loop's steps are lit before the pick")
|
||||
d.answer(-1)
|
||||
await process_frame
|
||||
_check(main.pending_choice() == null and main.current.get("done", false), "Random finishes the roll")
|
||||
_eq(_var("name"), "Ann", "typed name saved")
|
||||
_eq(_var("rooms"), 2, "typed number saved")
|
||||
var random := false
|
||||
for s: Dictionary in main.current["all"]:
|
||||
if s.get("table_id") == "way_out" and s.get("random", false):
|
||||
random = true
|
||||
_check(random, "Random rolls the pick card normally")
|
||||
|
||||
|
||||
func _test_cancel() -> void:
|
||||
main.start_roll("start")
|
||||
await process_frame
|
||||
var d := main.pending_choice()
|
||||
_check(d != null, "a pop-up is open")
|
||||
if d == null:
|
||||
return
|
||||
d.close() # Esc does this
|
||||
await process_frame
|
||||
_check(main.pending_choice() == null, "Esc closes the pop-up")
|
||||
_eq(main.current.get("halted", ""), "Cancelled", "Cancel stops the roll with Cancelled")
|
||||
_check(main.current.get("done", false), "the cancelled roll is shown, not left hanging")
|
||||
var last: Dictionary = (main.current["all"] as Array).back()
|
||||
_check(last.get("cancelled", false) and last.get("stop", false), "the chain ends with a Cancelled marker")
|
||||
_check(main.tray._halt.visible and main.tray._halt_label.text.contains("Cancelled"), "the tray says Cancelled")
|
||||
_check(main.rolling_ctx == null, "no roll is left running")
|
||||
# Freeing the dialog some other way also answers Cancel.
|
||||
main.start_roll("start")
|
||||
await process_frame
|
||||
d = main.pending_choice()
|
||||
if d:
|
||||
d.free()
|
||||
await process_frame
|
||||
_check(main.current.get("done", false) and main.current.get("halted", "") == "Cancelled", "a freed pop-up cancels its roll instead of hanging")
|
||||
|
||||
|
||||
func _test_replace() -> void:
|
||||
main.start_roll("start")
|
||||
await process_frame
|
||||
var first := main.pending_choice()
|
||||
_check(first != null, "first roll asks")
|
||||
var first_reply := first.reply if first else null
|
||||
var history := main.history.size()
|
||||
main.start_roll("start")
|
||||
_check(first_reply != null and first_reply.finished, "a new roll answers the old question with Cancel")
|
||||
await process_frame
|
||||
var second := main.pending_choice()
|
||||
_check(second != null and second != first, "the new roll opens its own pop-up")
|
||||
_check(not is_instance_valid(first) or first.is_queued_for_deletion(), "the old pop-up goes away")
|
||||
_check(not main.current.has("halted"), "the old roll doesn't overwrite the new one")
|
||||
_eq(main.history.size(), history, "the replaced (unanswered) roll isn't added to Earlier")
|
||||
if second == null:
|
||||
return
|
||||
second._text.text = "Cy"
|
||||
second._confirm()
|
||||
await process_frame
|
||||
var n := main.pending_choice()
|
||||
if n:
|
||||
n.answer(1)
|
||||
await process_frame
|
||||
var p := main.pending_choice()
|
||||
if p:
|
||||
p.answer(2)
|
||||
await process_frame
|
||||
_check(main.current.get("done", false) and main.current.get("halted", "") == "", "the new roll finishes normally")
|
||||
_eq(_var("name"), "Cy", "with its own answers")
|
||||
|
||||
|
||||
func _test_keys() -> void:
|
||||
main.start_roll("start")
|
||||
await process_frame
|
||||
var d := main.pending_choice()
|
||||
if d:
|
||||
d._text.text = "Dee"
|
||||
d._confirm()
|
||||
await process_frame
|
||||
d = main.pending_choice()
|
||||
if d:
|
||||
# Typing in the number field, then Enter.
|
||||
var le := d._spin.get_line_edit()
|
||||
le.text = "4"
|
||||
le.text_changed.emit(le.text) # what typing does
|
||||
le.text_submitted.emit(le.text)
|
||||
await process_frame
|
||||
_eq(_var("rooms"), 4, "a typed number is used")
|
||||
d = main.pending_choice()
|
||||
_check(d != null and d.kind == "pick", "pick pop-up for the key test")
|
||||
if d == null:
|
||||
return
|
||||
var ev := InputEventKey.new()
|
||||
ev.keycode = KEY_3
|
||||
ev.pressed = true
|
||||
d._input(ev)
|
||||
await process_frame
|
||||
_check(main.pending_choice() == null and main.current.get("done", false), "pressing 3 answers")
|
||||
var paid := false
|
||||
for s: Dictionary in main.current["all"]:
|
||||
if s.get("table_id") == "way_out" and Formatter.strip_tags(str(s["text"])) == "Pay the toll":
|
||||
paid = true
|
||||
_check(paid, "key 3 picks the third option")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- live cards
|
||||
|
||||
func _test_live_edits() -> void:
|
||||
main.set_variable("gold", "42")
|
||||
_eq(_var("gold"), 42, "a number variable stays a number")
|
||||
_eq(main.card_for("v_gold")._var_value.text, "42", "the variable card follows an edit")
|
||||
_check(Formatter.strip_tags(main.card_for("report")._sheet_label.text).contains("Gold 42"), "the sheet follows an edit")
|
||||
main.reset_variable("gold")
|
||||
_eq(_var("gold"), 0, "reset goes back to the starting value")
|
||||
main.set_variable("hp", "3")
|
||||
main.persistent_vars["stray"] = {"value": "x", "source": ""}
|
||||
main.reset_all_variables()
|
||||
_check(_var("hp") == 10 and not main.persistent_vars.has("stray"), "Reset all: declared to start, undeclared cleared")
|
||||
_eq(main.card_for("v_hp")._var_value.text, "10", "cards show the reset values")
|
||||
main.tray.set_side(ResultTray.Side.VARIABLES)
|
||||
main.tray.render()
|
||||
var rows := 0
|
||||
for c in main.tray._vars._list.get_children():
|
||||
if c is HBoxContainer:
|
||||
rows += 1
|
||||
_check(rows >= 4, "the Variables tab lists every board variable, numbers included (%d rows)" % rows)
|
||||
var dlg := main.tray._vars.confirm_reset_all()
|
||||
_check(dlg != null and dlg.is_inside_tree(), "Reset all asks first, in the app")
|
||||
dlg.close()
|
||||
main.tray.set_side(ResultTray.Side.EARLIER)
|
||||
# Rendering live cards doesn't happen per frame: the sheet's text stays put.
|
||||
var before := main.card_for("report")._sheet_label.text
|
||||
for i in 3:
|
||||
await process_frame
|
||||
_eq(main.card_for("report")._sheet_label.text, before, "live cards only re-render on change")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- build rules
|
||||
|
||||
func _test_settings_rules() -> void:
|
||||
var c := RollTable.create(RollTable.KIND_CHOICE, "c", "C", "pick")
|
||||
c.entries[0].effects = "@a = 1"
|
||||
c.entries[0].add_pipe("x")
|
||||
var r := TableSettingsDialog.apply_settings(c, {"name": "C", "choice": "number", "min": "1", "max": "@top", "prompt": "How many?", "save_as": "@n"})
|
||||
_check(r["ok"] and c.choice == "number" and c.entries.size() == 1 and c.entries[0].text == "Answer", "pick → number keeps one Answer row")
|
||||
_check(Array(c.entries[0].pipes) == ["x"] and c.entries[0].effects == "@a = 1", "…with the first option's pipes and effects")
|
||||
_check(c.max_expr == "@top" and c.save_as == "@n", "min/max and save as applied")
|
||||
var bad := TableSettingsDialog.apply_settings(c, {"name": "C", "choice": "number", "min": "1 +", "max": "5"})
|
||||
_check(not bad["ok"] and c.min_expr == "1", "a bad min is refused and nothing changes")
|
||||
var back := TableSettingsDialog.apply_settings(c, {"name": "C", "choice": "pick"})
|
||||
_check(back["ok"] and c.entries.size() == 3 and c.entries[0].text == "Option 1", "number → pick gives three options")
|
||||
var l := RollTable.create(RollTable.KIND_LOOP, "l", "L", "times")
|
||||
_check(not TableSettingsDialog.apply_settings(l, {"loop_mode": "while", "loop_expr": "@hp >"})["ok"], "a bad loop rule is refused")
|
||||
_check(TableSettingsDialog.apply_settings(l, {"loop_mode": "while", "loop_expr": "@hp > 0"})["ok"] and l.loop_mode == "while", "a loop rule is applied")
|
||||
var v := RollTable.create(RollTable.KIND_VARIABLE, "v", "V")
|
||||
_check(not TableSettingsDialog.apply_settings(v, {"var_name": "Bad Name"})["ok"], "variable names are checked")
|
||||
_check(TableSettingsDialog.apply_settings(v, {"var_name": "@str", "var_type": "number", "initial": "2d6"})["ok"] and v.var_name == "str",
|
||||
"variable name, type and starting value applied")
|
||||
var t := RollTable.create(RollTable.KIND_ROLL, "t", "T")
|
||||
_check(TableSettingsDialog.apply_settings(t, {"ranged": true, "dice": "2d6 + dm(@end)"})["ok"], "expression dice are accepted")
|
||||
var s := RollTable.create(RollTable.KIND_SHEET, "s", "S")
|
||||
TableSettingsDialog.apply_settings(s, {"template": "HP {@hp}"})
|
||||
_eq(s.entries[0].text, "HP {@hp}", "sheet template applied")
|
||||
_eq(PipePopover._count_error("@terms"), "", "pipe counts take expressions")
|
||||
_check(PipePopover._count_error("@terms +") != "", "bad pipe counts are flagged")
|
||||
var e := TableEntry.new("e", "x")
|
||||
e.set_pipe_count("y", "@terms")
|
||||
_eq(PipeLayer._pipe_tag(e, "y"), "×@terms", "expression counts show on the pipe")
|
||||
# Previews.
|
||||
var pv := RichText.preview("{@skill_*} and {= dm(@str)} and {= 1 +}", main.data)
|
||||
_check(pv.contains("{@skill_*}") and pv.contains("{= dm(@str)}"), "previews show {@x_*} and {= expr} readably")
|
||||
_check(pv.contains("error:expr"), "a broken {= expr} is marked")
|
||||
_check(RichText.decorate(TextExpander.error_marker("oops")).contains(Style.DANGER_INK.to_html(false)), "error markers are red")
|
||||
|
||||
|
||||
func _test_add_kinds() -> void:
|
||||
main.set_mode(Main.Mode.BUILD)
|
||||
var n := main.data.tables.size()
|
||||
for k: Array in Main.ADD_KINDS:
|
||||
var t := main.add_table(str(k[1]), str(k[2]))
|
||||
_check(t.kind == k[1] and main.card_for(t.id) != null, "+ Table adds a %s" % str(k[0]))
|
||||
_eq(main.data.tables.size(), n + Main.ADD_KINDS.size(), "one card per menu item")
|
||||
var v1 := main.add_table(RollTable.KIND_VARIABLE, "number")
|
||||
var v2 := main.add_table(RollTable.KIND_VARIABLE, "number")
|
||||
_check(v1.var_name != v2.var_name, "new variable cards get distinct names")
|
||||
main.set_mode(Main.Mode.PLAY)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- long chains
|
||||
|
||||
func _long_chain(n: int) -> void:
|
||||
for id in ["long_start", "long_link"]:
|
||||
if main.data.get_table(id):
|
||||
main.data.remove_table(id)
|
||||
var head := RollTable.create(RollTable.KIND_ROLL, "long_start", "Long chain")
|
||||
head.entries.resize(1)
|
||||
head.entries[0].text = "Go"
|
||||
head.entries[0].effects = "@k = 0"
|
||||
head.entries[0].add_pipe("long_link")
|
||||
var link := RollTable.create(RollTable.KIND_ROLL, "long_link", "Link")
|
||||
link.entries.resize(1)
|
||||
link.entries[0].text = "Link {@k}"
|
||||
link.entries[0].effects = "@k += 1"
|
||||
link.entries[0].add_pipe("long_link", "@k < %d" % n)
|
||||
head.position = Vector2(40, 1200)
|
||||
link.position = Vector2(360, 1200)
|
||||
main.data.tables.append(head)
|
||||
main.data.tables.append(link)
|
||||
main._rebuild_cards()
|
||||
|
||||
|
||||
func _chips() -> int:
|
||||
var k := 0
|
||||
for c in main.tray._flow.get_children():
|
||||
if c is PanelContainer:
|
||||
k += 1
|
||||
return k
|
||||
|
||||
|
||||
func _test_long_chain() -> void:
|
||||
_long_chain(3000)
|
||||
await process_frame
|
||||
var t0 := Time.get_ticks_msec()
|
||||
main.start_roll("long_start")
|
||||
var ms := Time.get_ticks_msec() - t0
|
||||
var all: Array = main.current["all"]
|
||||
_eq(all.size(), 3001, "a 3,001-step chain")
|
||||
_check(main.current.get("done", false), "a long chain shows at once, without animating")
|
||||
_check(main.is_entry_lit("long_link", "e1"), "its path is lit")
|
||||
_eq(_chips(), ResultTray.TAIL, "the tray shows only the last %d steps" % ResultTray.TAIL)
|
||||
var toggle: Button = null
|
||||
for c in main.tray._flow.get_children():
|
||||
if c is HBoxContainer and c.get_child(0) is Button:
|
||||
toggle = c.get_child(0)
|
||||
_check(toggle != null and toggle.text == "+2,989 earlier steps", "a +N earlier steps toggle: %s" % (toggle.text if toggle else "none"))
|
||||
if toggle:
|
||||
toggle.pressed.emit()
|
||||
_eq(_chips(), ResultTray.MAX_EXPANDED, "expanding shows more steps (capped)")
|
||||
_check(ms < 4000, "lighting 3,000 steps is quick (%d ms)" % ms)
|
||||
print(" (3,001-step roll, lit and shown in %d ms)" % ms)
|
||||
_check(main.result_text(all, ResultTray.COPY_TEXT).length() < 3001 * 40, "copy text indents are capped")
|
||||
var line := ResultTray.earlier_line({"root_name": "x", "steps": all})
|
||||
_check(line.length() < 2000, "Earlier rows show the last few steps of a long chain")
|
||||
await process_frame
|
||||
|
||||
|
||||
func _test_action_limit() -> void:
|
||||
_long_chain(20000)
|
||||
await process_frame
|
||||
main.start_roll("long_start")
|
||||
_check(str(main.current.get("halted", "")).begins_with("Stopped after 10,000"), "the action limit is reported: %s" % str(main.current.get("halted", "")))
|
||||
_check(main.tray._halt.visible and main.tray._halt_label.text.contains("10,000"), "the tray shows the limit clearly")
|
||||
await process_frame
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- checks
|
||||
|
||||
func _eq(got: Variant, want: Variant, what: String) -> void:
|
||||
if typeof(got) != typeof(want) or got != want:
|
||||
_failures += 1
|
||||
print(" ✗ %s (got %s, want %s)" % [what, str(got), str(want)])
|
||||
|
||||
|
||||
func _check(ok: bool, what: String) -> void:
|
||||
if not ok:
|
||||
_failures += 1
|
||||
print(" ✗ ", what)
|
||||
|
|
@ -1 +0,0 @@
|
|||
uid://bvol3ms6pww03
|
||||
|
|
@ -68,7 +68,7 @@ func _init() -> void:
|
|||
stops += 1
|
||||
_check(stops > 50 and stops < 150, "rolls into a gap stop with a message (%d/200)" % stops)
|
||||
|
||||
# A self-pipe stops at the action limit (docs/LOGIC.md §7) instead of looping forever.
|
||||
# A self-pipe stops at the depth limit instead of looping forever.
|
||||
var loop := RollTable.new("loop", "Loop")
|
||||
var again := TableEntry.new("e1", "Again")
|
||||
again.pipes.append("loop")
|
||||
|
|
@ -76,7 +76,7 @@ func _init() -> void:
|
|||
var b3 := TowerBoard.new()
|
||||
b3.tables.append(loop)
|
||||
var steps := Roller.flatten(Roller.roll(b3, "loop", rng), [])
|
||||
_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())
|
||||
_check(steps.size() == Roller.MAX_DEPTH + 2, "self-pipe stops after the depth limit (%d steps)" % steps.size())
|
||||
|
||||
# JSON round trip keeps everything.
|
||||
var copy := TowerBoard.new()
|
||||
|
|
|
|||
|
|
@ -1,100 +0,0 @@
|
|||
extends SceneTree
|
||||
## Keeps tools/simulate_board.gd working: runs it on a small inline board with
|
||||
## a choice, a loop, a check, a bad effect, an unreachable table and a sheet.
|
||||
## Run: godot --headless --path . -s res://tests/test_simulate.gd
|
||||
|
||||
const Sim := preload("res://tools/simulate_board.gd")
|
||||
|
||||
var _failures := 0
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
var b := _board()
|
||||
var r: Dictionary = await Sim.simulate(b, "start", {"runs": 60, "seed": 3, "track": ["gold", "@name"]})
|
||||
_eq(r["runs"], 60, "60 runs")
|
||||
_eq(r["completed"], 60, "every run completes")
|
||||
_check((r["halted"] as Dictionary).is_empty(), "nothing halted: %s" % str(r["halted"]))
|
||||
var a: Dictionary = r["actions"]
|
||||
_check(a["max"] >= a["p95"] and a["p95"] >= 4 and a["mean"] > 4.0, "action stats are sensible: %s" % str(a))
|
||||
var errs: Array = r["errors"]
|
||||
_check(errs.size() == 1 and str(errs[0]["table"]).contains("pick") and str(errs[0]["entry"]) == "Broken", "the bad effect is reported with its table and entry: %s" % str(errs))
|
||||
_eq(r["unreached"], ["island"], "the island table is never reached")
|
||||
var uc: Dictionary = r["unchosen"]
|
||||
_check(not uc.has("check"), "an entry that can't come up (13 on 2d6) is not reported as unchosen: %s" % str(uc))
|
||||
_check(not uc.has("pick"), "every pick option was chosen at some point")
|
||||
var sheet := str(r["sample_sheet"])
|
||||
_check(sheet.begins_with("Hero: ") and sheet.contains("Gold "), "a sample sheet is kept: %s" % sheet)
|
||||
_check(not Sim.is_clean(r), "a run with an effect error is not clean")
|
||||
# Each run starts with empty variables: gold never grows past one run's worth.
|
||||
var gold := int((r["sample_vars"].get("gold", {}) as Dictionary).get("value", -1))
|
||||
_check(gold <= 18, "variables start clean for every run (gold %d)" % gold)
|
||||
var mk: Array = r["unset_markers"]
|
||||
_check(mk.size() == 1 and mk[0]["entry"] == "(prompt)" and str(mk[0]["text"]).contains("@nothing"), "an unset variable in a prompt is reported: %s" % str(mk))
|
||||
var tg: Dictionary = r["track"]["gold"]
|
||||
_check(int(tg["n"]) > 0 and float(tg["max"]) <= 18.0 and float(tg["min"]) >= 0.0, "--track summarises a number variable: %s" % str(tg))
|
||||
_eq(r["track"]["name"]["n"], 0, "--track skips text variables")
|
||||
var lg: Dictionary = r["longest"]
|
||||
_check(int(lg["actions"]) == int(a["max"]) and not (lg["top"] as Array).is_empty(), "the longest run's busiest tables are kept: %s" % str(lg))
|
||||
# A preference picks the matching option every time.
|
||||
var r2: Dictionary = await Sim.simulate(b, "start", {"runs": 20, "seed": 4, "prefer": "^Mine$"})
|
||||
_check((r2["unchosen"] as Dictionary).has("pick"), "--prefer always picks the matching option")
|
||||
_check(int((r2["table_hits"] as Dictionary).get("mine", 0)) == 20 * 3, "the preferred option's pipe ran on every pass")
|
||||
# The action limit is reported as a halt reason.
|
||||
var r3: Dictionary = await Sim.simulate(b, "start", {"runs": 5, "seed": 5, "max_actions": 4})
|
||||
_eq((r3["halted"] as Dictionary).get("Action limit", 0), 5, "the action limit is a halt reason")
|
||||
var text := Sim.format_report(r)
|
||||
_check(text.contains("Runs: 60") and text.contains("Tables never reached: 1") and text.contains("Sample final sheet") and text.contains("@gold: min"), "the report prints:\n%s" % text)
|
||||
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
|
||||
quit(1 if _failures else 0)
|
||||
|
||||
|
||||
func _board() -> TowerBoard:
|
||||
var b := TowerBoard.new()
|
||||
b.id = "sim-test"
|
||||
var start := RollTable.new("start", "Start")
|
||||
var e := TableEntry.new("e1", "Begin")
|
||||
e.effects = "reset @gold; @name = \"Hero\""
|
||||
e.add_pipe("loop")
|
||||
e.add_pipe("sheet")
|
||||
start.entries.append(e)
|
||||
var loop := RollTable.create(RollTable.KIND_LOOP, "loop", "Three times", "times")
|
||||
loop.loop_expr = "3"
|
||||
loop.entries[0].add_pipe("pick")
|
||||
var pick := RollTable.create(RollTable.KIND_CHOICE, "pick", "Pick", "pick")
|
||||
pick.prompt = "Which? {@nothing}"
|
||||
pick.entries[0].text = "Mine"
|
||||
pick.entries[0].effects = "@gold += 1d6"
|
||||
pick.entries[0].add_pipe("mine")
|
||||
pick.entries[1].text = "Check"
|
||||
pick.entries[1].add_pipe("check")
|
||||
pick.entries[2].text = "Broken"
|
||||
pick.entries[2].effects = "@gold += nope("
|
||||
var mine := RollTable.new("mine", "Mine")
|
||||
mine.entries.append(TableEntry.new("e1", "Dig"))
|
||||
var check := RollTable.new("check", "Check")
|
||||
check.dice = "2d6"
|
||||
for spec in [[2, 7, "Fail"], [8, 12, "Pass"], [13, 13, "Impossible"]]:
|
||||
var ce := TableEntry.new("c%d" % spec[0], spec[2])
|
||||
ce.has_range = true
|
||||
ce.range_lo = spec[0]
|
||||
ce.range_hi = spec[1]
|
||||
check.entries.append(ce)
|
||||
var island := RollTable.new("island", "Island")
|
||||
island.entries.append(TableEntry.new("e1", "Alone"))
|
||||
var sheet := RollTable.create(RollTable.KIND_SHEET, "sheet", "Sheet")
|
||||
sheet.entries[0].text = "{@name}: Gold {@gold}"
|
||||
var gold := RollTable.create(RollTable.KIND_VARIABLE, "v_gold", "Gold", "number")
|
||||
gold.var_name = "gold"
|
||||
for t in [start, loop, pick, mine, check, island, sheet, gold]:
|
||||
b.tables.append(t)
|
||||
return b
|
||||
|
||||
|
||||
func _eq(got: Variant, want: Variant, what: String) -> void:
|
||||
_check(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 +0,0 @@
|
|||
uid://neyn2x0o53cn
|
||||
|
|
@ -1,366 +0,0 @@
|
|||
extends SceneTree
|
||||
## Rolls a collection many times headlessly, answering every choice card at
|
||||
## random, and reports what happened: how many rolls finished, why the others
|
||||
## stopped, how many actions they took, every effect or expression error, the
|
||||
## tables and entries that were never reached, and a sample final sheet.
|
||||
##
|
||||
## Run:
|
||||
## godot --headless --path . -s res://tools/simulate_board.gd -- \
|
||||
## --board=<collection.json> --start=<table id> --runs=N [--seed=S] \
|
||||
## [--prefer=<regex>] [--track=a,b] [--max-actions=N] [--list=N] [--quiet]
|
||||
##
|
||||
## --prefer on a pick card, choose an option whose text matches this
|
||||
## regular expression (case-insensitive) whenever there is one,
|
||||
## e.g. --prefer="^Continue|another career"; otherwise random.
|
||||
## --list how many lines to print per section (default 40).
|
||||
## --quiet leave the sample sheet out of the report.
|
||||
## --track comma-separated board variables (no "@") whose final values
|
||||
## are summarised over all runs (min, mean, max), e.g.
|
||||
## --track=terms,age
|
||||
##
|
||||
## Every run starts with a fresh, empty set of board variables (its own
|
||||
## persistent-vars dictionary), so runs never leak state into each other.
|
||||
## The exit code is 1 when any run hit an error, the action limit, or a
|
||||
## dead end ("No result for ..."), else 0.
|
||||
##
|
||||
## Other scripts can call simulate() and format_report() directly (see
|
||||
## tests/test_simulate.gd).
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
var args := _parse_args(OS.get_cmdline_user_args())
|
||||
var path := str(args.get("board", ""))
|
||||
var start := str(args.get("start", ""))
|
||||
if path == "" or start == "":
|
||||
print("Usage: godot --headless --path . -s res://tools/simulate_board.gd -- --board=<json> --start=<table id> --runs=N [--seed=S] [--prefer=<regex>] [--track=a,b] [--max-actions=N] [--list=N] [--quiet]")
|
||||
quit(2)
|
||||
return
|
||||
var text := FileAccess.get_file_as_string(path)
|
||||
if text == "":
|
||||
print("Can't read %s" % path)
|
||||
quit(2)
|
||||
return
|
||||
var board := TowerBoard.new()
|
||||
if not board.load_json(text):
|
||||
print("%s is not a TableTower collection" % path)
|
||||
quit(2)
|
||||
return
|
||||
if board.get_table(start) == null:
|
||||
print("No table with id \"%s\" in %s" % [start, path])
|
||||
quit(2)
|
||||
return
|
||||
var opts := {
|
||||
"runs": int(args.get("runs", "100")),
|
||||
"seed": int(args.get("seed", "1")),
|
||||
"prefer": str(args.get("prefer", "")),
|
||||
"max_actions": int(args.get("max-actions", str(RollContext.DEFAULT_MAX_ACTIONS))),
|
||||
"track": str(args.get("track", "")).split(",", false),
|
||||
}
|
||||
var report: Dictionary = await simulate(board, start, opts)
|
||||
print(format_report(report, int(args.get("list", "40")), not args.has("quiet")))
|
||||
quit(0 if is_clean(report) else 1)
|
||||
|
||||
|
||||
static func _parse_args(list: PackedStringArray) -> Dictionary:
|
||||
var out := {}
|
||||
for a in list:
|
||||
if not a.begins_with("--"):
|
||||
continue
|
||||
var s := a.substr(2)
|
||||
var eq := s.find("=")
|
||||
if eq < 0:
|
||||
out[s] = "true"
|
||||
else:
|
||||
out[s.substr(0, eq)] = s.substr(eq + 1)
|
||||
return out
|
||||
|
||||
|
||||
## Runs `opts.runs` top-level rolls of `start` and gathers statistics.
|
||||
## opts: runs (int), seed (int), prefer (String regex, may be ""),
|
||||
## max_actions (int), track (Array of variable names). Returns the report
|
||||
## Dictionary that format_report() prints:
|
||||
## runs, completed, halted {reason: count}, actions {max, mean, p95},
|
||||
## longest {actions, run, top: [{table, count}]} (the most-rolled tables
|
||||
## of the run that took the most actions), track {name: {min, max, sum, n}},
|
||||
## prompts_mean, errors [{table, entry, text, count}], dead_ends
|
||||
## [{table, text, count}], unset_markers [{table, entry, text, count}]
|
||||
## (unset {@var?}, missing [[table]] and failed {= expr} markers),
|
||||
## unreached [table ids], unchosen {table id: [entry texts]},
|
||||
## table_hits {table id: count}, sample_sheet (String), sample_vars
|
||||
## (Dictionary), sample_halted (String)
|
||||
static func simulate(board: TowerBoard, start: String, opts: Dictionary = {}) -> Dictionary:
|
||||
var runs := maxi(1, int(opts.get("runs", 100)))
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = int(opts.get("seed", 1))
|
||||
var answer_rng := RandomNumberGenerator.new()
|
||||
answer_rng.seed = rng.seed * 7919 + 17
|
||||
var prefer: RegEx = null
|
||||
var pat := str(opts.get("prefer", ""))
|
||||
if pat != "":
|
||||
prefer = RegEx.create_from_string("(?i)" + pat)
|
||||
var max_actions := int(opts.get("max_actions", RollContext.DEFAULT_MAX_ACTIONS))
|
||||
|
||||
var completed := 0
|
||||
var halted := {}
|
||||
var actions: Array[int] = []
|
||||
var prompts_total := 0
|
||||
var errors := {} # key -> {table, entry, text, count}
|
||||
var dead_ends := {} # key -> {table, text, count}
|
||||
var markers := {} # key -> {table, entry, text, count}
|
||||
var table_hits := {} # table id -> count
|
||||
var entry_hits := {} # "table:entry" -> count
|
||||
var sample_sheet := ""
|
||||
var sample_vars := {}
|
||||
var sample_halted := ""
|
||||
var longest := {"actions": -1, "run": 0, "top": []}
|
||||
var track := {} # name -> {min, max, sum, n}
|
||||
for name: String in opts.get("track", []):
|
||||
track[name.strip_edges().trim_prefix("@")] = {"min": INF, "max": -INF, "sum": 0.0, "n": 0}
|
||||
|
||||
for run in runs:
|
||||
var vars := {}
|
||||
var ctx := Roller.new_context(board, rng, vars, {})
|
||||
ctx.max_actions = max_actions
|
||||
var counter := [0]
|
||||
ctx.prompt = func(req: Dictionary) -> Variant:
|
||||
counter[0] += 1
|
||||
var texts: Array = [str(req.get("prompt", ""))]
|
||||
for o: Dictionary in req.get("options", []):
|
||||
texts.append(str(o.get("text", "")))
|
||||
for txt: String in texts:
|
||||
for m in _marker_re().search_all(txt):
|
||||
var what := Formatter.strip_tags(m.get_string())
|
||||
var tid := str(req.get("table_id", ""))
|
||||
var mk := tid + ":prompt|" + what
|
||||
if not markers.has(mk):
|
||||
markers[mk] = {"table": "%s (%s)" % [Formatter.strip_tags(str(req.get("title", ""))), tid], "entry": "(prompt)", "text": what, "count": 0}
|
||||
markers[mk]["count"] += 1
|
||||
return answer(req, answer_rng, prefer)
|
||||
var root: Dictionary = await Roller.roll_async(board, start, ctx)
|
||||
prompts_total += counter[0]
|
||||
actions.append(ctx.actions)
|
||||
if ctx.halted == "":
|
||||
completed += 1
|
||||
else:
|
||||
var why := "Action limit" if ctx.halted.begins_with("Stopped after") else ctx.halted
|
||||
halted[why] = int(halted.get(why, 0)) + 1
|
||||
for name: String in track:
|
||||
var v: Variant = Expr.to_value((vars.get(name, {}) as Dictionary).get("value") if vars.get(name) is Dictionary else null)
|
||||
if v is int or v is float:
|
||||
var tr: Dictionary = track[name]
|
||||
tr["min"] = minf(tr["min"], v)
|
||||
tr["max"] = maxf(tr["max"], v)
|
||||
tr["sum"] += v
|
||||
tr["n"] += 1
|
||||
var run_hits := {}
|
||||
for st: Dictionary in Roller.flatten(root, []):
|
||||
var tid := str(st.get("table_id", ""))
|
||||
run_hits[tid] = int(run_hits.get(tid, 0)) + 1
|
||||
var eid := str(st.get("entry_id", ""))
|
||||
var tname := Formatter.strip_tags(str(st.get("table", "")))
|
||||
if st.get("stop", false):
|
||||
if not st.get("limit", false) and not st.get("cancelled", false):
|
||||
var dk := tid + "|" + str(st.get("text", ""))
|
||||
if not dead_ends.has(dk):
|
||||
dead_ends[dk] = {"table": "%s (%s)" % [tname, tid], "text": Formatter.strip_tags(str(st.get("text", ""))), "count": 0}
|
||||
dead_ends[dk]["count"] += 1
|
||||
continue
|
||||
table_hits[tid] = int(table_hits.get(tid, 0)) + 1
|
||||
if eid != "" and not st.has("pass") and not st.has("after"):
|
||||
entry_hits[tid + ":" + eid] = int(entry_hits.get(tid + ":" + eid, 0)) + 1
|
||||
elif st.has("pass"):
|
||||
entry_hits[tid + ":" + _loop_entry_id(board, tid, 0)] = 1
|
||||
elif st.has("after"):
|
||||
entry_hits[tid + ":" + _loop_entry_id(board, tid, 1)] = 1
|
||||
for l: Variant in st.get("effects", []):
|
||||
if l is Dictionary and (l as Dictionary).get("error", false):
|
||||
var text := str((l as Dictionary).get("text", ""))
|
||||
var ek := tid + ":" + eid + "|" + text
|
||||
if not errors.has(ek):
|
||||
errors[ek] = {"table": "%s (%s)" % [tname, tid], "entry": _entry_label(board, tid, eid), "text": text, "count": 0}
|
||||
errors[ek]["count"] += 1
|
||||
for m in _marker_re().search_all(str(st.get("text", ""))):
|
||||
var what := Formatter.strip_tags(m.get_string())
|
||||
var mk := tid + ":" + eid + "|" + what
|
||||
if not markers.has(mk):
|
||||
markers[mk] = {"table": "%s (%s)" % [tname, tid], "entry": _entry_label(board, tid, eid), "text": what, "count": 0}
|
||||
markers[mk]["count"] += 1
|
||||
if ctx.actions > int(longest["actions"]):
|
||||
var top: Array = []
|
||||
for k: String in run_hits:
|
||||
top.append({"table": k, "count": run_hits[k]})
|
||||
top = _sorted_by_count(top).slice(0, 8)
|
||||
longest = {"actions": ctx.actions, "run": run + 1, "top": top}
|
||||
if run == runs - 1 or (sample_sheet == "" and ctx.halted == ""):
|
||||
var sheet := Roller.last_sheet(root)
|
||||
if not sheet.is_empty():
|
||||
sample_sheet = Formatter.strip_tags(str(sheet.get("summary", "")))
|
||||
sample_vars = vars.duplicate(true)
|
||||
sample_halted = ctx.halted
|
||||
|
||||
var unreached: Array[String] = []
|
||||
var unchosen := {}
|
||||
for t in board.tables:
|
||||
if t.kind == RollTable.KIND_VARIABLE:
|
||||
continue
|
||||
if not table_hits.has(t.id):
|
||||
unreached.append(t.id)
|
||||
continue
|
||||
var missing: Array[String] = []
|
||||
for e in t.entries:
|
||||
if t.kind == RollTable.KIND_ROLL and not t.can_come_up(e):
|
||||
continue
|
||||
if not entry_hits.has(t.id + ":" + e.id):
|
||||
missing.append(Formatter.strip_tags(e.text).substr(0, 60))
|
||||
if not missing.is_empty():
|
||||
unchosen[t.id] = missing
|
||||
|
||||
var sorted_actions := actions.duplicate()
|
||||
sorted_actions.sort()
|
||||
var total := 0
|
||||
for a in actions:
|
||||
total += a
|
||||
var p95: int = sorted_actions[clampi(ceili(0.95 * sorted_actions.size()) - 1, 0, sorted_actions.size() - 1)]
|
||||
return {
|
||||
"runs": runs,
|
||||
"completed": completed,
|
||||
"halted": halted,
|
||||
"actions": {"max": sorted_actions.back(), "mean": float(total) / runs, "p95": p95},
|
||||
"longest": longest,
|
||||
"track": track,
|
||||
"prompts_mean": float(prompts_total) / runs,
|
||||
"errors": _sorted_by_count(errors.values()),
|
||||
"dead_ends": _sorted_by_count(dead_ends.values()),
|
||||
"unset_markers": _sorted_by_count(markers.values()),
|
||||
"unreached": unreached,
|
||||
"unchosen": unchosen,
|
||||
"table_hits": table_hits,
|
||||
"sample_sheet": sample_sheet,
|
||||
"sample_vars": sample_vars,
|
||||
"sample_halted": sample_halted,
|
||||
}
|
||||
|
||||
|
||||
## The simulated player's reply to a prompt request (docs/LOGIC.md §8): a
|
||||
## random option or Random for a pick (or an option matching `prefer`), a
|
||||
## random number in range, a short random word for text.
|
||||
static func answer(req: Dictionary, rng: RandomNumberGenerator, prefer: RegEx = null) -> Variant:
|
||||
match str(req.get("kind", "pick")):
|
||||
"number":
|
||||
return rng.randi_range(int(req.get("min", 0)), int(req.get("max", 0)))
|
||||
"text":
|
||||
var letters := "abcdefghijklmnopqrstuvwxyz"
|
||||
var s := ""
|
||||
for k in rng.randi_range(3, 8):
|
||||
s += letters[rng.randi_range(0, letters.length() - 1)]
|
||||
return s.capitalize()
|
||||
var options: Array = req.get("options", [])
|
||||
if prefer != null:
|
||||
for o: Dictionary in options:
|
||||
if prefer.search(Formatter.strip_tags(str(o.get("text", "")))) != null:
|
||||
return int(o["index"])
|
||||
if options.is_empty():
|
||||
return -1
|
||||
# Random (-1) is offered beside every option.
|
||||
var k := rng.randi_range(-1, options.size() - 1)
|
||||
return -1 if k < 0 else int(options[k]["index"])
|
||||
|
||||
|
||||
## True when no run hit an error, a dead end or the action limit.
|
||||
static func is_clean(report: Dictionary) -> bool:
|
||||
return (report["errors"] as Array).is_empty() and (report["dead_ends"] as Array).is_empty() \
|
||||
and not (report["halted"] as Dictionary).has("Action limit")
|
||||
|
||||
|
||||
static func format_report(r: Dictionary, list: int = 40, show_sheet: bool = true) -> String:
|
||||
var out := PackedStringArray()
|
||||
var a: Dictionary = r["actions"]
|
||||
out.append("Runs: %d completed: %d prompts per run: %.1f" % [r["runs"], r["completed"], r["prompts_mean"]])
|
||||
var hl := PackedStringArray()
|
||||
for k: String in r["halted"]:
|
||||
hl.append("%s %d" % [k, r["halted"][k]])
|
||||
out.append("Halted: %s" % (", ".join(hl) if not hl.is_empty() else "none"))
|
||||
out.append("Actions: max %d, mean %.1f, p95 %d" % [a["max"], a["mean"], a["p95"]])
|
||||
var lg: Dictionary = r.get("longest", {})
|
||||
if not (lg.get("top", []) as Array).is_empty():
|
||||
var parts := PackedStringArray()
|
||||
for x: Dictionary in lg["top"]:
|
||||
parts.append("%s %d" % [x["table"], x["count"]])
|
||||
out.append("Longest run (#%d) most-rolled tables: %s" % [lg["run"], ", ".join(parts)])
|
||||
var tr: Dictionary = r.get("track", {})
|
||||
for name: String in tr:
|
||||
var t: Dictionary = tr[name]
|
||||
if int(t["n"]) == 0:
|
||||
out.append("@%s: never a number" % name)
|
||||
else:
|
||||
out.append("@%s: min %s, mean %.1f, max %s (%d runs)" % [name, Expr.format_value(t["min"]), t["sum"] / t["n"], Expr.format_value(t["max"]), t["n"]])
|
||||
_section(out, "Effect / expression errors", r["errors"], list, func(e: Dictionary) -> String:
|
||||
return "%dx %s, entry \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]])
|
||||
_section(out, "Dead ends (rolls that stopped)", r["dead_ends"], list, func(e: Dictionary) -> String:
|
||||
return "%dx %s: %s" % [e["count"], e["table"], e["text"]])
|
||||
_section(out, "Unset variables, missing tables and {= } errors in text", r["unset_markers"], list, func(e: Dictionary) -> String:
|
||||
return "%dx %s, entry \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]])
|
||||
var un: Array = r["unreached"]
|
||||
out.append("Tables never reached: %d" % un.size())
|
||||
for k in mini(list, un.size()):
|
||||
out.append(" " + str(un[k]))
|
||||
if un.size() > list:
|
||||
out.append(" ... and %d more" % (un.size() - list))
|
||||
var uc: Dictionary = r["unchosen"]
|
||||
var n_entries := 0
|
||||
for k: String in uc:
|
||||
n_entries += (uc[k] as Array).size()
|
||||
out.append("Entries never chosen: %d in %d reached tables" % [n_entries, uc.size()])
|
||||
var shown := 0
|
||||
for k: String in uc:
|
||||
if shown >= list:
|
||||
out.append(" ... and %d more tables" % (uc.size() - shown))
|
||||
break
|
||||
var items: Array = uc[k]
|
||||
var names := PackedStringArray()
|
||||
for x in mini(4, items.size()):
|
||||
names.append("\"%s\"" % items[x])
|
||||
out.append(" %s: %d (%s%s)" % [k, items.size(), ", ".join(names), ", ..." if items.size() > 4 else ""])
|
||||
shown += 1
|
||||
if show_sheet:
|
||||
out.append("Sample final sheet%s:" % (" (" + str(r["sample_halted"]) + ")" if str(r["sample_halted"]) != "" else ""))
|
||||
out.append(str(r["sample_sheet"]) if str(r["sample_sheet"]) != "" else " (no sheet card was reached)")
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
static func _section(out: PackedStringArray, title: String, items: Array, list: int, fmt: Callable) -> void:
|
||||
out.append("%s: %d" % [title, items.size()])
|
||||
for k in mini(list, items.size()):
|
||||
out.append(" " + str(fmt.call(items[k])))
|
||||
if items.size() > list:
|
||||
out.append(" ... and %d more" % (items.size() - list))
|
||||
|
||||
|
||||
static func _sorted_by_count(list: Array) -> Array:
|
||||
var out := list.duplicate()
|
||||
out.sort_custom(func(x: Dictionary, y: Dictionary) -> bool: return int(x["count"]) > int(y["count"]))
|
||||
return out
|
||||
|
||||
|
||||
static func _entry_label(board: TowerBoard, tid: String, eid: String) -> String:
|
||||
var t := board.get_table(tid)
|
||||
if t == null:
|
||||
return eid
|
||||
var e := t.find_entry(eid)
|
||||
return eid if e == null else Formatter.strip_tags(e.text).substr(0, 50)
|
||||
|
||||
|
||||
static func _loop_entry_id(board: TowerBoard, tid: String, index: int) -> String:
|
||||
var t := board.get_table(tid)
|
||||
if t == null or t.entries.size() <= index:
|
||||
return ""
|
||||
return t.entries[index].id
|
||||
|
||||
|
||||
static var _marker: RegEx = null
|
||||
|
||||
|
||||
static func _marker_re() -> RegEx:
|
||||
if _marker == null:
|
||||
_marker = RegEx.create_from_string("\\[url=(?:unset|missing|error):[^\\]]*\\][^\\[]*\\[/url\\]")
|
||||
return _marker
|
||||
|
|
@ -1 +0,0 @@
|
|||
uid://b4r31htjbaynj
|
||||
|
|
@ -1,243 +0,0 @@
|
|||
class_name ChoiceDialog
|
||||
extends ModalCard
|
||||
## The pop-up a choice card opens mid-roll (docs/LOGIC.md §2, §8): the card's
|
||||
## question and either its options (pick), a number field (number) or a text
|
||||
## field (text), with Cancel.
|
||||
##
|
||||
## Keys: 1–9 pick an option, R picks Random, Enter confirms, Esc cancels.
|
||||
##
|
||||
## The answer arrives through `reply.done`, a signal on a separate object so
|
||||
## the waiting roll never hangs: closing or freeing the dialog in any way
|
||||
## (Esc, the window closing, a new roll replacing this one) answers null,
|
||||
## which is Cancel.
|
||||
|
||||
## Holds the answer signal. It outlives the dialog, so an awaiting roll
|
||||
## resumes even when the dialog is freed.
|
||||
class Reply extends RefCounted:
|
||||
signal done(value: Variant)
|
||||
var finished := false
|
||||
|
||||
func finish(value: Variant) -> void:
|
||||
if finished:
|
||||
return
|
||||
finished = true
|
||||
done.emit(value)
|
||||
|
||||
|
||||
var request: Dictionary
|
||||
var reply := Reply.new()
|
||||
var kind := "pick"
|
||||
|
||||
var _spin: SpinBox
|
||||
var _text: LineEdit
|
||||
var _options: Array[Control] = []
|
||||
var _range_note: Label
|
||||
var _typed := false
|
||||
|
||||
|
||||
func _init(p_request: Dictionary = {}) -> void:
|
||||
request = p_request
|
||||
kind = str(request.get("kind", "pick"))
|
||||
var title := Formatter.strip_tags(str(request.get("title", ""))).strip_edges()
|
||||
super._init(title if title != "" else "A question", 500.0)
|
||||
# A stray click on the board behind shouldn't throw the answer away.
|
||||
close_on_backdrop = false
|
||||
# A lighter dim, so the steps that led here stay readable behind the card.
|
||||
var dim := get_child(0) as ColorRect
|
||||
if dim:
|
||||
dim.color = Color(0, 0, 0, 0.32)
|
||||
_build()
|
||||
|
||||
|
||||
func _build() -> void:
|
||||
var prompt := str(request.get("prompt", "")).strip_edges()
|
||||
if prompt != "":
|
||||
var p := RichText.label(RichText.decorate(prompt), 18, Style.INK, false)
|
||||
p.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
body.add_child(p)
|
||||
match kind:
|
||||
"number":
|
||||
_build_number()
|
||||
"text":
|
||||
_build_text()
|
||||
_:
|
||||
_build_pick()
|
||||
|
||||
|
||||
func _build_pick() -> void:
|
||||
var list := VBoxContainer.new()
|
||||
list.add_theme_constant_override("separation", 6)
|
||||
body.add_child(list)
|
||||
var opts: Array = request.get("options", [])
|
||||
for k in opts.size():
|
||||
var o: Dictionary = opts[k]
|
||||
var row := _option_row(k, o)
|
||||
list.add_child(row)
|
||||
_options.append(row)
|
||||
var hint := note("Press 1–%d to choose, R for Random, Esc to cancel." % mini(9, maxi(1, opts.size())))
|
||||
hint.add_theme_font_size_override("font_size", 13)
|
||||
body.add_child(hint)
|
||||
add_button("Cancel", "plain", func() -> void: answer(null))
|
||||
var r := add_button("Random", "primary", func() -> void: answer(-1))
|
||||
r.tooltip_text = "Roll this card normally instead of choosing (R)"
|
||||
|
||||
|
||||
## One option: number key, text and details as a subtitle; the whole row is a
|
||||
## button.
|
||||
func _option_row(k: int, o: Dictionary) -> Control:
|
||||
var b := Button.new()
|
||||
b.focus_mode = Control.FOCUS_ALL
|
||||
b.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
var m := [14, 8, 14, 9]
|
||||
var n := Style.bordered(Style.box(Color.WHITE, 9, m), 1, Style.RULE)
|
||||
var h := Style.bordered(Style.box(Style.LIT, 9, m), 1, Style.BRASS_DARK)
|
||||
Style.skin_button(b, n, h, h, Style.INK)
|
||||
b.add_theme_stylebox_override("focus", Style.focus_ring(9))
|
||||
var row := HBoxContainer.new()
|
||||
row.add_theme_constant_override("separation", 12)
|
||||
row.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
row.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
|
||||
row.offset_left = 14
|
||||
row.offset_right = -14
|
||||
row.offset_top = 8
|
||||
row.offset_bottom = -9
|
||||
var key := Style.make_label(str(k + 1) if k < 9 else "", Style.display(), 20, Style.COPPER)
|
||||
key.custom_minimum_size = Vector2(16, 0)
|
||||
key.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
key.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
row.add_child(key)
|
||||
var col := VBoxContainer.new()
|
||||
col.add_theme_constant_override("separation", 1)
|
||||
col.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
col.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
row.add_child(col)
|
||||
var text := RichText.label(RichText.decorate(str(o.get("text", ""))), 17, Style.INK, false, true, true)
|
||||
text.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
col.add_child(text)
|
||||
var det := Formatter.strip_tags(str(o.get("details", ""))).strip_edges()
|
||||
if det != "":
|
||||
var sub := Style.make_label(det, Style.body(), 13, Style.MUTED)
|
||||
sub.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||
sub.max_lines_visible = 2
|
||||
sub.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
|
||||
sub.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
col.add_child(sub)
|
||||
b.tooltip_text = det
|
||||
b.add_child(row)
|
||||
# Buttons don't size to their children, so follow the row's height.
|
||||
var fit := func() -> void: b.custom_minimum_size.y = row.get_combined_minimum_size().y + 17.0
|
||||
row.minimum_size_changed.connect(fit)
|
||||
fit.call_deferred()
|
||||
var index := int(o.get("index", k))
|
||||
b.pressed.connect(func() -> void: answer(index))
|
||||
return b
|
||||
|
||||
|
||||
func _build_number() -> void:
|
||||
var lo := int(request.get("min", 0))
|
||||
var hi := maxi(lo, int(request.get("max", 99)))
|
||||
var def: Variant = request.get("default", lo)
|
||||
_spin = SpinBox.new()
|
||||
_spin.min_value = lo
|
||||
_spin.max_value = hi
|
||||
_spin.step = 1
|
||||
_spin.rounded = true
|
||||
_spin.value = clampi(int(def) if (def is int or def is float) else lo, lo, hi)
|
||||
_spin.custom_minimum_size = Vector2(150, 46)
|
||||
_spin.size_flags_horizontal = SIZE_SHRINK_BEGIN
|
||||
var le := _spin.get_line_edit()
|
||||
style_line_edit(le)
|
||||
le.add_theme_font_override("font", Style.body_bold())
|
||||
le.add_theme_font_size_override("font_size", 22)
|
||||
le.add_theme_color_override("font_selected_color", Style.INK)
|
||||
_spin.add_theme_color_override("up_icon_modulate", Style.MUTED)
|
||||
_spin.add_theme_color_override("down_icon_modulate", Style.MUTED)
|
||||
# Typed text is applied on confirm; the arrows (or code) set the value directly.
|
||||
le.text_changed.connect(func(_t: String) -> void: _typed = true)
|
||||
_spin.value_changed.connect(func(_v: float) -> void: _typed = false)
|
||||
le.text_submitted.connect(func(_t: String) -> void: _confirm())
|
||||
var row := HBoxContainer.new()
|
||||
row.add_theme_constant_override("separation", 12)
|
||||
row.add_child(_spin)
|
||||
_range_note = note("A whole number from %d to %d." % [lo, hi])
|
||||
_range_note.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
row.add_child(_range_note)
|
||||
body.add_child(row)
|
||||
add_button("Cancel", "plain", func() -> void: answer(null))
|
||||
add_button("OK", "primary", _confirm)
|
||||
|
||||
|
||||
func _build_text() -> void:
|
||||
_text = LineEdit.new()
|
||||
_text.placeholder_text = "Type your answer"
|
||||
_text.text = str(request.get("default", ""))
|
||||
style_line_edit(_text)
|
||||
_text.add_theme_font_size_override("font_size", 18)
|
||||
_text.text_submitted.connect(func(_t: String) -> void: _confirm())
|
||||
body.add_child(_text)
|
||||
add_button("Cancel", "plain", func() -> void: answer(null))
|
||||
add_button("OK", "primary", _confirm)
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
super._ready()
|
||||
if _spin:
|
||||
_spin.get_line_edit().grab_focus()
|
||||
_spin.get_line_edit().select_all()
|
||||
elif _text:
|
||||
_text.grab_focus()
|
||||
elif not _options.is_empty():
|
||||
_options[0].grab_focus()
|
||||
|
||||
|
||||
## Enter on the number or text field, or OK.
|
||||
func _confirm() -> void:
|
||||
if _spin:
|
||||
if _typed:
|
||||
_spin.apply()
|
||||
answer(int(_spin.value))
|
||||
elif _text:
|
||||
answer(_text.text)
|
||||
|
||||
|
||||
## Gives the answer (null = Cancel) and closes. Only the first answer counts.
|
||||
func answer(value: Variant) -> void:
|
||||
reply.finish(value)
|
||||
if is_inside_tree() and not is_queued_for_deletion():
|
||||
super.close()
|
||||
|
||||
|
||||
## Esc and every other way of closing answer Cancel.
|
||||
func close() -> void:
|
||||
answer(null)
|
||||
|
||||
|
||||
func _input(event: InputEvent) -> void:
|
||||
if not is_inside_tree():
|
||||
return
|
||||
var k := event as InputEventKey
|
||||
if k and k.pressed and not k.echo and kind == "pick":
|
||||
var code := k.keycode
|
||||
if code >= KEY_1 and code <= KEY_9:
|
||||
var i := code - KEY_1
|
||||
if i < _options.size():
|
||||
get_viewport().set_input_as_handled()
|
||||
_options[i].emit_signal("pressed")
|
||||
return
|
||||
if code >= KEY_KP_1 and code <= KEY_KP_9:
|
||||
var j := code - KEY_KP_1
|
||||
if j < _options.size():
|
||||
get_viewport().set_input_as_handled()
|
||||
_options[j].emit_signal("pressed")
|
||||
return
|
||||
if code == KEY_R:
|
||||
get_viewport().set_input_as_handled()
|
||||
answer(-1)
|
||||
return
|
||||
super._input(event)
|
||||
|
||||
|
||||
func _notification(what: int) -> void:
|
||||
# Freed or taken off the screen without an answer: the roll gets Cancel.
|
||||
if what == NOTIFICATION_EXIT_TREE or what == NOTIFICATION_PREDELETE:
|
||||
reply.finish(null)
|
||||
|
|
@ -1 +0,0 @@
|
|||
uid://bac7rv8cja4tc
|
||||
|
|
@ -186,27 +186,16 @@ func show_meta(owner: Control, meta: String) -> void:
|
|||
show_for(owner, "{%s} isn't set" % arg, "Nothing has saved this variable yet. Save it earlier in the roll with [lb][lb]Table -> %s]] or a pipe's [i]Save as[/i]." % RichText.plain(arg))
|
||||
"deep":
|
||||
show_for(owner, "Chain too deep", "The roll stopped after %d levels so a loop can't run forever." % Roller.MAX_DEPTH)
|
||||
"error":
|
||||
show_for(owner, "Can't work this out", "This expression has a mistake; the message after ⚠ says what. Expressions use @variables, dice such as 2d6, + - * / and functions such as max() and dm().")
|
||||
"expr":
|
||||
show_for(owner, "{= %s}" % RichText.plain(arg), "A computed value, worked out each time the text is shown.")
|
||||
|
||||
|
||||
func _show_var(owner: Control, name: String) -> void:
|
||||
var persistent := name.begins_with("@")
|
||||
var value: Variant = null
|
||||
var source := ""
|
||||
if persistent and name.ends_with("*"):
|
||||
var parts := PackedStringArray()
|
||||
for v: Dictionary in RollContext.vars_with_prefix(main.persistent_vars, name.substr(1)):
|
||||
parts.append("%s %s" % [v["label"], Expr.format_value(v["value"])])
|
||||
show_for(owner, "{%s}" % name, ", ".join(parts) if not parts.is_empty() else "[i]None set yet[/i]",
|
||||
"Every variable starting with %s" % name.trim_suffix("*"))
|
||||
return
|
||||
if persistent:
|
||||
var v: Variant = main.persistent_vars.get(name.substr(1))
|
||||
if v is Dictionary:
|
||||
value = Expr.format_value(v.get("value", ""))
|
||||
value = str(v.get("value", ""))
|
||||
source = str(v.get("source", ""))
|
||||
else:
|
||||
value = (main.current.get("chain_vars", {}) as Dictionary).get(name)
|
||||
|
|
@ -220,15 +209,6 @@ func _show_var(owner: Control, name: String) -> void:
|
|||
|
||||
## "d100 · 6 ranges · 4 / 6 cards left"
|
||||
func table_summary(t: RollTable) -> String:
|
||||
match t.kind:
|
||||
RollTable.KIND_CHOICE:
|
||||
return {"pick": "Choice · %d options" % t.entries.size(), "number": "Choice · a number", "text": "Choice · open ended"}.get(t.choice, "Choice")
|
||||
RollTable.KIND_LOOP:
|
||||
return "Loop · " + TableCard.loop_rule(t)
|
||||
RollTable.KIND_VARIABLE:
|
||||
return "Variable @%s · %s" % [t.var_name, t.var_type]
|
||||
RollTable.KIND_SHEET:
|
||||
return "Sheet"
|
||||
var parts := PackedStringArray([t.dice_label()])
|
||||
parts.append("%d %s" % [t.entries.size(), "ranges" if t.is_ranged() else "results"])
|
||||
if t.card_mode:
|
||||
|
|
|
|||
16
ui/icons.gd
16
ui/icons.gd
|
|
@ -18,19 +18,3 @@ static func draw_tower(ci: CanvasItem, origin: Vector2, scale: float, color: Col
|
|||
door.append(origin + (Vector2(11, 19) + Vector2(cos(a), sin(a)) * 4.0) * scale)
|
||||
door.append(origin + Vector2(15, 25) * scale)
|
||||
ci.draw_polyline(door, accent, 1.7 * scale, true)
|
||||
|
||||
|
||||
## A loop arrow: most of a circle with an arrowhead, centred on `center`.
|
||||
static func draw_loop(ci: CanvasItem, center: Vector2, radius: float, color: Color, width: float = 2.0) -> void:
|
||||
var start := -PI * 0.35
|
||||
var end := start + TAU * 0.8
|
||||
ci.draw_arc(center, radius, start, end, 24, color, width, true)
|
||||
var tip := center + Vector2(cos(end), sin(end)) * radius
|
||||
var tangent := Vector2(-sin(end), cos(end))
|
||||
var normal := Vector2(cos(end), sin(end))
|
||||
var s := radius * 0.62
|
||||
ci.draw_colored_polygon(PackedVector2Array([
|
||||
tip + tangent * s,
|
||||
tip - normal * s * 0.85 - tangent * s * 0.15,
|
||||
tip + normal * s * 0.85 - tangent * s * 0.15,
|
||||
]), color)
|
||||
|
|
|
|||
457
ui/main.gd
457
ui/main.gd
|
|
@ -8,7 +8,7 @@ enum Mode { PLAY, BUILD }
|
|||
const HISTORY_SIZE := 6
|
||||
const SAVE_DELAY := 0.6
|
||||
const HINTS := {
|
||||
Mode.PLAY: "Click a die to roll. Shift-click skips straight to the result.",
|
||||
Mode.PLAY: "Click a die to roll. Results flow down the pipes.",
|
||||
Mode.BUILD: "Type to edit. Drag from a ● to another table to lay a pipe. Click a pipe for its options.",
|
||||
}
|
||||
|
||||
|
|
@ -51,22 +51,6 @@ var lit_texts: Dictionary = {} # "tid:eid" -> expanded BBCode from the la
|
|||
var _details_popup: DetailsPopup
|
||||
var _pipe_popover: PipePopover
|
||||
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). It opens the choice pop-up (_ask_player); tests swap in
|
||||
## a script.
|
||||
var prompt_hook: Callable = Callable()
|
||||
var _choice: ChoiceDialog
|
||||
## 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
|
||||
## Copy-as-text indents by depth up to this many levels.
|
||||
const MAX_INDENT := 8
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
prompt_hook = _ask_player
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
|
|
@ -205,8 +189,9 @@ func _build_top_bar() -> Control:
|
|||
var tools := HBoxContainer.new()
|
||||
tools.add_theme_constant_override("separation", 6)
|
||||
_build_tools = tools
|
||||
_add_menu = _make_add_menu()
|
||||
tools.add_child(_add_menu)
|
||||
var add := Style.bar_button("+ Table", true)
|
||||
add.pressed.connect(add_table)
|
||||
tools.add_child(add)
|
||||
_board_menu = IoMenu.new()
|
||||
_board_menu.setup(true, collections_enabled())
|
||||
_board_menu.reset_requested.connect(reset_sample)
|
||||
|
|
@ -367,8 +352,6 @@ func mark_dirty() -> void:
|
|||
_ref_cache.clear()
|
||||
_update_collapse_all()
|
||||
_update_endless_chip()
|
||||
if mode == Mode.BUILD:
|
||||
refresh_live()
|
||||
|
||||
|
||||
func _any_expanded() -> bool:
|
||||
|
|
@ -402,83 +385,18 @@ func set_all_collapsed(collapsed: bool) -> void:
|
|||
mark_dirty()
|
||||
|
||||
|
||||
## The "+ Table ▾" kinds: [label, kind, sub, default name].
|
||||
const ADD_KINDS := [
|
||||
["Roll table", RollTable.KIND_ROLL, "", "New table"],
|
||||
["Choice: which option", RollTable.KIND_CHOICE, "pick", "New choice"],
|
||||
["Choice: how many", RollTable.KIND_CHOICE, "number", "How many?"],
|
||||
["Choice: open ended", RollTable.KIND_CHOICE, "text", "What is it?"],
|
||||
["Loop", RollTable.KIND_LOOP, "times", "Repeat"],
|
||||
["Variable", RollTable.KIND_VARIABLE, "number", "New variable"],
|
||||
["Sheet", RollTable.KIND_SHEET, "", "Sheet"],
|
||||
]
|
||||
|
||||
var _add_menu: MenuButton
|
||||
|
||||
|
||||
func _make_add_menu() -> MenuButton:
|
||||
var mb := MenuButton.new()
|
||||
mb.text = "+ Table ▾"
|
||||
mb.tooltip_text = "Add a roll table or a logic card"
|
||||
mb.flat = false
|
||||
var ref := Style.bar_button("", true)
|
||||
for n in ["normal", "hover", "pressed", "hover_pressed", "disabled", "focus"]:
|
||||
mb.add_theme_stylebox_override(n, ref.get_theme_stylebox(n))
|
||||
for c in ["font_color", "font_hover_color", "font_focus_color", "font_pressed_color", "font_hover_pressed_color"]:
|
||||
mb.add_theme_color_override(c, ref.get_theme_color(c))
|
||||
mb.add_theme_font_override("font", Style.body_bold())
|
||||
mb.add_theme_font_size_override("font_size", 15)
|
||||
mb.mouse_default_cursor_shape = CURSOR_POINTING_HAND
|
||||
ref.free()
|
||||
var pm := mb.get_popup()
|
||||
ModalCard.style_popup(pm)
|
||||
for i in ADD_KINDS.size():
|
||||
if i == 1:
|
||||
pm.add_separator("Logic cards")
|
||||
pm.add_item(str(ADD_KINDS[i][0]), i)
|
||||
pm.id_pressed.connect(func(id: int) -> void:
|
||||
var k: Array = ADD_KINDS[id]
|
||||
add_table(str(k[1]), str(k[2]))
|
||||
)
|
||||
return mb
|
||||
|
||||
|
||||
## Adds a card of any kind (RollTable.create) in the middle of the view.
|
||||
func add_table(kind: String = RollTable.KIND_ROLL, sub: String = "") -> RollTable:
|
||||
func add_table() -> void:
|
||||
var center := board.screen_to_world(board.size / 2.0)
|
||||
var name := "New table"
|
||||
for k: Array in ADD_KINDS:
|
||||
if k[1] == kind and (sub == "" or k[2] == sub or kind != RollTable.KIND_CHOICE):
|
||||
name = str(k[3])
|
||||
break
|
||||
var t := RollTable.create(kind, TowerBoard.new_id("t"), name, sub)
|
||||
if kind == RollTable.KIND_ROLL:
|
||||
for e in t.entries:
|
||||
e.id = TowerBoard.new_id("e")
|
||||
if kind == RollTable.KIND_VARIABLE:
|
||||
t.var_name = _free_var_name(t.var_name)
|
||||
var t := RollTable.new(TowerBoard.new_id("t"), "New table")
|
||||
t.position = Vector2(maxf(20.0, roundf(center.x - 128.0)), maxf(20.0, roundf(center.y - 120.0)))
|
||||
for n in range(1, 5):
|
||||
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Result %d" % n))
|
||||
data.tables.append(t)
|
||||
var card := TableCard.new()
|
||||
board.cards.add_child(card)
|
||||
card.setup(self, t)
|
||||
cards[t.id] = card
|
||||
mark_dirty()
|
||||
return t
|
||||
|
||||
|
||||
## `base`, or base_2, base_3… when another variable card already uses it.
|
||||
func _free_var_name(base: String) -> String:
|
||||
var used := {}
|
||||
for t in data.tables:
|
||||
if t.kind == RollTable.KIND_VARIABLE:
|
||||
used[t.var_name] = true
|
||||
var n := base
|
||||
var k := 2
|
||||
while used.has(n):
|
||||
n = "%s_%d" % [base, k]
|
||||
k += 1
|
||||
return n
|
||||
|
||||
|
||||
func reset_sample() -> void:
|
||||
|
|
@ -585,9 +503,6 @@ func finish_link() -> void:
|
|||
_link_from = {}
|
||||
if e == null or e.pipes.has(over.table.id):
|
||||
return
|
||||
if over.table.kind == RollTable.KIND_VARIABLE:
|
||||
toast("Variable cards aren't rolled, so pipes can't lead into them. Use an effect such as @%s += 1." % over.table.var_name)
|
||||
return
|
||||
# Each range on a ranged table takes a single pipe, so a new one replaces the old.
|
||||
var replaced: RollTable = null
|
||||
if t.is_ranged():
|
||||
|
|
@ -615,23 +530,13 @@ func _card_under_mouse() -> TableCard:
|
|||
|
||||
# ---------- Rolling ----------
|
||||
|
||||
## Rolls a table and plays the result down its pipes. A fast roll (Shift held
|
||||
## while clicking, or `fast`) skips the flicker and the beads and shows the
|
||||
## whole result at once. Choice cards still ask (docs/LOGIC.md §8): before a
|
||||
## question opens, the steps so far light up; after the last answer the rest
|
||||
## of the roll shows at once. Starting a roll while a question is open cancels
|
||||
## the old roll.
|
||||
func start_roll(tid: String, fast: bool = false) -> void:
|
||||
func start_roll(tid: String) -> void:
|
||||
var t := data.get_table(tid)
|
||||
if t == null or t.kind == RollTable.KIND_VARIABLE:
|
||||
if t == null:
|
||||
return
|
||||
fast = fast or Input.is_key_pressed(KEY_SHIFT)
|
||||
_archive_current()
|
||||
_token += 1
|
||||
var my := _token
|
||||
# A question left open by the previous roll answers Cancel; that roll then
|
||||
# sees it has been replaced and stops quietly.
|
||||
cancel_choice()
|
||||
if _pulse_tween and _pulse_tween.is_valid():
|
||||
_pulse_tween.kill()
|
||||
board.pipes.pulse_key = ""
|
||||
|
|
@ -639,139 +544,29 @@ func start_roll(tid: String, fast: bool = false) -> void:
|
|||
(c as TableCard).set_rolling(false)
|
||||
(c as TableCard).clear_flick()
|
||||
var ctx := Roller.new_context(data, rng, persistent_vars, decks)
|
||||
ctx.prompt = _prompt_for.bind(my)
|
||||
rolling_ctx = ctx
|
||||
current = {"collection": data.id, "root": tid, "root_name": t.name, "time": Time.get_unix_time_from_system(),
|
||||
"steps": [], "all": [], "done": false, "pending": true}
|
||||
var tree: Dictionary = await Roller.roll_async(data, tid, ctx)
|
||||
if rolling_ctx == ctx:
|
||||
rolling_ctx = null
|
||||
if my != _token or not is_inside_tree():
|
||||
# Another roll started while this one waited for an answer.
|
||||
_store_decks()
|
||||
if ctx.persistent_changed:
|
||||
_store_variables()
|
||||
return
|
||||
var prompted: bool = current.get("prompted", false)
|
||||
var tree := Roller.roll(data, tid, rng, 0, decks, ctx)
|
||||
lit_entries.clear()
|
||||
lit_pipes.clear()
|
||||
lit_texts.clear()
|
||||
current = {"collection": data.id, "root": tid, "root_name": t.name, "time": current.get("time", Time.get_unix_time_from_system()),
|
||||
"steps": [], "all": Roller.flatten(tree, []), "done": false, "chain_vars": ctx.chain_vars.duplicate()}
|
||||
if ctx.halted != "":
|
||||
current["halted"] = ctx.halted
|
||||
_store_roll(ctx)
|
||||
if fast or prompted or (current["all"] as Array).size() > LONG_CHAIN:
|
||||
_finish_fast_roll()
|
||||
return
|
||||
_refresh_lit()
|
||||
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()}
|
||||
_store_roll(ctx)
|
||||
tray.render()
|
||||
await _play_node(tree, my)
|
||||
if my == _token:
|
||||
current["steps"] = current["all"]
|
||||
current["done"] = true
|
||||
tray.render()
|
||||
refresh_live()
|
||||
|
||||
|
||||
## The roll's prompt hook: lights the steps so far, then asks through
|
||||
## prompt_hook (the pop-up, or a test's script). A reply for a roll that has
|
||||
## been replaced in the meantime is turned into Cancel.
|
||||
func _prompt_for(req: Dictionary, my: int) -> Variant:
|
||||
if my != _token:
|
||||
return null
|
||||
current["prompted"] = true
|
||||
current["asking"] = Formatter.strip_tags(str(req.get("title", "")))
|
||||
show_progress()
|
||||
var reply: Variant = await prompt_hook.call(req)
|
||||
if my != _token:
|
||||
return null
|
||||
current.erase("asking")
|
||||
return reply
|
||||
|
||||
|
||||
## Lights the steps of the running roll so far (Roller.progress) on the board
|
||||
## and in the tray, all at once. Used just before a question opens.
|
||||
func show_progress() -> void:
|
||||
if rolling_ctx == null:
|
||||
return
|
||||
var steps := Roller.progress(rolling_ctx)
|
||||
lit_entries.clear()
|
||||
lit_pipes.clear()
|
||||
lit_texts.clear()
|
||||
_light_steps(steps)
|
||||
_refresh_lit()
|
||||
_reveal_steps(steps)
|
||||
current["steps"] = steps
|
||||
current["all"] = steps
|
||||
current["fast"] = true
|
||||
refresh_live()
|
||||
tray.render()
|
||||
|
||||
|
||||
## The real prompt hook: opens the choice pop-up and waits for its answer
|
||||
## (an index or -1 for a pick, an int, a String, or null for Cancel).
|
||||
func _ask_player(req: Dictionary) -> Variant:
|
||||
cancel_choice()
|
||||
var d := ChoiceDialog.new(req)
|
||||
_choice = d
|
||||
var waiter := d.reply
|
||||
_add_modal(d)
|
||||
var v: Variant = await waiter.done
|
||||
if _choice == d:
|
||||
_choice = null
|
||||
return v
|
||||
|
||||
|
||||
## The open choice pop-up, or null.
|
||||
func pending_choice() -> ChoiceDialog:
|
||||
return _choice if is_instance_valid(_choice) else null
|
||||
|
||||
|
||||
## Closes an open choice pop-up as Cancel (its roll stops with "Cancelled").
|
||||
func cancel_choice() -> void:
|
||||
var d := pending_choice()
|
||||
_choice = null
|
||||
if d != null:
|
||||
d.answer(null)
|
||||
|
||||
|
||||
## Plays a result tree step by step. Iterative (an explicit stack), so long
|
||||
## chains don't recurse.
|
||||
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]
|
||||
func _play_node(n: Dictionary, my: int, depth: int = 0) -> void:
|
||||
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 stopped := n.has("stop")
|
||||
var card := card_for(t.id)
|
||||
var tumble: bool = not n.has("kind") or bool(n.get("random", false))
|
||||
if not stopped and card and tumble:
|
||||
if not stopped and card:
|
||||
card.set_rolling(true)
|
||||
for k in 8:
|
||||
card = card_for(t.id)
|
||||
|
|
@ -798,41 +593,11 @@ func _play_one(n: Dictionary, my: int, depth: int) -> void:
|
|||
card.reveal(e.id)
|
||||
(current["steps"] as Array).append(Roller.step_of(n, depth))
|
||||
tray.render()
|
||||
|
||||
|
||||
## Shows the whole current roll at once: every result and pipe on its path lit,
|
||||
## long lists scrolled to their result, and the full chain in the tray.
|
||||
func _finish_fast_roll() -> void:
|
||||
var all: Array = current["all"]
|
||||
_light_steps(all)
|
||||
_refresh_lit()
|
||||
_reveal_steps(all)
|
||||
current["steps"] = all
|
||||
current["done"] = true
|
||||
current["fast"] = true
|
||||
refresh_live()
|
||||
tray.render()
|
||||
|
||||
|
||||
## Scrolls long cards to the last result each table gave in `steps` (one
|
||||
## reveal per table, so thousands of steps cost one pass).
|
||||
func _reveal_steps(steps: Array) -> void:
|
||||
var last := {}
|
||||
for s: Dictionary in steps:
|
||||
if s.has("entry_id") and not s.get("stop", false):
|
||||
last[str(s.get("table_id", ""))] = str(s["entry_id"])
|
||||
for tid: String in last:
|
||||
var card := card_for(tid)
|
||||
if card:
|
||||
card.reveal(last[tid])
|
||||
|
||||
|
||||
## Re-renders the live cards (variables, sheets, questions). Called after a
|
||||
## roll, after variable edits and after edits in Build, never per frame, so
|
||||
## dice inside {= } don't re-roll all the time.
|
||||
func refresh_live() -> void:
|
||||
for card in cards.values():
|
||||
(card as TableCard).refresh_live()
|
||||
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)
|
||||
|
||||
|
||||
func _pulse(key: String, my: int) -> void:
|
||||
|
|
@ -850,8 +615,7 @@ func _pulse(key: String, my: int) -> void:
|
|||
|
||||
## Moves the current roll to the Earlier list (it's already in the saved history).
|
||||
func _archive_current() -> void:
|
||||
# A roll still waiting for an answer is cancelled, not kept.
|
||||
if current.is_empty() or current.get("archived", false) or current.get("pending", false):
|
||||
if current.is_empty() or current.get("archived", false):
|
||||
return
|
||||
current["archived"] = true
|
||||
var rec := current.duplicate()
|
||||
|
|
@ -871,7 +635,6 @@ func _seed_session() -> void:
|
|||
if not current.is_empty():
|
||||
_light_steps(current.get("all", []))
|
||||
_refresh_lit()
|
||||
refresh_live()
|
||||
tray.render()
|
||||
return
|
||||
var now := Time.get_unix_time_from_system()
|
||||
|
|
@ -892,42 +655,26 @@ func _seed_session() -> void:
|
|||
var n := Roller.roll(data, pair[1], rng, 0, scratch, ctx)
|
||||
if not n.is_empty() and not n.has("stop"):
|
||||
ctx.save(pair[0], Formatter.to_export_bbcode(str(n["summary"])), pair[1])
|
||||
var start := "wilderness" if data.get_table("wilderness") else _first_rollable()
|
||||
var start := "wilderness" if data.get_table("wilderness") else (data.tables[0].id if not data.tables.is_empty() else "")
|
||||
if start == "":
|
||||
refresh_live()
|
||||
tray.render()
|
||||
return
|
||||
var best: Dictionary
|
||||
if data.get_table("trinkets"):
|
||||
best = Roller.roll(data, start, rng, 0, scratch)
|
||||
var best := Roller.roll(data, start, rng, 0, scratch)
|
||||
for i in 400:
|
||||
if Roller.reaches(best, "trinkets"):
|
||||
break
|
||||
best = Roller.roll(data, start, rng, 0, scratch)
|
||||
else:
|
||||
# Any other board: one roll with the headless answers, through the real
|
||||
# variables, so variable and sheet cards have values to show.
|
||||
best = Roller.roll(data, start, rng, 0, scratch, Roller.new_context(data, rng, persistent_vars, scratch))
|
||||
var all := Roller.flatten(best, [])
|
||||
current = {"collection": data.id, "root": start, "root_name": data.get_table(start).name, "time": now - 60,
|
||||
"steps": all, "all": all, "done": true, "chain_vars": {}}
|
||||
Roller.collect_lit(best, lit_entries, lit_pipes, lit_texts)
|
||||
_refresh_lit()
|
||||
refresh_live()
|
||||
tray.render()
|
||||
|
||||
|
||||
## The first table that can start a roll (not a variable card), or "".
|
||||
func _first_rollable() -> String:
|
||||
for t in data.tables:
|
||||
if t.kind != RollTable.KIND_VARIABLE:
|
||||
return t.id
|
||||
return ""
|
||||
|
||||
|
||||
# ---------- Command line (used for screenshots and checks) ----------
|
||||
# godot --path . -- --screenshot=/tmp/shot.png [--build] [--expand-all] [--collapse-all]
|
||||
# [--roll=<table id>] [--fast] [--shot-delay=<seconds>]
|
||||
# [--roll=<table id>] [--shot-delay=<seconds>]
|
||||
# [--board=<collection.json>] (with --sample/--screenshot only: show that board instead)
|
||||
# [--tray=variables] [--hover=<x>,<y>] [--details=<table id>] [--pipe=<pipe key>] [--edit-details=<table id>]
|
||||
|
||||
|
|
@ -949,10 +696,9 @@ func _run_cli(args: PackedStringArray) -> void:
|
|||
if args.has("--collapse-all"):
|
||||
set_all_collapsed(true)
|
||||
_run_shell_cli(args)
|
||||
_run_logic_cli(args)
|
||||
var roll := _arg_value(args, "--roll")
|
||||
if roll != "":
|
||||
start_roll(roll, args.has("--fast"))
|
||||
start_roll(roll)
|
||||
_run_cli_extras(args)
|
||||
var shot := _arg_value(args, "--screenshot")
|
||||
if shot == "":
|
||||
|
|
@ -994,16 +740,10 @@ func open_table_settings(table_id: String) -> void:
|
|||
d.applied.connect(func(result: Dictionary) -> void:
|
||||
if result.get("deck_reset", false) and state and data.id != "":
|
||||
state.clear_deck(data.id, t.id)
|
||||
if t.kind == RollTable.KIND_VARIABLE:
|
||||
# Effect chips on other cards name variables by their card.
|
||||
for c in cards.values():
|
||||
(c as TableCard).rebuild()
|
||||
else:
|
||||
var card := card_for(t.id)
|
||||
if card:
|
||||
card.rebuild()
|
||||
mark_dirty()
|
||||
refresh_live()
|
||||
toast("Updated %s" % t.name, snap)
|
||||
)
|
||||
_add_modal(d)
|
||||
|
|
@ -1028,8 +768,6 @@ func switch_collection(id: String) -> void:
|
|||
func _show_collection(b: TowerBoard) -> void:
|
||||
data = b
|
||||
_token += 1
|
||||
cancel_choice()
|
||||
rolling_ctx = null
|
||||
board.pipes.pulse_key = ""
|
||||
load_local_state()
|
||||
if not current.is_empty():
|
||||
|
|
@ -1207,59 +945,6 @@ func _run_shell_cli(args: PackedStringArray) -> void:
|
|||
_board_menu.show_popup()
|
||||
elif menu == "collections":
|
||||
_switcher.show_popup()
|
||||
elif menu == "add":
|
||||
# The Build tools were only just shown; let them lay out first.
|
||||
await get_tree().process_frame
|
||||
await get_tree().process_frame
|
||||
_add_menu.show_popup()
|
||||
|
||||
|
||||
# ----- Logic-card screenshot flags -----
|
||||
# --answers=<a>|<b>|… answer the first questions automatically, in order
|
||||
# (an option index or -1 for a pick, a number, or text);
|
||||
# later questions open the pop-up
|
||||
# --demo-long=<n> add a table that pipes into itself n times, and fast-roll it
|
||||
# --confirm-reset open the Variables tab's "Reset all…" confirmation
|
||||
# --edit-effects=<table id> open the effects editor on every row of a card (Build)
|
||||
|
||||
func _run_logic_cli(args: PackedStringArray) -> void:
|
||||
var answers := _arg_value(args, "--answers")
|
||||
if answers != "":
|
||||
var queue: Array = Array(answers.split("|"))
|
||||
prompt_hook = func(req: Dictionary) -> Variant:
|
||||
if queue.is_empty():
|
||||
return await _ask_player(req)
|
||||
var a := str(queue.pop_front())
|
||||
return a if str(req.get("kind", "")) == "text" else a.to_int()
|
||||
var n := _arg_value(args, "--demo-long").to_int()
|
||||
if n > 0:
|
||||
var head := RollTable.create(RollTable.KIND_ROLL, "long_start", "Long chain")
|
||||
head.entries.resize(1)
|
||||
head.entries[0].text = "Off we go"
|
||||
head.entries[0].effects = "@k = 0"
|
||||
head.entries[0].add_pipe("long_link")
|
||||
var link := RollTable.create(RollTable.KIND_ROLL, "long_link", "Link")
|
||||
link.entries.resize(1)
|
||||
link.entries[0].text = "Link {@k}"
|
||||
link.entries[0].effects = "@k += 1"
|
||||
link.entries[0].add_pipe("long_link", "@k < %d" % n)
|
||||
var y := 40.0
|
||||
for t in data.tables:
|
||||
y = maxf(y, t.position.y + 80.0)
|
||||
head.position = Vector2(40, y + 400)
|
||||
link.position = Vector2(360, y + 400)
|
||||
data.tables.append(head)
|
||||
data.tables.append(link)
|
||||
_rebuild_cards()
|
||||
start_roll("long_start", true)
|
||||
var fx := card_for(_arg_value(args, "--edit-effects"))
|
||||
if fx:
|
||||
for e in fx.table.entries:
|
||||
fx._open_effects[e.id] = true
|
||||
fx.rebuild()
|
||||
if args.has("--confirm-reset"):
|
||||
tray.set_side(ResultTray.Side.VARIABLES)
|
||||
tray._vars.confirm_reset_all()
|
||||
|
||||
|
||||
# ---------- Local state: decks, persistent variables, history ----------
|
||||
|
|
@ -1312,7 +997,7 @@ func _light_steps(steps: Array) -> void:
|
|||
var ek := Roller.entry_key(tid, str(s["entry_id"]))
|
||||
lit_entries[ek] = true
|
||||
lit_texts[ek] = str(s.get("text", ""))
|
||||
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"):
|
||||
if d > 0 and stack[d - 1] is Dictionary and (stack[d - 1] as Dictionary).has("entry_id"):
|
||||
var p: Dictionary = stack[d - 1]
|
||||
var ptid := str(p.get("table_id", ""))
|
||||
var peid := str(p["entry_id"])
|
||||
|
|
@ -1346,7 +1031,7 @@ func _store_variables() -> void:
|
|||
for n: String in persistent_vars:
|
||||
var v: Variant = persistent_vars[n]
|
||||
if v is Dictionary:
|
||||
state.set_variable(data.id, n, v.get("value", ""), str(v.get("source", "")))
|
||||
state.set_variable(data.id, n, str(v.get("value", "")), str(v.get("source", "")))
|
||||
else:
|
||||
state.set_variable(data.id, n, str(v))
|
||||
|
||||
|
|
@ -1405,76 +1090,21 @@ func ref_targets_for(e: TableEntry) -> Array[String]:
|
|||
func set_variable(name: String, value: String) -> void:
|
||||
var old: Variant = persistent_vars.get(name)
|
||||
var source := str(old.get("source", "")) if old is Dictionary else ""
|
||||
# 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 card := variable_card(name)
|
||||
if source == "" and card:
|
||||
source = card.id
|
||||
var as_number := Expr.is_number(was) or (card != null and card.var_type == "number")
|
||||
var typed: Variant = Expr.to_value(value) if as_number and Expr.is_number(value) else value
|
||||
persistent_vars[name] = {"value": typed, "source": source}
|
||||
_variables_changed()
|
||||
persistent_vars[name] = {"value": value, "source": source}
|
||||
_store_variables()
|
||||
if state:
|
||||
state.save()
|
||||
tray.render()
|
||||
|
||||
|
||||
func clear_variable(name: String) -> void:
|
||||
if not persistent_vars.erase(name):
|
||||
return
|
||||
_variables_changed()
|
||||
toast("Cleared {@%s}" % name)
|
||||
|
||||
|
||||
## The variable card declaring `name` (no "@"), or null.
|
||||
func variable_card(name: String) -> RollTable:
|
||||
for t in data.tables:
|
||||
if t.kind == RollTable.KIND_VARIABLE and t.var_name == name:
|
||||
return t
|
||||
return null
|
||||
|
||||
|
||||
## Every board variable name: the set ones and the ones variable cards declare.
|
||||
func variable_names() -> Array[String]:
|
||||
var seen := {}
|
||||
for n: String in persistent_vars:
|
||||
seen[n] = true
|
||||
for t in data.tables:
|
||||
if t.kind == RollTable.KIND_VARIABLE and t.var_name != "":
|
||||
seen[t.var_name] = true
|
||||
var out: Array[String] = []
|
||||
for n: String in seen:
|
||||
out.append(n)
|
||||
out.sort_custom(func(a: String, b: String) -> bool: return a.naturalnocasecmp_to(b) < 0)
|
||||
return out
|
||||
|
||||
|
||||
## `reset @name`: a declared variable goes back to its starting value, an
|
||||
## undeclared one is cleared.
|
||||
func reset_variable(name: String) -> void:
|
||||
var ctx := Roller.new_context(data, rng, persistent_vars, decks)
|
||||
var err := Effects.reset_one(name, ctx)
|
||||
_variables_changed()
|
||||
if err != "":
|
||||
toast("Couldn't reset @%s: %s" % [name, err])
|
||||
else:
|
||||
var v: Variant = ctx.get_value("@" + name)
|
||||
toast("Reset @%s%s" % [name, "" if v == null else " to " + Expr.format_value(v)])
|
||||
|
||||
|
||||
## Resets every board variable (see reset_variable).
|
||||
func reset_all_variables() -> void:
|
||||
var ctx := Roller.new_context(data, rng, persistent_vars, decks)
|
||||
for n in variable_names():
|
||||
Effects.reset_one(n, ctx)
|
||||
_variables_changed()
|
||||
toast("Reset every variable")
|
||||
|
||||
|
||||
## Saves the variables and re-renders what shows them.
|
||||
func _variables_changed() -> void:
|
||||
_store_variables()
|
||||
if state:
|
||||
state.save()
|
||||
refresh_live()
|
||||
tray.render()
|
||||
toast("Cleared {@%s}" % name)
|
||||
|
||||
|
||||
## Rolls the variable's source table again and saves the new result.
|
||||
|
|
@ -1497,23 +1127,10 @@ func reroll_variable(name: String) -> void:
|
|||
if state:
|
||||
state.save()
|
||||
_refresh_lit()
|
||||
refresh_live()
|
||||
tray.render()
|
||||
toast("{@%s} is now %s" % [name, Formatter.strip_tags(value)])
|
||||
|
||||
|
||||
## Re-rolling only makes sense for a text value a roll table gave (a pipe's
|
||||
## "save as" or a {@var|Table}); numbers and logic-card values can't be.
|
||||
func can_reroll_variable(name: String) -> bool:
|
||||
var v: Variant = persistent_vars.get(name)
|
||||
if not (v is Dictionary) or variable_card(name) != null:
|
||||
return false
|
||||
if Expr.is_number((v as Dictionary).get("value")):
|
||||
return false
|
||||
var t := data.get_table(str((v as Dictionary).get("source", "")))
|
||||
return t != null and t.kind == RollTable.KIND_ROLL
|
||||
|
||||
|
||||
# ---------- Copy ----------
|
||||
|
||||
## Copies the current result: ResultTray.COPY_TEXT, COPY_BBCODE or COPY_DETAILS.
|
||||
|
|
@ -1532,8 +1149,7 @@ func result_text(steps: Array, kind: int) -> String:
|
|||
for s: Dictionary in steps:
|
||||
if s.get("inline", false):
|
||||
continue
|
||||
# Long pipe chains nest thousands deep; cap the indent so the text stays usable.
|
||||
var indent := " ".repeat(mini(int(s.get("depth", 0)), MAX_INDENT))
|
||||
var indent := " ".repeat(int(s.get("depth", 0)))
|
||||
var tname := str(s.get("table", ""))
|
||||
var text := str(s.get("text", ""))
|
||||
if kind == ResultTray.COPY_BBCODE:
|
||||
|
|
@ -1587,9 +1203,6 @@ func _load_board_file(path: String) -> void:
|
|||
if text == "" or not data.load_json(text):
|
||||
push_warning("Couldn't load board file %s" % path)
|
||||
return
|
||||
_token += 1
|
||||
cancel_choice()
|
||||
_switcher.refresh()
|
||||
_rebuild_cards()
|
||||
_seed_session()
|
||||
await get_tree().process_frame
|
||||
|
|
|
|||
|
|
@ -102,10 +102,7 @@ func _draw() -> void:
|
|||
## "×2 → foe" for a pipe with options, or "".
|
||||
static func _pipe_tag(e: TableEntry, to: String) -> String:
|
||||
var parts := PackedStringArray()
|
||||
if e.count_expr(to) != "":
|
||||
var ex := e.count_expr(to)
|
||||
parts.append("×" + (ex if ex.length() <= 18 else ex.substr(0, 17) + "…"))
|
||||
elif e.count_for(to) > 1:
|
||||
if e.count_for(to) > 1:
|
||||
parts.append("×%d" % e.count_for(to))
|
||||
if e.save_for(to) != "":
|
||||
parts.append("→ " + e.save_for(to))
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@ var _entry: TableEntry
|
|||
var _to: String = ""
|
||||
var _title: RichTextLabel
|
||||
var _count: LineEdit
|
||||
var _count_msg: Label
|
||||
var _save: LineEdit
|
||||
var _save_ok: StyleBoxFlat
|
||||
var _save_bad: StyleBoxFlat
|
||||
|
|
@ -51,35 +50,21 @@ func setup(p_main: Main) -> void:
|
|||
cl.custom_minimum_size = Vector2(62, 0)
|
||||
count_row.add_child(cl)
|
||||
var minus := _small_button("−")
|
||||
minus.pressed.connect(func() -> void: _set_count(str(_entry.count_for(_to) - 1) if _entry else "1"))
|
||||
minus.pressed.connect(func() -> void: _set_count(_entry.count_for(_to) - 1 if _entry else 1))
|
||||
count_row.add_child(minus)
|
||||
_count = LineEdit.new()
|
||||
_count.custom_minimum_size = Vector2(64, 0)
|
||||
_count.custom_minimum_size = Vector2(44, 0)
|
||||
_count.alignment = HORIZONTAL_ALIGNMENT_CENTER
|
||||
_count.max_length = 60
|
||||
_count.tooltip_text = "A number, or an expression such as @terms, answer or 1d3 (worked out when the pipe runs)"
|
||||
_count.max_length = 2
|
||||
_count.add_theme_stylebox_override("normal", field_ok)
|
||||
_count.add_theme_stylebox_override("focus", field_focus)
|
||||
_count.text_changed.connect(func(s: String) -> void:
|
||||
var ok := _count_error(s) == ""
|
||||
_count.add_theme_stylebox_override("normal", field_ok if ok else _save_bad)
|
||||
_count.add_theme_stylebox_override("focus", field_focus if ok else _save_bad)
|
||||
_count_msg.text = _count_error(s)
|
||||
_count_msg.visible = not ok
|
||||
reset_size()
|
||||
)
|
||||
_count.text_submitted.connect(func(s: String) -> void: _set_count(s))
|
||||
_count.focus_exited.connect(func() -> void: _set_count(_count.text))
|
||||
_count.text_submitted.connect(func(s: String) -> void: _set_count(s.to_int()))
|
||||
_count.focus_exited.connect(func() -> void: _set_count(_count.text.to_int()))
|
||||
count_row.add_child(_count)
|
||||
var plus := _small_button("+")
|
||||
plus.pressed.connect(func() -> void: _set_count(str(_entry.count_for(_to) + 1) if _entry else "1"))
|
||||
plus.pressed.connect(func() -> void: _set_count(_entry.count_for(_to) + 1 if _entry else 1))
|
||||
count_row.add_child(plus)
|
||||
count_row.add_child(Style.make_label("times", Style.body(), 14, Style.MUTED))
|
||||
_count_msg = Style.make_label("", Style.body(), 12, Style.DANGER_INK)
|
||||
_count_msg.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||
_count_msg.custom_minimum_size = Vector2(260, 0)
|
||||
_count_msg.hide()
|
||||
v.add_child(_count_msg)
|
||||
|
||||
var save_row := HBoxContainer.new()
|
||||
save_row.add_theme_constant_override("separation", 6)
|
||||
|
|
@ -143,9 +128,7 @@ func open(pipe_key: String, at: Vector2) -> void:
|
|||
key = pipe_key
|
||||
var target := main.data.get_table(_to)
|
||||
_title.text = "%s [color=#%s]→[/color] [b]%s[/b]" % [RichText.preview(_entry.text, main.data), Style.COPPER.to_html(false), RichText.plain(Formatter.strip_tags(target.name)) if target else _to]
|
||||
_count.text = _entry.count_text(_to)
|
||||
_count.add_theme_stylebox_override("normal", _save_ok)
|
||||
_count_msg.hide()
|
||||
_count.text = str(_entry.count_for(_to))
|
||||
_save.text = _entry.save_for(_to)
|
||||
_save.add_theme_stylebox_override("normal", _save_ok)
|
||||
main.board.pipes.select_key = pipe_key
|
||||
|
|
@ -158,27 +141,14 @@ func open(pipe_key: String, at: Vector2) -> void:
|
|||
popup(Rect2i(Vector2i(p), Vector2i.ZERO))
|
||||
|
||||
|
||||
## Sets the count from typed text: a whole number (1–99) or an expression.
|
||||
## Text that isn't a valid expression is left in the field, unsaved.
|
||||
func _set_count(text: String) -> void:
|
||||
if _entry == null or _count_error(text) != "":
|
||||
func _set_count(n: int) -> void:
|
||||
if _entry == null:
|
||||
return
|
||||
var before := _entry.count_text(_to)
|
||||
_entry.set_pipe_count(_to, text.strip_edges())
|
||||
_count.text = _entry.count_text(_to)
|
||||
if _entry.count_text(_to) != before:
|
||||
_entry.set_pipe_count(_to, n)
|
||||
_count.text = str(_entry.count_for(_to))
|
||||
main.mark_dirty()
|
||||
|
||||
|
||||
## "" when `text` is a usable pipe count, else why not.
|
||||
static func _count_error(text: String) -> String:
|
||||
var s := text.strip_edges()
|
||||
if s == "" or s.is_valid_int():
|
||||
return ""
|
||||
var err := Expr.check(s)
|
||||
return "" if err == "" else "Not a number or expression: " + err
|
||||
|
||||
|
||||
func _commit_save() -> void:
|
||||
if _entry == null:
|
||||
return
|
||||
|
|
|
|||
|
|
@ -43,8 +43,6 @@ func _draw() -> void:
|
|||
var card := main.card_for(t.id)
|
||||
if card == null or not card.is_inside_tree():
|
||||
continue
|
||||
# Variable cards are never rolled, so nothing pipes into them.
|
||||
if t.kind != RollTable.KIND_VARIABLE:
|
||||
_port(card.inlet_point(), Style.COPPER, Style.COPPER_DARK, 1.0)
|
||||
for e in t.entries:
|
||||
if not card.rows.has(e.id):
|
||||
|
|
|
|||
|
|
@ -25,24 +25,6 @@ var _tab_earlier: Button
|
|||
var _tab_vars: Button
|
||||
var _shown_for: Dictionary = {}
|
||||
var _shown_count := 0
|
||||
var _scroll: ScrollContainer
|
||||
var _halt: PanelContainer
|
||||
var _halt_label: Label
|
||||
var _headline: PanelContainer
|
||||
var _headline_cap: Label
|
||||
var _headline_text: RichTextLabel
|
||||
## True when "+N earlier steps" has been opened for the current roll.
|
||||
var expanded := false
|
||||
var _scroll_to_end := false
|
||||
|
||||
## A long chain shows only its last steps; the rest sit behind a toggle.
|
||||
const TAIL := 12
|
||||
## Most chips shown even when expanded (a chain may have thousands).
|
||||
const MAX_EXPANDED := 300
|
||||
## The chips area scrolls past this height instead of pushing the board up.
|
||||
const MAX_FLOW_HEIGHT := 200.0
|
||||
## Most effect lines listed under one chip.
|
||||
const EFFECT_LINES := 3
|
||||
|
||||
|
||||
func setup(p_main: Main) -> void:
|
||||
|
|
@ -67,7 +49,6 @@ func setup(p_main: Main) -> void:
|
|||
_title.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
head.add_child(_title)
|
||||
_again = Style.bar_button("Roll again")
|
||||
_again.tooltip_text = "Shift-click to skip the animation"
|
||||
_again.pressed.connect(func() -> void:
|
||||
if not main.current.is_empty():
|
||||
main.start_roll(main.current["root"])
|
||||
|
|
@ -75,50 +56,12 @@ func setup(p_main: Main) -> void:
|
|||
head.add_child(_again)
|
||||
_copy = _make_copy_menu()
|
||||
head.add_child(_copy)
|
||||
_halt = PanelContainer.new()
|
||||
_halt.add_theme_stylebox_override("panel", Style.box(Style.WARN_BG, 8, [10, 3, 10, 4]))
|
||||
_halt.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
_halt_label = Style.make_label("", Style.body_bold(), 14, Style.WARN_INK)
|
||||
_halt.add_child(_halt_label)
|
||||
_halt.hide()
|
||||
head.add_child(_halt)
|
||||
|
||||
# A chain that reached a sheet card leads with the rendered sheet.
|
||||
_headline = PanelContainer.new()
|
||||
var hsb := Style.box(Style.CARD, 10, [16, 10, 16, 12])
|
||||
Style.bordered(hsb, 2, Style.BRASS)
|
||||
_headline.add_theme_stylebox_override("panel", hsb)
|
||||
_headline.size_flags_horizontal = SIZE_SHRINK_BEGIN
|
||||
var hv := VBoxContainer.new()
|
||||
hv.add_theme_constant_override("separation", 2)
|
||||
_headline.add_child(hv)
|
||||
_headline_cap = Style.make_label("", Style.body(), 12, Style.MUTED)
|
||||
hv.add_child(_headline_cap)
|
||||
_headline_text = RichText.label("", 17, Style.INK, false, false)
|
||||
RichText.hook_hover(_headline_text, main)
|
||||
hv.add_child(_headline_text)
|
||||
_headline.hide()
|
||||
_headline.size_flags_vertical = SIZE_SHRINK_BEGIN
|
||||
# The headline sits left of the chips, so a sheet doesn't make the tray taller.
|
||||
var body_row := HBoxContainer.new()
|
||||
body_row.add_theme_constant_override("separation", 14)
|
||||
now.add_child(body_row)
|
||||
body_row.add_child(_headline)
|
||||
|
||||
_scroll = ScrollContainer.new()
|
||||
_scroll.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
|
||||
_scroll.custom_minimum_size = Vector2(0, 58)
|
||||
_flow = HFlowContainer.new()
|
||||
_flow.add_theme_constant_override("h_separation", 0)
|
||||
_flow.add_theme_constant_override("v_separation", 8)
|
||||
_flow.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
# Keep the tray's height steady while a new roll's chips arrive.
|
||||
_flow.custom_minimum_size = Vector2(0, 58)
|
||||
_flow.minimum_size_changed.connect(_fit_scroll.call_deferred)
|
||||
_flow.resized.connect(_fit_scroll.call_deferred)
|
||||
_scroll.add_child(_flow)
|
||||
body_row.add_child(_scroll)
|
||||
now.add_child(_flow)
|
||||
_empty = Style.make_label("Click a die on any table to roll.", Style.body(), 16, Style.ON_FELT_MUTED)
|
||||
now.add_child(_empty)
|
||||
|
||||
|
|
@ -205,8 +148,6 @@ func render() -> void:
|
|||
var fresh_from := 0
|
||||
if is_same(current, _shown_for):
|
||||
fresh_from = _shown_count
|
||||
else:
|
||||
expanded = false
|
||||
_shown_for = current
|
||||
_shown_count = steps.size()
|
||||
|
||||
|
|
@ -214,7 +155,6 @@ func render() -> void:
|
|||
_flow.remove_child(c)
|
||||
c.queue_free()
|
||||
_empty.visible = current.is_empty()
|
||||
_render_status(current, steps)
|
||||
if current.is_empty():
|
||||
_title.text = "RESULT"
|
||||
_again.hide()
|
||||
|
|
@ -226,23 +166,15 @@ func render() -> void:
|
|||
_again.visible = main.data.get_table(current["root"]) != null
|
||||
var done: bool = current.get("done", false)
|
||||
_copy.visible = done
|
||||
var first := visible_from(steps.size(), expanded)
|
||||
if first > 0 or expanded and steps.size() > TAIL:
|
||||
_flow.add_child(_earlier_toggle(first, steps.size()))
|
||||
for i in range(first, steps.size()):
|
||||
for i in steps.size():
|
||||
var step: Dictionary = steps[i]
|
||||
if i > first:
|
||||
if i > 0:
|
||||
_flow.add_child(_link(step.get("inline", false)))
|
||||
var chip := _chip(step, done and i == steps.size() - 1)
|
||||
_flow.add_child(chip)
|
||||
if i >= fresh_from and not current.get("fast", false):
|
||||
if i >= fresh_from:
|
||||
chip.modulate.a = 0.3
|
||||
create_tween().tween_property(chip, "modulate:a", 1.0, 0.25)
|
||||
var asking := str(current.get("asking", ""))
|
||||
if asking != "" and not done:
|
||||
if steps.size() > first:
|
||||
_flow.add_child(_link(false))
|
||||
_flow.add_child(_asking_chip(asking))
|
||||
|
||||
for c in _earlier.get_children():
|
||||
_earlier.remove_child(c)
|
||||
|
|
@ -255,185 +187,21 @@ func render() -> void:
|
|||
time.custom_minimum_size = Vector2(44, 0)
|
||||
time.size_flags_vertical = SIZE_SHRINK_BEGIN
|
||||
row.add_child(time)
|
||||
var line := RichText.label(earlier_line(rec), 14, Style.ON_FELT, false)
|
||||
var texts := PackedStringArray()
|
||||
for s: Dictionary in rec["steps"]:
|
||||
if not s.get("inline", false):
|
||||
texts.append(RichText.decorate(str(s["text"]), true))
|
||||
var line := RichText.label("[color=#%s]%s:[/color] %s" % [Style.ON_FELT_MUTED.to_html(false),
|
||||
RichText.plain(Formatter.strip_tags(str(rec["root_name"]))), " → ".join(texts)], 14, Style.ON_FELT, false)
|
||||
line.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
RichText.hook_hover(line, main)
|
||||
row.add_child(line)
|
||||
_earlier.add_child(row)
|
||||
|
||||
var n := main.variable_names().size()
|
||||
var n := main.persistent_vars.size()
|
||||
_tab_vars.text = "VARIABLES · %d" % n if n > 0 else "VARIABLES"
|
||||
if side == Side.VARIABLES:
|
||||
_vars.render()
|
||||
_scroll_to_end = not expanded
|
||||
_fit_scroll.call_deferred()
|
||||
|
||||
|
||||
## Index of the first chip shown for a chain of `count` steps: only the last
|
||||
## TAIL steps of a long chain, or up to MAX_EXPANDED when expanded.
|
||||
static func visible_from(count: int, is_expanded: bool) -> int:
|
||||
if count <= TAIL:
|
||||
return 0
|
||||
if is_expanded:
|
||||
return maxi(0, count - MAX_EXPANDED)
|
||||
return count - TAIL
|
||||
|
||||
|
||||
## One Earlier row: "Root: a → b → c", with only the last few steps of a long
|
||||
## chain.
|
||||
static func earlier_line(rec: Dictionary) -> String:
|
||||
var texts := PackedStringArray()
|
||||
var all: Array = rec.get("steps", [])
|
||||
var shown := 0
|
||||
var skipped := 0
|
||||
for k in range(all.size() - 1, -1, -1):
|
||||
var s: Dictionary = all[k]
|
||||
if s.get("inline", false):
|
||||
continue
|
||||
if shown >= 6:
|
||||
skipped += 1
|
||||
continue
|
||||
texts.insert(0, RichText.decorate(_one_line(str(s["text"])), true))
|
||||
shown += 1
|
||||
var lead := "[color=#%s]%s:[/color] " % [Style.ON_FELT_MUTED.to_html(false), RichText.plain(Formatter.strip_tags(str(rec.get("root_name", ""))))]
|
||||
if skipped > 0:
|
||||
lead += "[color=#%s]… %d earlier →[/color] " % [Style.ON_FELT_MUTED.to_html(false), skipped]
|
||||
return lead + " → ".join(texts)
|
||||
|
||||
|
||||
## The first line of a (sheet's) multi-line text, with "…" when there's more.
|
||||
static func _one_line(text: String) -> String:
|
||||
var nl := text.find("\n")
|
||||
if nl < 0:
|
||||
return text
|
||||
return Formatter.close_open_tags(text.substr(0, nl)) + " …"
|
||||
|
||||
|
||||
## The "Cancelled" / "Stopped after 10,000 actions" pill, and the sheet headline.
|
||||
func _render_status(current: Dictionary, steps: Array) -> void:
|
||||
var halted := str(current.get("halted", ""))
|
||||
if halted == "" and current.get("done", false):
|
||||
for k in range(steps.size() - 1, maxi(-1, steps.size() - 4), -1):
|
||||
var s: Dictionary = steps[k]
|
||||
if s.get("cancelled", false) or s.get("limit", false):
|
||||
halted = Formatter.strip_tags(str(s.get("text", "")))
|
||||
break
|
||||
_halt.visible = halted != ""
|
||||
if halted != "":
|
||||
_halt_label.text = ("✕ " if halted == Roller.CANCELLED else "⚠ ") + halted
|
||||
_halt.tooltip_text = "The roll was cancelled at a question; what came before is kept." if halted == Roller.CANCELLED \
|
||||
else "This roll took too many steps, so it stopped; everything up to that point is kept."
|
||||
var sheet := sheet_step(steps) if current.get("done", false) else {}
|
||||
_headline.visible = not sheet.is_empty()
|
||||
if not sheet.is_empty():
|
||||
_headline_cap.text = Formatter.strip_tags(str(sheet.get("table", ""))).to_upper()
|
||||
_headline_text.text = RichText.decorate(str(sheet.get("text", "")))
|
||||
|
||||
|
||||
## The last sheet step of a chain (the headline), or {}.
|
||||
static func sheet_step(steps: Array) -> Dictionary:
|
||||
for k in range(steps.size() - 1, -1, -1):
|
||||
var s: Dictionary = steps[k]
|
||||
if str(s.get("kind", "")) == RollTable.KIND_SHEET and not s.get("stop", false):
|
||||
return s
|
||||
return {}
|
||||
|
||||
|
||||
func _fit_scroll() -> void:
|
||||
if _scroll == null or _flow == null:
|
||||
return
|
||||
var want := _flow.get_combined_minimum_size().y
|
||||
_scroll.custom_minimum_size.y = clampf(want, 58.0, MAX_FLOW_HEIGHT)
|
||||
if _scroll_to_end:
|
||||
# The newest steps (and an open question) are at the end of the chain.
|
||||
_scroll_to_end = false
|
||||
await get_tree().process_frame
|
||||
await get_tree().process_frame
|
||||
if is_instance_valid(_scroll):
|
||||
_scroll.scroll_vertical = int(_scroll.get_v_scroll_bar().max_value)
|
||||
|
||||
|
||||
## "+N earlier steps" (or "Hide earlier steps") at the start of a long chain.
|
||||
func _earlier_toggle(first: int, total: int) -> Control:
|
||||
var b := Button.new()
|
||||
if expanded:
|
||||
b.text = "Hide earlier steps" if first == 0 else "Hide earlier steps (%s not shown)" % _thousands(first)
|
||||
else:
|
||||
b.text = "+%s earlier steps" % _thousands(first)
|
||||
b.tooltip_text = "This chain has %s steps" % _thousands(total)
|
||||
b.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
var n := Style.bordered(Style.box(Color(1, 1, 1, 0.04), 8, [12, 6, 12, 6]), 1, Color(1, 1, 1, 0.16))
|
||||
var h := Style.bordered(Style.box(Color(1, 1, 1, 0.1), 8, [12, 6, 12, 6]), 1, Color(Style.BRASS, 0.5))
|
||||
Style.skin_button(b, n, h, h, Style.ON_FELT_MUTED, Style.ON_FELT)
|
||||
b.add_theme_font_size_override("font_size", 14)
|
||||
b.pressed.connect(func() -> void:
|
||||
expanded = not expanded
|
||||
render()
|
||||
)
|
||||
var wrap := HBoxContainer.new()
|
||||
wrap.add_theme_constant_override("separation", 0)
|
||||
wrap.add_child(b)
|
||||
var gap := Control.new()
|
||||
gap.custom_minimum_size = Vector2(10, 0)
|
||||
wrap.add_child(gap)
|
||||
return wrap
|
||||
|
||||
|
||||
static func _thousands(n: int) -> 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 s + out
|
||||
|
||||
|
||||
## A dashed placeholder chip for the question that is open right now.
|
||||
func _asking_chip(title: String) -> Control:
|
||||
var p := PanelContainer.new()
|
||||
var sb := Style.box(Color(1, 1, 1, 0.05), 9, [12, 7, 12, 8])
|
||||
Style.bordered(sb, 1, Color(Style.BRASS, 0.6))
|
||||
p.add_theme_stylebox_override("panel", sb)
|
||||
p.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
var v := VBoxContainer.new()
|
||||
v.add_theme_constant_override("separation", 1)
|
||||
p.add_child(v)
|
||||
v.add_child(Style.make_label(title, Style.body(), 12, Style.ON_FELT_MUTED))
|
||||
v.add_child(Style.make_label("Waiting for your answer…", Style.display(), 20, Style.BRASS))
|
||||
return p
|
||||
|
||||
|
||||
## The muted line above a chip's text: table name and how it got its result.
|
||||
static func caption_for(step: Dictionary) -> String:
|
||||
var caption := Formatter.strip_tags(str(step["table"]))
|
||||
var num: String = str(step.get("num", ""))
|
||||
match str(step.get("kind", "")):
|
||||
RollTable.KIND_CHOICE:
|
||||
if step.get("cancelled", false):
|
||||
pass
|
||||
elif step.has("answer"):
|
||||
caption += " · answered"
|
||||
elif step.get("picked", false):
|
||||
caption += " · picked"
|
||||
elif step.get("random", false):
|
||||
caption += " · random"
|
||||
if num != "":
|
||||
caption += ", rolled %s on %s" % [num, step.get("dice", "d%d" % int(step.get("die", 0)))]
|
||||
RollTable.KIND_LOOP:
|
||||
if step.has("pass"):
|
||||
caption += " · pass %s" % str(step["pass"])
|
||||
elif step.get("after", false):
|
||||
caption += " · afterwards"
|
||||
RollTable.KIND_SHEET:
|
||||
caption += " · sheet"
|
||||
_:
|
||||
if num != "":
|
||||
caption += " · rolled %s on %s" % [num, step.get("dice", "d%d" % int(step.get("die", 0)))]
|
||||
if step.get("reshuffled", false):
|
||||
caption += " · deck reshuffled"
|
||||
if str(step.get("save_as", "")) != "":
|
||||
caption += " · saved as {%s}" % step["save_as"]
|
||||
return caption
|
||||
|
||||
|
||||
func _chip(step: Dictionary, last: bool) -> Control:
|
||||
|
|
@ -454,63 +222,32 @@ func _chip(step: Dictionary, last: bool) -> Control:
|
|||
var v := VBoxContainer.new()
|
||||
v.add_theme_constant_override("separation", 1)
|
||||
p.add_child(v)
|
||||
var caption := caption_for(step)
|
||||
var num: String = step["num"]
|
||||
var caption := Formatter.strip_tags(str(step["table"]))
|
||||
if num != "":
|
||||
caption += " · rolled %s on %s" % [num, step.get("dice", "d%d" % int(step["die"]))]
|
||||
if step.get("reshuffled", false):
|
||||
caption += " · deck reshuffled"
|
||||
if str(step.get("save_as", "")) != "":
|
||||
caption += " · saved as {%s}" % step["save_as"]
|
||||
var has_details := main.details().step_has_details(step)
|
||||
if has_details:
|
||||
caption += " " + RichText.INFO_MARK
|
||||
var cap := Style.make_label(caption, Style.body(), 11 if inline else 12, Style.MUTED)
|
||||
cap.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
v.add_child(cap)
|
||||
var raw := str(step["text"])
|
||||
if str(step.get("kind", "")) == RollTable.KIND_SHEET:
|
||||
raw = _one_line(raw)
|
||||
if step.has("answer") and Formatter.strip_tags(raw).strip_edges() == "":
|
||||
raw = "[i]no answer[/i]"
|
||||
var shown := RichText.decorate(raw)
|
||||
var shown := RichText.decorate(str(step["text"]))
|
||||
var body := RichText.display_label(shown, 16 if inline else 20, Style.DANGER_INK if step.get("stop", false) else Style.INK)
|
||||
if Formatter.strip_tags(shown).length() > 56:
|
||||
body.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||
body.custom_minimum_size = Vector2(420, 0)
|
||||
RichText.hook_hover(body, main)
|
||||
v.add_child(body)
|
||||
var fx: Array = step.get("effects", [])
|
||||
if not fx.is_empty():
|
||||
v.add_child(_effect_lines(fx))
|
||||
if has_details:
|
||||
p.mouse_entered.connect(func() -> void: main.details().show_step(p, step))
|
||||
return p
|
||||
|
||||
|
||||
## The effect log under a chip: a few compact lines, errors in red.
|
||||
func _effect_lines(fx: Array) -> Control:
|
||||
var box := VBoxContainer.new()
|
||||
box.add_theme_constant_override("separation", 0)
|
||||
box.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
var shown := 0
|
||||
var errors := 0
|
||||
for l: Variant in fx:
|
||||
var d: Dictionary = l if l is Dictionary else {"text": str(l)}
|
||||
var bad: bool = d.get("error", false)
|
||||
if bad:
|
||||
errors += 1
|
||||
# Errors are always listed; ordinary lines up to EFFECT_LINES.
|
||||
if shown >= EFFECT_LINES and not bad:
|
||||
continue
|
||||
var lab := Style.make_label(("⚠ " if bad else "") + str(d.get("text", "")), Style.body_bold() if bad else Style.body(), 12,
|
||||
Style.DANGER_INK if bad else Style.COPPER_DARK)
|
||||
lab.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
lab.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
|
||||
lab.custom_minimum_size.x = 0
|
||||
box.add_child(lab)
|
||||
shown += 1
|
||||
var more := fx.size() - shown
|
||||
if more > 0:
|
||||
box.add_child(Style.make_label("+%d more" % more, Style.body(), 11, Style.MUTED))
|
||||
var tip := Effects.log_text(fx)
|
||||
box.tooltip_text = "\n".join(tip)
|
||||
return box
|
||||
|
||||
|
||||
func _link(inline: bool = false) -> Control:
|
||||
var link := Panel.new()
|
||||
var sb := Style.box(Style.BRASS)
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@ const _COUNT_PATTERN := "^(?:(\\d+)\\s*[x×]|(\\d*[dD]\\d+(?:\\s*[+-]\\s*\\d+)?)
|
|||
|
||||
static var _var_re: RegEx
|
||||
static var _count_re: RegEx
|
||||
static var _list_re: RegEx
|
||||
|
||||
## Colours for marker text, on cards (light) and on the felt (dark).
|
||||
const REF_INK := Color("#1d6656")
|
||||
|
|
@ -112,24 +111,6 @@ static func preview(text: String, board: TowerBoard) -> String:
|
|||
i += (tag["raw"] as String).length()
|
||||
continue
|
||||
elif c == "{":
|
||||
# {= expr}: a computed value, shown as written (red if it can't parse).
|
||||
if i + 1 < n and text[i + 1] == "=":
|
||||
var close := text.find("}", i + 2)
|
||||
var nl := text.find("\n", i + 2)
|
||||
if close >= 0 and (nl < 0 or close < nl):
|
||||
var src := text.substr(i + 2, close - i - 2).strip_edges()
|
||||
var err := Expr.check(src)
|
||||
var ink := Style.DANGER_INK if err != "" else VAR_INK
|
||||
out += "[url=%s][color=#%s]{= %s}[/color][/url]" % ["error:expr" if err != "" else "expr:" + plain(src).replace("]", ""),
|
||||
ink.to_html(false), plain(src)]
|
||||
i = close + 1
|
||||
continue
|
||||
# {@prefix_*}: a list of every variable with the prefix.
|
||||
var lm := _lre().search(text, i)
|
||||
if lm != null and lm.get_start() == i:
|
||||
out += "[url=var:@%s*][color=#%s]{@%s*}[/color][/url]" % [lm.get_string(1), VAR_INK.to_html(false), lm.get_string(1)]
|
||||
i = lm.get_end()
|
||||
continue
|
||||
var m := _vre().search(text, i)
|
||||
if m != null and m.get_start() == i:
|
||||
var vname := m.get_string(1)
|
||||
|
|
@ -201,7 +182,7 @@ static func _marker_color(meta: String, on_felt: bool) -> String:
|
|||
return (REF_INK_FELT if on_felt else REF_INK).to_html(false)
|
||||
if meta.begins_with("var:"):
|
||||
return (VAR_INK_FELT if on_felt else VAR_INK).to_html(false)
|
||||
if meta.begins_with("missing:") or meta.begins_with("unset:") or meta.begins_with("deep:") or meta.begins_with("error:"):
|
||||
if meta.begins_with("missing:") or meta.begins_with("unset:") or meta.begins_with("deep:"):
|
||||
return (BAD_INK_FELT if on_felt else Style.DANGER_INK).to_html(false)
|
||||
return ""
|
||||
|
||||
|
|
@ -217,13 +198,6 @@ static func _vre() -> RegEx:
|
|||
return _var_re
|
||||
|
||||
|
||||
static func _lre() -> RegEx:
|
||||
if _list_re == null:
|
||||
_list_re = RegEx.new()
|
||||
_list_re.compile("\\{@([A-Za-z0-9_]*)\\*\\}")
|
||||
return _list_re
|
||||
|
||||
|
||||
static func _cre() -> RegEx:
|
||||
if _count_re == null:
|
||||
_count_re = RegEx.new()
|
||||
|
|
|
|||
537
ui/table_card.gd
537
ui/table_card.gd
|
|
@ -3,13 +3,6 @@ extends PanelContainer
|
|||
## One table on the board: a header with the collapse toggle, name and die
|
||||
## button, then its numbered results. Rebuilt from the RollTable whenever the
|
||||
## mode, the table's shape, or (when collapsed) the lit result changes.
|
||||
##
|
||||
## Logic cards (docs/LOGIC.md) share the layout: a choice card has a "?"
|
||||
## badge, its question and its options (or one Answer row); a loop card shows
|
||||
## its rule and the Each time / Afterwards rows; a variable card shows its
|
||||
## live value and has no rows; a sheet card's one row is its rendered
|
||||
## template. Live text (values, sheets, prompts) is only re-rendered by
|
||||
## refresh_live(), which Main calls after rolls and edits, never per frame.
|
||||
|
||||
const WIDTH := 256.0
|
||||
## Build mode has more controls per row, so cards are a little wider there.
|
||||
|
|
@ -47,15 +40,7 @@ var _deck_row: Control
|
|||
var _deck_label: Label
|
||||
## Entry ids whose details editor is open (Build mode).
|
||||
var _open_details: Dictionary = {}
|
||||
## Entry ids whose effects editor is open (Build mode).
|
||||
var _open_effects: Dictionary = {}
|
||||
var _table_details_open := false
|
||||
## Live parts, updated by refresh_live().
|
||||
var _prompt_label: RichTextLabel
|
||||
var _var_value: Label
|
||||
var _var_hint: Label
|
||||
var _sheet_label: RichTextLabel
|
||||
var _live_cache: Dictionary = {}
|
||||
|
||||
|
||||
func setup(p_main: Main, p_table: RollTable) -> void:
|
||||
|
|
@ -104,17 +89,11 @@ func rebuild() -> void:
|
|||
_flick_id = ""
|
||||
_deck_row = null
|
||||
_deck_label = null
|
||||
_prompt_label = null
|
||||
_var_value = null
|
||||
_var_hint = null
|
||||
_sheet_label = null
|
||||
_live_cache.clear()
|
||||
|
||||
var build := main.mode == Main.Mode.BUILD
|
||||
custom_minimum_size = Vector2(card_width(), 0)
|
||||
_shrink.call_deferred()
|
||||
var ranged := table.is_ranged()
|
||||
var collapsed := is_collapsed()
|
||||
var col := _vbox(0)
|
||||
add_child(col)
|
||||
col.add_child(_make_header(build, ranged))
|
||||
|
|
@ -126,24 +105,13 @@ func rebuild() -> void:
|
|||
ted.add_theme_constant_override("margin_top", 8)
|
||||
col.add_child(ted)
|
||||
|
||||
if table.kind == RollTable.KIND_VARIABLE:
|
||||
col.add_child(_make_variable_body(build))
|
||||
_warn_panel = _make_warning()
|
||||
col.add_child(_warn_panel)
|
||||
_update_warning()
|
||||
if build:
|
||||
col.add_child(_make_footer(ranged))
|
||||
_apply_style()
|
||||
refresh_live()
|
||||
return
|
||||
|
||||
var pad := MarginContainer.new()
|
||||
pad.mouse_filter = MOUSE_FILTER_PASS
|
||||
pad.add_theme_constant_override("margin_top", 6)
|
||||
pad.add_theme_constant_override("margin_bottom", 8)
|
||||
_list_box = _vbox(0)
|
||||
pad.add_child(_list_box)
|
||||
if not collapsed and table.entries.size() > LONG_LIST:
|
||||
if not table.collapsed and table.entries.size() > LONG_LIST:
|
||||
list_scroll = ScrollContainer.new()
|
||||
list_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
|
||||
list_scroll.custom_minimum_size = Vector2(0, LIST_HEIGHT)
|
||||
|
|
@ -159,21 +127,16 @@ func rebuild() -> void:
|
|||
for i in table.entries.size():
|
||||
var e := table.entries[i]
|
||||
var lit := main.is_entry_lit(table.id, e.id)
|
||||
if collapsed and not lit:
|
||||
if table.collapsed and not lit:
|
||||
continue
|
||||
if table.kind == RollTable.KIND_SHEET:
|
||||
_list_box.add_child(_make_sheet_row(e, build))
|
||||
else:
|
||||
_list_box.add_child(_make_row(e, i, build, ranged, numw))
|
||||
_set_row_state(e.id, RowState.LIT if lit else RowState.NORMAL)
|
||||
if build and _open_effects.has(e.id):
|
||||
_list_box.add_child(_effects_editor(e, 12.0 + numw + 4.0))
|
||||
if build and _open_details.has(e.id):
|
||||
_list_box.add_child(_details_editor(e.details, "Details for this result (BBCode)", 12.0 + numw + 4.0,
|
||||
func(s: String) -> void:
|
||||
e.details = s
|
||||
main.mark_dirty()))
|
||||
if collapsed:
|
||||
if table.collapsed:
|
||||
_list_box.add_child(_make_more_row(numw))
|
||||
|
||||
_warn_panel = _make_warning()
|
||||
|
|
@ -182,7 +145,6 @@ func rebuild() -> void:
|
|||
if build:
|
||||
col.add_child(_make_footer(ranged))
|
||||
_apply_style()
|
||||
refresh_live()
|
||||
if list_scroll != null:
|
||||
for eid in rows:
|
||||
if main.is_entry_lit(table.id, eid):
|
||||
|
|
@ -190,15 +152,6 @@ func rebuild() -> void:
|
|||
break
|
||||
|
||||
|
||||
## Variable and sheet cards always show everything; other cards collapse.
|
||||
func is_collapsed() -> bool:
|
||||
return table.collapsed and can_collapse()
|
||||
|
||||
|
||||
func can_collapse() -> bool:
|
||||
return table.kind != RollTable.KIND_VARIABLE and table.kind != RollTable.KIND_SHEET
|
||||
|
||||
|
||||
func _reveal_when_laid_out(eid: String) -> void:
|
||||
await get_tree().process_frame
|
||||
if is_instance_valid(list_scroll):
|
||||
|
|
@ -245,7 +198,6 @@ func _make_header(build: bool, ranged: bool) -> Control:
|
|||
header.add_child(head_box)
|
||||
head_box.add_child(row)
|
||||
|
||||
if can_collapse():
|
||||
var chevron := ChevronButton.new()
|
||||
chevron.open = not table.collapsed
|
||||
chevron.tooltip_text = ("Expand " if table.collapsed else "Collapse ") + table.name
|
||||
|
|
@ -300,81 +252,23 @@ func _make_header(build: bool, ranged: bool) -> Control:
|
|||
titles.add_child(name_row)
|
||||
else:
|
||||
titles.add_child(title)
|
||||
var sub := _subtitle()
|
||||
if sub != "":
|
||||
var cl := Style.make_label(sub, Style.body(true), 12, Style.MUTED)
|
||||
if ranged or table.collapsed:
|
||||
var count := "%d %s" % [table.entries.size(), "ranges" if ranged else "results"]
|
||||
var cl := Style.make_label(count, Style.body(true), 12, Style.MUTED)
|
||||
cl.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
cl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||
titles.add_child(cl)
|
||||
row.add_child(titles)
|
||||
if table.card_mode:
|
||||
_deck_row = _make_deck_row()
|
||||
|
||||
var go := _make_go_button()
|
||||
if go != null:
|
||||
row.add_child(go)
|
||||
if _deck_row != null:
|
||||
head_box.add_child(_deck_row)
|
||||
var extra := _make_kind_header(build)
|
||||
if extra != null:
|
||||
head_box.add_child(extra)
|
||||
return header
|
||||
|
||||
|
||||
## The small line under the title in Play mode ("2d6 + dm(@end) · 2 ranges").
|
||||
func _subtitle() -> String:
|
||||
match table.kind:
|
||||
RollTable.KIND_ROLL:
|
||||
if table.is_ranged():
|
||||
var n := "%d ranges" % table.entries.size()
|
||||
return "%s · %s" % [table.dice_label(), n] if table.is_expr_dice() else n
|
||||
if table.collapsed:
|
||||
return "%d results" % table.entries.size()
|
||||
RollTable.KIND_CHOICE:
|
||||
if table.collapsed:
|
||||
return "%d options" % table.entries.size()
|
||||
return ""
|
||||
|
||||
|
||||
## The header button that starts a roll: the die on roll tables, a "?" badge on
|
||||
## choice cards, a loop arrow on loop cards and "Print" on sheets. Variable
|
||||
## cards have none.
|
||||
func _make_go_button() -> Button:
|
||||
_die_icon = null
|
||||
if table.kind == RollTable.KIND_VARIABLE:
|
||||
return null
|
||||
var b := Button.new()
|
||||
b.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
b.add_theme_font_override("font", Style.display(true))
|
||||
b.add_theme_font_size_override("font_size", 17)
|
||||
var left := 10
|
||||
match table.kind:
|
||||
RollTable.KIND_CHOICE:
|
||||
b.text = "?"
|
||||
b.add_theme_font_size_override("font_size", 20)
|
||||
b.custom_minimum_size = Vector2(36, 0)
|
||||
b.tooltip_text = "Ask: %s" % Formatter.strip_tags(table.prompt if table.prompt != "" else table.name)
|
||||
RollTable.KIND_LOOP:
|
||||
b.custom_minimum_size = Vector2(38, 32)
|
||||
b.tooltip_text = "Run %s" % Formatter.strip_tags(table.name)
|
||||
var icon := Control.new()
|
||||
icon.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
icon.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
|
||||
icon.draw.connect(func() -> void: Icons.draw_loop(icon, icon.size / 2.0 + Vector2(0, -1), 7.0, Style.BRASS, 2.2))
|
||||
b.add_child(icon)
|
||||
RollTable.KIND_SHEET:
|
||||
b.text = "Print"
|
||||
b.add_theme_font_override("font", Style.body_bold(true))
|
||||
b.add_theme_font_size_override("font_size", 14)
|
||||
b.tooltip_text = "Print this sheet in the tray"
|
||||
_:
|
||||
left = 34
|
||||
var label := "d%d" % table.die_size()
|
||||
if table.is_expr_dice():
|
||||
label = table.dice_label() if table.dice_label().length() <= 5 else "Roll"
|
||||
b.text = label
|
||||
b.tooltip_text = "Roll %s on %s\nShift-click to skip the animation" % [table.dice_label(), table.name]
|
||||
var rn := Style.box(Style.FELT, 8, [left, 6, 10, 6])
|
||||
var die := table.die_size()
|
||||
var roll := Button.new()
|
||||
roll.text = "d%d" % die
|
||||
roll.tooltip_text = "Roll d%d on %s" % [die, table.name]
|
||||
roll.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
roll.add_theme_font_override("font", Style.display(true))
|
||||
roll.add_theme_font_size_override("font_size", 17)
|
||||
var rn := Style.box(Style.FELT, 8, [34, 6, 10, 6])
|
||||
rn.border_width_bottom = 2
|
||||
rn.border_color = Style.FELT_DEEP
|
||||
var rh := rn.duplicate() as StyleBoxFlat
|
||||
|
|
@ -383,67 +277,16 @@ func _make_go_button() -> Button:
|
|||
rp.border_width_bottom = 1
|
||||
rp.content_margin_top = 7
|
||||
rp.content_margin_bottom = 5
|
||||
Style.skin_button(b, rn, rh, rp, Style.BRASS)
|
||||
if table.kind == RollTable.KIND_ROLL:
|
||||
var die := DieIcon.new()
|
||||
die.spinning = _rolling
|
||||
_die_icon = die
|
||||
b.add_child(die)
|
||||
b.resized.connect(func() -> void: die.position = Vector2(8, (b.size.y - 20.0) / 2.0 - 1.0))
|
||||
b.pressed.connect(func() -> void: main.start_roll(table.id))
|
||||
return b
|
||||
|
||||
|
||||
## Kind-specific lines under the header: a choice card's question, a loop's
|
||||
## rule, a variable's name.
|
||||
func _make_kind_header(_build: bool) -> Control:
|
||||
match table.kind:
|
||||
RollTable.KIND_CHOICE:
|
||||
var v := _vbox(3)
|
||||
_prompt_label = RichText.label("", 15, Style.INK, true)
|
||||
_prompt_label.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
v.add_child(_prompt_label)
|
||||
var kinds := {"pick": "Pick one", "number": "A number", "text": "Your words"}
|
||||
var info := str(kinds.get(table.choice, ""))
|
||||
if table.choice == "number":
|
||||
info += " · %s to %s" % [table.min_expr, table.max_expr]
|
||||
if table.save_as != "":
|
||||
info += " · saves %s" % table.save_as
|
||||
var l := Style.make_label(info, Style.body(true), 12, Style.MUTED)
|
||||
l.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||
v.add_child(l)
|
||||
return v
|
||||
RollTable.KIND_LOOP:
|
||||
var chip := PanelContainer.new()
|
||||
chip.mouse_filter = MOUSE_FILTER_PASS
|
||||
chip.size_flags_horizontal = SIZE_SHRINK_BEGIN
|
||||
chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(Color(Style.BRASS, 0.16), 6, [8, 1, 8, 2]), 1, Color(Style.BRASS_DARK, 0.35)))
|
||||
var err := Expr.check(table.loop_expr) if table.loop_expr.strip_edges() != "" else "No rule yet"
|
||||
var l := Style.make_label(loop_rule(table), Style.display(true), 16, Style.DANGER_INK if err != "" else Style.COPPER_DARK)
|
||||
l.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
chip.add_child(l)
|
||||
chip.tooltip_text = err
|
||||
return chip
|
||||
RollTable.KIND_VARIABLE:
|
||||
var txt := "@%s · %s" % [table.var_name, table.var_type]
|
||||
var l := Style.make_label(txt, Style.body(true), 12, Style.MUTED)
|
||||
l.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
return l
|
||||
return null
|
||||
|
||||
|
||||
## "× @answer", "while @alive = 1", "until @done".
|
||||
static func loop_rule(t: RollTable) -> String:
|
||||
var e := t.loop_expr.strip_edges()
|
||||
if e == "":
|
||||
e = "?"
|
||||
match t.loop_mode:
|
||||
"while":
|
||||
return "while " + e
|
||||
"until":
|
||||
return "until " + e
|
||||
return "× " + e
|
||||
Style.skin_button(roll, rn, rh, rp, Style.BRASS)
|
||||
_die_icon = DieIcon.new()
|
||||
_die_icon.spinning = _rolling
|
||||
roll.add_child(_die_icon)
|
||||
roll.resized.connect(func() -> void: _die_icon.position = Vector2(8, (roll.size.y - 20.0) / 2.0 - 1.0))
|
||||
roll.pressed.connect(func() -> void: main.start_roll(table.id))
|
||||
row.add_child(roll)
|
||||
if _deck_row != null:
|
||||
head_box.add_child(_deck_row)
|
||||
return header
|
||||
|
||||
|
||||
## Card mode: "4 / 6 left" and a small Reshuffle link under the title.
|
||||
|
|
@ -487,9 +330,6 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
|
|||
row.custom_minimum_size = Vector2(0, 36)
|
||||
var h := _hbox(8)
|
||||
row.add_child(h)
|
||||
# Loop rows and the Answer row of number/text choices are fixed: no number,
|
||||
# weight or delete.
|
||||
var fixed := table.kind == RollTable.KIND_LOOP or (table.kind == RollTable.KIND_CHOICE and table.choice != "pick")
|
||||
|
||||
var num: Label = null
|
||||
if build and ranged:
|
||||
|
|
@ -501,47 +341,50 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
|
|||
r.add_child(_range_edit(e, false))
|
||||
h.add_child(r)
|
||||
else:
|
||||
num = Style.make_label("" if fixed else table.num_label(e, index), Style.display(true), 16, Style.MUTED)
|
||||
num = Style.make_label(table.num_label(e, index), Style.display(true), 16, Style.MUTED)
|
||||
num.custom_minimum_size = Vector2(numw, 0)
|
||||
num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
|
||||
num.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
if fixed:
|
||||
num.text = "↻" if table.kind == RollTable.KIND_LOOP and index == 0 else "→"
|
||||
num.add_theme_font_override("font", Style.body_bold(true))
|
||||
num.add_theme_font_size_override("font_size", 14)
|
||||
h.add_child(num)
|
||||
|
||||
var text: RichTextLabel = null
|
||||
if build:
|
||||
h.add_theme_constant_override("separation", 4)
|
||||
if table.kind == RollTable.KIND_CHOICE and table.choice != "pick":
|
||||
var al := Style.make_label("Answer", Style.body_italic(true), 15, Style.MUTED)
|
||||
al.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
al.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
al.tooltip_text = "Its effects and pipes run after the player answers ({answer} holds the answer)"
|
||||
h.add_child(al)
|
||||
else:
|
||||
var edit := LineEdit.new()
|
||||
edit.text = e.text
|
||||
edit.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
edit.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
edit.custom_minimum_size = Vector2(40, 0)
|
||||
edit.add_theme_font_size_override("font_size", 15)
|
||||
if table.kind == RollTable.KIND_LOOP:
|
||||
edit.placeholder_text = LOOP_ROWS[clampi(index, 0, 1)]
|
||||
edit.tooltip_text = "%s: shown each pass ({i} is the pass number)" % LOOP_ROWS[0] if index == 0 else "%s: runs once when the loop ends" % LOOP_ROWS[1]
|
||||
edit.text_changed.connect(func(s: String) -> void:
|
||||
e.text = s
|
||||
main.mark_dirty()
|
||||
)
|
||||
h.add_child(edit)
|
||||
if not ranged and not fixed:
|
||||
if not ranged:
|
||||
h.add_child(_weight_edit(e))
|
||||
h.add_child(_toggle_button("ƒ", "Effects: statements such as @hp -= 1 that run when this comes up",
|
||||
_open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(e.effects).is_empty()))
|
||||
h.add_child(_toggle_button("i", "Details shown when hovering this result",
|
||||
_open_details, e.id, e.details.strip_edges() != "", false))
|
||||
if not fixed:
|
||||
var info := Button.new()
|
||||
info.text = "i"
|
||||
info.toggle_mode = true
|
||||
info.button_pressed = _open_details.has(e.id)
|
||||
info.tooltip_text = "Details shown when hovering this result"
|
||||
info.custom_minimum_size = Vector2(22, 22)
|
||||
info.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
info.add_theme_font_override("font", Style.body_bold(true))
|
||||
info.add_theme_font_size_override("font_size", 13)
|
||||
var has := e.details.strip_edges() != ""
|
||||
var inn := Style.bordered(Style.box(Color(0, 0, 0, 0), 11), 1, Style.COPPER if has else Style.DASH)
|
||||
var inh := Style.bordered(Style.box(Color("#e6dfcd"), 11), 1, Style.COPPER)
|
||||
var inp := Style.bordered(Style.box(Style.LIT, 11), 1, Style.COPPER)
|
||||
Style.skin_button(info, inn, inh, inp, Style.COPPER if has else Style.MUTED, Style.INK)
|
||||
info.toggled.connect(func(on: bool) -> void:
|
||||
if on:
|
||||
_open_details[e.id] = true
|
||||
else:
|
||||
_open_details.erase(e.id)
|
||||
rebuild()
|
||||
)
|
||||
h.add_child(info)
|
||||
var x := Button.new()
|
||||
x.text = "×"
|
||||
x.tooltip_text = "Delete this result"
|
||||
|
|
@ -552,301 +395,32 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
|
|||
x.pressed.connect(func() -> void: main.delete_entry(table.id, e.id))
|
||||
h.add_child(x)
|
||||
else:
|
||||
var col := _vbox(3)
|
||||
col.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
col.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
text = RichText.label(_row_text(e), 16, Style.INK, true)
|
||||
text.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
text.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
RichText.hook_hover(text, main)
|
||||
col.add_child(text)
|
||||
if e.effects.strip_edges() != "":
|
||||
col.add_child(_effects_chip(e))
|
||||
h.add_child(col)
|
||||
h.add_child(text)
|
||||
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
|
||||
if ranged and table.has_chances():
|
||||
if ranged:
|
||||
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
|
||||
h.add_child(pct)
|
||||
|
||||
rows[e.id] = row
|
||||
_row_parts[e.id] = {"num": num, "text": text, "entry": e, "index": index}
|
||||
_row_parts[e.id] = {"num": num, "text": text, "entry": e}
|
||||
return row
|
||||
|
||||
|
||||
const LOOP_ROWS := ["Each time", "Afterwards"]
|
||||
## Longest effects summary shown on a Play-mode chip.
|
||||
const CHIP_CHARS := 30
|
||||
|
||||
|
||||
## A small round toggle in a Build row ("i" details, "ƒ" effects). `open` is
|
||||
## the dictionary of entry ids whose editor is shown.
|
||||
func _toggle_button(glyph: String, tip: String, open: Dictionary, eid: String, has: bool, bad: bool) -> Button:
|
||||
var b := Button.new()
|
||||
b.text = glyph
|
||||
b.toggle_mode = true
|
||||
b.button_pressed = open.has(eid)
|
||||
b.tooltip_text = tip
|
||||
b.custom_minimum_size = Vector2(22, 22)
|
||||
b.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
b.add_theme_font_override("font", Style.body_bold(true))
|
||||
b.add_theme_font_size_override("font_size", 13)
|
||||
var ring := Style.DANGER_INK if bad else (Style.COPPER if has else Style.DASH)
|
||||
var inn := Style.bordered(Style.box(Color(0, 0, 0, 0), 11), 1, ring)
|
||||
var inh := Style.bordered(Style.box(Color("#e6dfcd"), 11), 1, Style.COPPER)
|
||||
var inp := Style.bordered(Style.box(Style.LIT, 11), 1, Style.COPPER)
|
||||
Style.skin_button(b, inn, inh, inp, ring if (has or bad) else Style.MUTED, Style.INK)
|
||||
b.toggled.connect(func(on: bool) -> void:
|
||||
if on:
|
||||
open[eid] = true
|
||||
else:
|
||||
open.erase(eid)
|
||||
rebuild()
|
||||
)
|
||||
return b
|
||||
|
||||
|
||||
## Play-mode text of a row: the last rolled (expanded) text when the row is
|
||||
## lit, otherwise the entry as written with its references shown readably.
|
||||
## Loop rows read "Each time · …"; a number/text choice's row is its answer.
|
||||
func _row_text(e: TableEntry) -> String:
|
||||
var rolled := main.lit_text(table.id, e.id)
|
||||
var s := RichText.decorate(rolled) if rolled != "" else RichText.preview(e.text, main.data)
|
||||
var muted := Style.MUTED.to_html(false)
|
||||
if table.kind == RollTable.KIND_LOOP:
|
||||
var index := table.entries.find(e)
|
||||
var cap: String = LOOP_ROWS[clampi(index, 0, 1)]
|
||||
var plain_text := Formatter.strip_tags(e.text).strip_edges()
|
||||
if plain_text == "" or plain_text == cap:
|
||||
s = "[b]%s[/b]" % cap
|
||||
else:
|
||||
s = "[color=#%s]%s ·[/color] %s" % [muted, cap, s]
|
||||
elif table.kind == RollTable.KIND_CHOICE and table.choice != "pick":
|
||||
if rolled != "":
|
||||
s = "[color=#%s]Answer ·[/color] [b]%s[/b]" % [muted, RichText.decorate(rolled)]
|
||||
else:
|
||||
s = "[i][color=#%s]Answer[/color][/i]" % muted
|
||||
if e.details.strip_edges() != "":
|
||||
s += RichText.info_mark()
|
||||
return s
|
||||
|
||||
|
||||
## Play mode: a subtle brass chip summarising an entry's effects ("STR = 2d6").
|
||||
func _effects_chip(e: TableEntry) -> Control:
|
||||
var bad := not Effects.validate(e.effects).is_empty()
|
||||
var chip := PanelContainer.new()
|
||||
chip.mouse_filter = MOUSE_FILTER_PASS
|
||||
chip.size_flags_horizontal = SIZE_SHRINK_BEGIN
|
||||
var bg := Color(Style.DANGER_INK, 0.1) if bad else Color(Style.BRASS, 0.2)
|
||||
var line := Color(Style.DANGER_INK, 0.4) if bad else Color(Style.BRASS_DARK, 0.3)
|
||||
chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(bg, 5, [6, 0, 6, 1]), 1, line))
|
||||
var summary := effect_summary(e.effects, main.data)
|
||||
# Cut long summaries by hand: a clipped Label would collapse to nothing.
|
||||
if summary.length() > CHIP_CHARS:
|
||||
summary = summary.substr(0, CHIP_CHARS - 1).strip_edges() + "…"
|
||||
var l := Style.make_label(summary, Style.body(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK)
|
||||
l.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
chip.add_child(l)
|
||||
chip.tooltip_text = "\n".join(Effects.split(e.effects))
|
||||
return chip
|
||||
|
||||
|
||||
## A short summary of effect text: the first two statements, with declared
|
||||
## variables by their card's name ("STR = 2d6 · Terms += 1 · +3").
|
||||
static func effect_summary(text: String, board: TowerBoard) -> String:
|
||||
var list := Effects.split(text)
|
||||
var parts := PackedStringArray()
|
||||
for k in mini(2, list.size()):
|
||||
var st := Effects.parse_statement(list[k])
|
||||
if st.has("error"):
|
||||
parts.append("⚠ " + list[k])
|
||||
continue
|
||||
var target: String = st["target"]
|
||||
var shown := target
|
||||
if board != null and target.begins_with("@") and not target.ends_with("*"):
|
||||
for t in board.tables:
|
||||
if t.kind == RollTable.KIND_VARIABLE and t.var_name == target.substr(1):
|
||||
shown = Formatter.strip_tags(t.name).strip_edges()
|
||||
break
|
||||
if st["op"] == "reset":
|
||||
parts.append("reset " + shown)
|
||||
else:
|
||||
parts.append("%s %s %s" % [shown, st["op"], st["expr"]])
|
||||
if list.size() > 2:
|
||||
parts.append("+%d" % (list.size() - 2))
|
||||
return " · ".join(parts)
|
||||
|
||||
|
||||
## Build mode: the effects editor under a row, validated as you type.
|
||||
func _effects_editor(e: TableEntry, left: float) -> Control:
|
||||
var wrap := MarginContainer.new()
|
||||
wrap.mouse_filter = MOUSE_FILTER_PASS
|
||||
wrap.add_theme_constant_override("margin_left", int(left))
|
||||
wrap.add_theme_constant_override("margin_right", 12)
|
||||
wrap.add_theme_constant_override("margin_top", 2)
|
||||
wrap.add_theme_constant_override("margin_bottom", 6)
|
||||
var v := _vbox(3)
|
||||
wrap.add_child(v)
|
||||
var te := TextEdit.new()
|
||||
te.text = e.effects
|
||||
te.placeholder_text = "@hp -= 1\n@gold += 2d6\nreset @loot"
|
||||
te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
|
||||
te.custom_minimum_size = Vector2(0, 58)
|
||||
te.scroll_fit_content_height = true
|
||||
te.add_theme_font_override("font", Style.body(true))
|
||||
te.add_theme_font_size_override("font_size", 13)
|
||||
te.add_theme_color_override("font_color", Style.INK)
|
||||
te.add_theme_color_override("font_placeholder_color", Style.MUTED)
|
||||
te.add_theme_color_override("caret_color", Style.INK)
|
||||
te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
|
||||
var ok_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 4, 7, 4]), 1, Color(Style.BRASS_DARK, 0.4))
|
||||
var focus_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 4, 7, 4]), 1, Style.COPPER)
|
||||
var bad_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 4, 7, 4]), 1, Style.DANGER_INK)
|
||||
v.add_child(te)
|
||||
var msg := Style.make_label("", Style.body(true), 12, Style.DANGER_INK)
|
||||
msg.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||
v.add_child(msg)
|
||||
var check := func() -> void:
|
||||
var problems := Effects.validate(te.text)
|
||||
var lines := PackedStringArray()
|
||||
for p: Dictionary in problems:
|
||||
lines.append("⚠ %s: %s" % [p["src"], p["error"]])
|
||||
msg.text = "\n".join(lines)
|
||||
msg.visible = not lines.is_empty()
|
||||
te.add_theme_stylebox_override("normal", bad_box if not lines.is_empty() else ok_box)
|
||||
te.add_theme_stylebox_override("focus", bad_box if not lines.is_empty() else focus_box)
|
||||
te.text_changed.connect(func() -> void:
|
||||
e.effects = te.text
|
||||
check.call()
|
||||
main.mark_dirty()
|
||||
)
|
||||
check.call()
|
||||
return wrap
|
||||
|
||||
|
||||
## A sheet card's one row: the rendered template in Play, its editor in Build.
|
||||
func _make_sheet_row(e: TableEntry, build: bool) -> Control:
|
||||
var row := PanelContainer.new()
|
||||
row.mouse_filter = MOUSE_FILTER_PASS
|
||||
row.custom_minimum_size = Vector2(0, 36)
|
||||
var v := _vbox(6)
|
||||
row.add_child(v)
|
||||
if build:
|
||||
var te := TextEdit.new()
|
||||
te.text = e.text
|
||||
te.placeholder_text = "[b]Name[/b] {@name}\nHP {@hp} · Skills {@skill_*}"
|
||||
te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
|
||||
te.custom_minimum_size = Vector2(0, 90)
|
||||
te.scroll_fit_content_height = true
|
||||
te.add_theme_font_override("font", Style.body(true))
|
||||
te.add_theme_font_size_override("font_size", 14)
|
||||
te.add_theme_color_override("font_color", Style.INK)
|
||||
te.add_theme_color_override("font_placeholder_color", Style.MUTED)
|
||||
te.add_theme_color_override("caret_color", Style.INK)
|
||||
te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
|
||||
te.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.RULE))
|
||||
te.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.COPPER))
|
||||
te.tooltip_text = "The sheet's template: BBCode with {@var}, {@prefix_*} and {= expr}"
|
||||
te.text_changed.connect(func() -> void:
|
||||
e.text = te.text
|
||||
main.mark_dirty()
|
||||
)
|
||||
v.add_child(te)
|
||||
var tools := _hbox(4)
|
||||
tools.add_child(_toggle_button("ƒ", "Effects that run when the chain reaches this sheet",
|
||||
_open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(e.effects).is_empty()))
|
||||
tools.add_child(_toggle_button("i", "Details shown when hovering the sheet",
|
||||
_open_details, e.id, e.details.strip_edges() != "", false))
|
||||
var pv := Style.make_label("Preview on the board in Play", Style.body_italic(true), 12, Style.MUTED)
|
||||
pv.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
tools.add_child(pv)
|
||||
v.add_child(tools)
|
||||
_sheet_label = null
|
||||
else:
|
||||
_sheet_label = RichText.label("", 15, Style.INK, true)
|
||||
_sheet_label.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
RichText.hook_hover(_sheet_label, main)
|
||||
v.add_child(_sheet_label)
|
||||
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
|
||||
rows[e.id] = row
|
||||
_row_parts[e.id] = {"num": null, "text": null, "entry": e, "index": 0}
|
||||
return row
|
||||
|
||||
|
||||
## A variable card's body: its live value, big, and in Build its starting value
|
||||
## and a reset button.
|
||||
func _make_variable_body(build: bool) -> Control:
|
||||
var wrap := MarginContainer.new()
|
||||
wrap.mouse_filter = MOUSE_FILTER_PASS
|
||||
wrap.add_theme_constant_override("margin_left", 14)
|
||||
wrap.add_theme_constant_override("margin_right", 12)
|
||||
wrap.add_theme_constant_override("margin_top", 6)
|
||||
wrap.add_theme_constant_override("margin_bottom", 10)
|
||||
var v := _vbox(2)
|
||||
wrap.add_child(v)
|
||||
_var_value = Style.make_label("", Style.display(true), 34, Style.INK)
|
||||
_var_value.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||
_var_value.mouse_filter = MOUSE_FILTER_PASS
|
||||
v.add_child(_var_value)
|
||||
_var_hint = Style.make_label("", Style.body(true), 12, Style.MUTED)
|
||||
_var_hint.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||
_var_hint.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
v.add_child(_var_hint)
|
||||
if build:
|
||||
var h := _hbox(8)
|
||||
var start := Style.make_label("Starts at %s" % (table.initial if table.initial.strip_edges() != "" else ("0" if table.var_type == "number" else "nothing")),
|
||||
Style.body(true), 12, Style.MUTED)
|
||||
start.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
start.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
h.add_child(start)
|
||||
var reset := Button.new()
|
||||
reset.text = "↺ Reset"
|
||||
reset.tooltip_text = "Set @%s back to its starting value" % table.var_name
|
||||
reset.add_theme_font_override("font", Style.body(true))
|
||||
reset.add_theme_font_size_override("font_size", 12)
|
||||
var n := Style.box(Color(0, 0, 0, 0), 5, [5, 0, 5, 1])
|
||||
var hv := Style.box(Color("#e6dfcd"), 5, [5, 0, 5, 1])
|
||||
Style.skin_button(reset, n, hv, hv, Style.COPPER, Style.INK)
|
||||
reset.pressed.connect(func() -> void: main.reset_variable(table.var_name))
|
||||
h.add_child(reset)
|
||||
v.add_child(h)
|
||||
return wrap
|
||||
|
||||
|
||||
## Re-renders the live parts (a variable's value, a sheet, a choice's
|
||||
## question) from the current variables. Only touches labels whose text
|
||||
## changed. Main calls it after rolls and edits, never per frame.
|
||||
func refresh_live() -> void:
|
||||
if is_instance_valid(_var_value):
|
||||
var d := Roller.variable_display(main.data, main.persistent_vars, table)
|
||||
var shown := str(d["text"]) if str(d["text"]) != "" else "—"
|
||||
if _var_value.text != shown:
|
||||
_var_value.text = shown
|
||||
var size_px := 34 if shown.length() <= 8 else (24 if shown.length() <= 18 else 17)
|
||||
_var_value.add_theme_font_size_override("font_size", size_px)
|
||||
_var_value.add_theme_color_override("font_color", Style.INK if d["set"] else Style.MUTED)
|
||||
var hint := ""
|
||||
if str(d["error"]) != "":
|
||||
hint = "⚠ " + str(d["error"])
|
||||
elif not d["set"]:
|
||||
hint = "Not set yet · starts at this"
|
||||
_var_hint.text = hint
|
||||
_var_hint.add_theme_color_override("font_color", Style.DANGER_INK if str(d["error"]) != "" else Style.MUTED)
|
||||
_var_hint.visible = hint != ""
|
||||
if is_instance_valid(_sheet_label):
|
||||
var s := RichText.decorate(Roller.render_sheet(main.data, main.persistent_vars, table))
|
||||
if _sheet_label.text != s:
|
||||
_sheet_label.text = s
|
||||
if is_instance_valid(_prompt_label):
|
||||
var p: String
|
||||
if main.mode == Main.Mode.BUILD:
|
||||
p = RichText.preview(table.prompt, main.data)
|
||||
else:
|
||||
p = RichText.decorate(TextExpander.render(table.prompt, Roller.live_context(main.data, main.persistent_vars)))
|
||||
if _prompt_label.text != p:
|
||||
_prompt_label.text = p
|
||||
_prompt_label.visible = table.prompt.strip_edges() != ""
|
||||
|
||||
|
||||
## Weight on a plain table, shown as ×N. Also the number of copies in card mode.
|
||||
func _weight_edit(e: TableEntry) -> LineEdit:
|
||||
var edit := LineEdit.new()
|
||||
|
|
@ -997,10 +571,7 @@ func _make_footer(ranged: bool) -> Control:
|
|||
wrap.add_theme_constant_override("margin_bottom", 10)
|
||||
var h := _hbox(8)
|
||||
wrap.add_child(h)
|
||||
# Loops, sheets, variables and number/text choices have fixed rows.
|
||||
if table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and table.choice == "pick"):
|
||||
var label := "+ Add range" if ranged else ("+ Add option" if table.kind == RollTable.KIND_CHOICE else "+ Add result")
|
||||
var add := _footer_button(label, Style.INK)
|
||||
var add := _footer_button("+ Add range" if ranged else "+ Add result", Style.INK)
|
||||
add.pressed.connect(func() -> void: main.add_entry(table.id))
|
||||
h.add_child(add)
|
||||
var det := _footer_button("Details", Style.INK)
|
||||
|
|
@ -1123,7 +694,7 @@ func set_more_text(text: String) -> void:
|
|||
## Updates highlights after a roll. Collapsed cards rebuild so the rolled result shows.
|
||||
func refresh_lit() -> void:
|
||||
update_deck()
|
||||
if is_collapsed():
|
||||
if table.collapsed:
|
||||
var want: Array = []
|
||||
for e in table.entries:
|
||||
if main.is_entry_lit(table.id, e.id):
|
||||
|
|
|
|||
|
|
@ -29,53 +29,13 @@ var _ranged := false
|
|||
var _card_mode := false
|
||||
var _deck_empty := "reshuffle"
|
||||
|
||||
# Logic-card fields (docs/LOGIC.md), shown for the matching kind.
|
||||
var _type_box: Control
|
||||
var _card_box: Control
|
||||
var _kind_problem: Label
|
||||
var _choice := "pick"
|
||||
var _choice_note: Label
|
||||
var _prompt: LineEdit
|
||||
var _save_as: LineEdit
|
||||
var _min: LineEdit
|
||||
var _max: LineEdit
|
||||
var _minmax_row: Control
|
||||
var _loop_mode := "times"
|
||||
var _loop_expr: LineEdit
|
||||
var _loop_note: Label
|
||||
var _var_name: LineEdit
|
||||
var _var_type := "number"
|
||||
var _initial: LineEdit
|
||||
var _template: TextEdit
|
||||
var _template_preview: RichTextLabel
|
||||
|
||||
const TITLES := {
|
||||
RollTable.KIND_ROLL: "Table settings",
|
||||
RollTable.KIND_CHOICE: "Choice settings",
|
||||
RollTable.KIND_LOOP: "Loop settings",
|
||||
RollTable.KIND_VARIABLE: "Variable settings",
|
||||
RollTable.KIND_SHEET: "Sheet settings",
|
||||
}
|
||||
const CHOICE_LABELS := ["Which option", "How many", "Open ended"]
|
||||
const LOOP_LABELS := ["Times", "While", "Until"]
|
||||
const LOOP_NOTES := {
|
||||
"times": "Runs Each time this many times (worked out once), then Afterwards. e.g. 3, @answer, 1d3",
|
||||
"while": "Checks the condition before each pass and stops when it's false. e.g. @hp > 0",
|
||||
"until": "Runs a pass, then stops once the condition is true (at least one pass). e.g. @gold >= 100",
|
||||
}
|
||||
const SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$"
|
||||
const VAR_PATTERN := "^[a-z0-9_]+$"
|
||||
|
||||
|
||||
func _init(p_table: RollTable = null) -> void:
|
||||
super._init(TITLES.get(p_table.kind, "Table settings") if p_table else "Table settings", 560.0)
|
||||
super._init("Table settings", 560.0)
|
||||
table = p_table
|
||||
_ranged = table.is_ranged()
|
||||
_card_mode = table.card_mode
|
||||
_deck_empty = table.deck_empty
|
||||
_choice = table.choice
|
||||
_loop_mode = table.loop_mode
|
||||
_var_type = table.var_type
|
||||
_build()
|
||||
|
||||
|
||||
|
|
@ -86,7 +46,6 @@ func _build() -> void:
|
|||
style_line_edit(_name)
|
||||
_name.text_changed.connect(func(_t: String) -> void: _refresh())
|
||||
body.add_child(field("Name", _name))
|
||||
_build_kind()
|
||||
|
||||
_details = TextEdit.new()
|
||||
_details.text = table.details
|
||||
|
|
@ -155,7 +114,6 @@ func _build() -> void:
|
|||
_problem = note("", Style.WARN_INK)
|
||||
type_box.add_child(_problem)
|
||||
body.add_child(type_box)
|
||||
_type_box = type_box
|
||||
|
||||
var card_box := VBoxContainer.new()
|
||||
card_box.add_theme_constant_override("separation", 6)
|
||||
|
|
@ -175,19 +133,12 @@ func _build() -> void:
|
|||
_deck_block = deck
|
||||
card_box.add_child(deck)
|
||||
body.add_child(card_box)
|
||||
_card_box = card_box
|
||||
|
||||
add_button("Close", "plain", close)
|
||||
add_button("Apply", "primary", _on_apply)
|
||||
_refresh()
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
super._ready()
|
||||
# Now that the dialog sits in Main, the sheet preview can use its variables.
|
||||
_refresh()
|
||||
|
||||
|
||||
func _tool_button(text: String, tip: String, on_press: Callable) -> Button:
|
||||
var b := make_button(text, "plain")
|
||||
b.tooltip_text = tip
|
||||
|
|
@ -244,179 +195,11 @@ func _set_caret_at_offset(off: int) -> void:
|
|||
|
||||
|
||||
func settings() -> Dictionary:
|
||||
var s := {
|
||||
return {
|
||||
"name": _name.text, "details": _details.text, "tags": _tags.text,
|
||||
"ranged": _ranged, "dice": _dice.text.strip_edges(),
|
||||
"card_mode": _card_mode, "deck_empty": _deck_empty,
|
||||
}
|
||||
match table.kind:
|
||||
RollTable.KIND_CHOICE:
|
||||
s["choice"] = _choice
|
||||
s["prompt"] = _prompt.text
|
||||
s["save_as"] = _save_as.text.strip_edges()
|
||||
s["min"] = _min.text.strip_edges()
|
||||
s["max"] = _max.text.strip_edges()
|
||||
RollTable.KIND_LOOP:
|
||||
s["loop_mode"] = _loop_mode
|
||||
s["loop_expr"] = _loop_expr.text.strip_edges()
|
||||
RollTable.KIND_VARIABLE:
|
||||
s["var_name"] = _var_name.text.strip_edges().trim_prefix("@")
|
||||
s["var_type"] = _var_type
|
||||
s["initial"] = _initial.text.strip_edges()
|
||||
RollTable.KIND_SHEET:
|
||||
s["template"] = _template.text
|
||||
return s
|
||||
|
||||
|
||||
# ---------- Kind-specific fields ----------
|
||||
|
||||
func _build_kind() -> void:
|
||||
var box := VBoxContainer.new()
|
||||
box.add_theme_constant_override("separation", 10)
|
||||
match table.kind:
|
||||
RollTable.KIND_CHOICE:
|
||||
box.add_child(section("Question type"))
|
||||
box.add_child(segmented(CHOICE_LABELS, RollTable.CHOICES.find(_choice), func(i: int) -> void:
|
||||
_choice = RollTable.CHOICES[i]
|
||||
_refresh()
|
||||
))
|
||||
_choice_note = note("")
|
||||
box.add_child(_choice_note)
|
||||
_prompt = LineEdit.new()
|
||||
_prompt.text = table.prompt
|
||||
_prompt.placeholder_text = "Which way out? You have {@gold} gold."
|
||||
style_line_edit(_prompt)
|
||||
_prompt.text_changed.connect(func(_t: String) -> void: _refresh())
|
||||
box.add_child(field("Question (BBCode, {@var} works)", _prompt))
|
||||
_save_as = LineEdit.new()
|
||||
_save_as.text = table.save_as
|
||||
_save_as.placeholder_text = "@name to keep, or a name for this roll"
|
||||
style_line_edit(_save_as)
|
||||
_save_as.text_changed.connect(func(_t: String) -> void: _refresh())
|
||||
box.add_child(field("Save the answer as (optional)", _save_as))
|
||||
var mm := HBoxContainer.new()
|
||||
mm.add_theme_constant_override("separation", 12)
|
||||
_min = LineEdit.new()
|
||||
_min.text = table.min_expr
|
||||
style_line_edit(_min)
|
||||
_min.text_changed.connect(func(_t: String) -> void: _refresh())
|
||||
_max = LineEdit.new()
|
||||
_max.text = table.max_expr
|
||||
style_line_edit(_max)
|
||||
_max.text_changed.connect(func(_t: String) -> void: _refresh())
|
||||
mm.add_child(field("Lowest", _min))
|
||||
mm.add_child(field("Highest", _max))
|
||||
for c in mm.get_children():
|
||||
(c as Control).size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
_minmax_row = mm
|
||||
box.add_child(mm)
|
||||
RollTable.KIND_LOOP:
|
||||
box.add_child(section("Repeat"))
|
||||
box.add_child(segmented(LOOP_LABELS, RollTable.LOOPS.find(_loop_mode), func(i: int) -> void:
|
||||
_loop_mode = RollTable.LOOPS[i]
|
||||
_refresh()
|
||||
))
|
||||
_loop_expr = LineEdit.new()
|
||||
_loop_expr.text = table.loop_expr
|
||||
style_line_edit(_loop_expr)
|
||||
_loop_expr.text_changed.connect(func(_t: String) -> void: _refresh())
|
||||
box.add_child(field("How many times / condition", _loop_expr))
|
||||
_loop_note = note("")
|
||||
box.add_child(_loop_note)
|
||||
RollTable.KIND_VARIABLE:
|
||||
_var_name = LineEdit.new()
|
||||
_var_name.text = table.var_name
|
||||
_var_name.placeholder_text = "hp"
|
||||
style_line_edit(_var_name)
|
||||
_var_name.text_changed.connect(func(_t: String) -> void: _refresh())
|
||||
box.add_child(field("Variable name (used as @name)", _var_name))
|
||||
box.add_child(section("Type"))
|
||||
box.add_child(segmented(["Number", "Text", "List"], RollTable.VAR_TYPES.find(_var_type), func(i: int) -> void:
|
||||
_var_type = RollTable.VAR_TYPES[i]
|
||||
_refresh()
|
||||
))
|
||||
_initial = LineEdit.new()
|
||||
_initial.text = table.initial
|
||||
_initial.placeholder_text = "10, 2d6, or a word"
|
||||
style_line_edit(_initial)
|
||||
_initial.text_changed.connect(func(_t: String) -> void: _refresh())
|
||||
box.add_child(field("Starting value", _initial))
|
||||
box.add_child(note("reset @name, and Reset in the Variables tab, put it back to this."))
|
||||
RollTable.KIND_SHEET:
|
||||
_template = TextEdit.new()
|
||||
_template.text = table.entries[0].text if not table.entries.is_empty() else ""
|
||||
_template.placeholder_text = "[b]{@name}[/b]\nHP {@hp} · Gold {@gold}\nSkills: {@skill_*}"
|
||||
_template.custom_minimum_size.y = 120
|
||||
_template.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
|
||||
style_text_edit(_template)
|
||||
_template.text_changed.connect(_refresh)
|
||||
box.add_child(field("Template (BBCode with {@var}, {@prefix_*} and {= expr})", _template))
|
||||
_template_preview = RichTextLabel.new()
|
||||
_template_preview.bbcode_enabled = true
|
||||
_template_preview.fit_content = true
|
||||
_template_preview.scroll_active = false
|
||||
var pbox := PanelContainer.new()
|
||||
pbox.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.05), 7, [10, 7, 10, 7]))
|
||||
pbox.add_child(_template_preview)
|
||||
box.add_child(pbox)
|
||||
_:
|
||||
return
|
||||
_kind_problem = note("", Style.DANGER_INK)
|
||||
box.add_child(_kind_problem)
|
||||
body.add_child(box)
|
||||
|
||||
|
||||
func _refresh_kind() -> void:
|
||||
var s := settings()
|
||||
var problems := kind_problems(table, s)
|
||||
if _kind_problem:
|
||||
_kind_problem.text = "\n".join(problems)
|
||||
_kind_problem.visible = not problems.is_empty()
|
||||
match table.kind:
|
||||
RollTable.KIND_CHOICE:
|
||||
_minmax_row.visible = _choice == "number"
|
||||
var msg := ""
|
||||
if _choice != table.choice and table.choice == "pick":
|
||||
msg = "Only the first option is kept, as the Answer row (its effects and pipes stay)."
|
||||
elif _choice != table.choice and _choice == "pick":
|
||||
msg = "The Answer row becomes the first option; two more are added."
|
||||
elif _choice == "pick":
|
||||
msg = "The player picks one of the card's options, or Random."
|
||||
else:
|
||||
msg = "The answer goes in {answer}; the Answer row's effects and pipes run after it."
|
||||
_choice_note.text = msg
|
||||
_mark(_save_as, s["save_as"] == "" or _re(SAVE_PATTERN).search(s["save_as"]) != null)
|
||||
_mark(_min, Expr.check(s["min"]) == "" and s["min"] != "")
|
||||
_mark(_max, Expr.check(s["max"]) == "" and s["max"] != "")
|
||||
RollTable.KIND_LOOP:
|
||||
_loop_note.text = LOOP_NOTES.get(_loop_mode, "")
|
||||
_mark(_loop_expr, s["loop_expr"] != "" and Expr.check(s["loop_expr"]) == "")
|
||||
RollTable.KIND_VARIABLE:
|
||||
_mark(_var_name, _re(VAR_PATTERN).search(s["var_name"]) != null)
|
||||
_mark(_initial, _initial_error(s["initial"], _var_type) == "")
|
||||
RollTable.KIND_SHEET:
|
||||
var ctx := Roller.live_context(table_board(), _live_vars())
|
||||
_template_preview.text = RichText.decorate(TextExpander.render(_template.text, ctx)) if _template.text.strip_edges() != "" \
|
||||
else "[color=#69726b]Preview appears here.[/color]"
|
||||
# The ranged/card-mode sections only apply to roll tables and pick choices.
|
||||
var rolls := table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and _choice == "pick")
|
||||
_type_box.visible = rolls
|
||||
_card_box.visible = rolls
|
||||
|
||||
|
||||
func _mark(le: LineEdit, ok: bool) -> void:
|
||||
le.add_theme_color_override("font_color", Style.INK if ok else Style.DANGER_INK)
|
||||
|
||||
|
||||
## The board and variables for the sheet preview, when the dialog sits in Main.
|
||||
func table_board() -> TowerBoard:
|
||||
var m := get_parent() as Main
|
||||
return m.data if m else TowerBoard.new()
|
||||
|
||||
|
||||
func _live_vars() -> Dictionary:
|
||||
var m := get_parent() as Main
|
||||
return m.persistent_vars if m else {}
|
||||
|
||||
|
||||
func _refresh() -> void:
|
||||
|
|
@ -427,7 +210,7 @@ func _refresh() -> void:
|
|||
_dice_row.visible = _ranged
|
||||
_deck_block.visible = _card_mode
|
||||
var s := settings()
|
||||
var dice_ok := not _ranged or dice_ok_text(s["dice"])
|
||||
var dice_ok := not _ranged or Dice.is_valid_text(s["dice"])
|
||||
_dice.add_theme_color_override("font_color", Style.INK if dice_ok else Style.WARN_INK)
|
||||
var msgs := PackedStringArray()
|
||||
if _ranged and not table.is_ranged():
|
||||
|
|
@ -441,14 +224,12 @@ func _refresh() -> void:
|
|||
var problem := ""
|
||||
if not dice_ok:
|
||||
problem = "“%s” is not a valid dice expression." % s["dice"]
|
||||
elif _type_box == null or _type_box.visible:
|
||||
else:
|
||||
var clone := RollTable.from_dict(table.to_dict())
|
||||
apply_settings(clone, s)
|
||||
problem = clone.range_problems()
|
||||
_problem.text = problem
|
||||
_problem.visible = problem != ""
|
||||
if _type_box != null:
|
||||
_refresh_kind()
|
||||
if is_inside_tree():
|
||||
_fit()
|
||||
|
||||
|
|
@ -457,10 +238,6 @@ func _on_apply() -> void:
|
|||
var s := settings()
|
||||
var r := apply_settings(table, s)
|
||||
if not r["ok"]:
|
||||
if _kind_problem and not kind_problems(table, s).is_empty():
|
||||
_kind_problem.text = r["error"]
|
||||
_kind_problem.visible = true
|
||||
else:
|
||||
_problem.text = r["error"]
|
||||
_problem.visible = true
|
||||
return
|
||||
|
|
@ -468,106 +245,6 @@ func _on_apply() -> void:
|
|||
close()
|
||||
|
||||
|
||||
## Problems with the kind-specific settings (empty when fine).
|
||||
static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray:
|
||||
var out := PackedStringArray()
|
||||
match t.kind:
|
||||
RollTable.KIND_CHOICE:
|
||||
var save := str(s.get("save_as", t.save_as)).strip_edges()
|
||||
if save != "" and _re(SAVE_PATTERN).search(save) == null:
|
||||
out.append("Save as: use a name like career, or @career to keep it.")
|
||||
if str(s.get("choice", t.choice)) == "number":
|
||||
for k in [["min", "Lowest"], ["max", "Highest"]]:
|
||||
var src := str(s.get(k[0], "")).strip_edges()
|
||||
var err := Expr.check(src) if src != "" else "it's empty"
|
||||
if err != "":
|
||||
out.append("%s: %s" % [k[1], err])
|
||||
RollTable.KIND_LOOP:
|
||||
var src := str(s.get("loop_expr", t.loop_expr)).strip_edges()
|
||||
if src == "":
|
||||
out.append("The loop needs a count or a condition.")
|
||||
elif Expr.check(src) != "":
|
||||
out.append("Loop rule: " + Expr.check(src))
|
||||
RollTable.KIND_VARIABLE:
|
||||
var n := str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@")
|
||||
if _re(VAR_PATTERN).search(n) == null:
|
||||
out.append("Variable name: lowercase letters, digits and _ only.")
|
||||
var err := _initial_error(str(s.get("initial", t.initial)), str(s.get("var_type", t.var_type)))
|
||||
if err != "":
|
||||
out.append("Starting value: " + err)
|
||||
return out
|
||||
|
||||
|
||||
static func _initial_error(src: String, type: String) -> String:
|
||||
src = src.strip_edges()
|
||||
if src == "":
|
||||
return ""
|
||||
if type != "number" and RollTable._looks_literal(src):
|
||||
return ""
|
||||
return Expr.check(src)
|
||||
|
||||
|
||||
static func _re(pattern: String) -> RegEx:
|
||||
return RegEx.create_from_string(pattern)
|
||||
|
||||
|
||||
## Dice text for a ranged table: plain dice (2d6) or an expression that uses a
|
||||
## variable, dice or a function ("2d6 + dm(@end)", "@terms"). A lone word
|
||||
## such as "banana" is not accepted.
|
||||
static func dice_ok_text(text: String) -> bool:
|
||||
var s := text.strip_edges()
|
||||
if Dice.is_valid_text(s):
|
||||
return true
|
||||
if s == "" or Expr.check(s) != "":
|
||||
return false
|
||||
return _re("^[A-Za-z_][A-Za-z0-9_]*$").search(s) == null
|
||||
|
||||
|
||||
## Applies the kind-specific settings. Turning a pick choice into a number or
|
||||
## text one keeps only its first entry (as the Answer); the other way, the
|
||||
## Answer becomes the first of three options.
|
||||
static func _apply_kind(t: RollTable, s: Dictionary) -> void:
|
||||
match t.kind:
|
||||
RollTable.KIND_CHOICE:
|
||||
var c := str(s.get("choice", t.choice))
|
||||
if RollTable.CHOICES.has(c) and c != t.choice:
|
||||
if c == "pick":
|
||||
if not t.entries.is_empty():
|
||||
t.entries[0].text = "Option 1"
|
||||
for n in range(t.entries.size() + 1, 4):
|
||||
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Option %d" % n))
|
||||
else:
|
||||
while t.entries.size() > 1:
|
||||
t.entries.remove_at(t.entries.size() - 1)
|
||||
if t.entries.is_empty():
|
||||
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Answer"))
|
||||
t.entries[0].text = "Answer"
|
||||
t.entries[0].has_range = false
|
||||
t.card_mode = false
|
||||
t.choice = c
|
||||
t.prompt = str(s.get("prompt", t.prompt))
|
||||
t.save_as = str(s.get("save_as", t.save_as)).strip_edges()
|
||||
if t.choice == "number":
|
||||
t.min_expr = str(s.get("min", t.min_expr)).strip_edges()
|
||||
t.max_expr = str(s.get("max", t.max_expr)).strip_edges()
|
||||
RollTable.KIND_LOOP:
|
||||
var m := str(s.get("loop_mode", t.loop_mode))
|
||||
if RollTable.LOOPS.has(m):
|
||||
t.loop_mode = m
|
||||
t.loop_expr = str(s.get("loop_expr", t.loop_expr)).strip_edges()
|
||||
RollTable.KIND_VARIABLE:
|
||||
t.var_name = str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@")
|
||||
var vt := str(s.get("var_type", t.var_type))
|
||||
if RollTable.VAR_TYPES.has(vt):
|
||||
t.var_type = vt
|
||||
t.initial = str(s.get("initial", t.initial)).strip_edges()
|
||||
RollTable.KIND_SHEET:
|
||||
if s.has("template"):
|
||||
if t.entries.is_empty():
|
||||
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), ""))
|
||||
t.entries[0].text = str(s["template"])
|
||||
|
||||
|
||||
# ---------- Pure editing logic ----------
|
||||
|
||||
## Wraps text[sel.x:sel.y] in open/close_tag. With an empty range, inserts the
|
||||
|
|
@ -604,17 +281,9 @@ static func extra_pipe_count(t: RollTable) -> int:
|
|||
## expression nothing is changed. deck_reset says the card deck no longer fits
|
||||
## (type, dice or card mode changed), so a saved deck should be cleared.
|
||||
static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary:
|
||||
var problems := kind_problems(t, s)
|
||||
if not problems.is_empty():
|
||||
return {"ok": false, "error": "\n".join(problems), "deck_reset": false}
|
||||
var ranged: bool = s.get("ranged", false)
|
||||
# Only roll tables and pick choices can be ranged or dealt as cards.
|
||||
var choice := str(s.get("choice", t.choice))
|
||||
var rolls := t.kind == RollTable.KIND_ROLL or (t.kind == RollTable.KIND_CHOICE and choice == "pick")
|
||||
if not rolls:
|
||||
ranged = false
|
||||
var dice := str(s.get("dice", t.dice)).strip_edges()
|
||||
if ranged and not dice_ok_text(dice):
|
||||
if ranged and not Dice.is_valid_text(dice):
|
||||
return {"ok": false, "error": "“%s” is not a valid dice expression." % dice, "deck_reset": false}
|
||||
var was_ranged := t.is_ranged()
|
||||
var old_dice := t.dice
|
||||
|
|
@ -624,7 +293,7 @@ static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary:
|
|||
t.name = new_name
|
||||
t.details = str(s.get("details", t.details))
|
||||
t.tags = parse_tags(str(s.get("tags", "")))
|
||||
t.card_mode = bool(s.get("card_mode", t.card_mode)) and rolls
|
||||
t.card_mode = bool(s.get("card_mode", t.card_mode))
|
||||
t.deck_empty = "stop" if str(s.get("deck_empty", t.deck_empty)) == "stop" else "reshuffle"
|
||||
if ranged:
|
||||
t.dice = dice
|
||||
|
|
@ -632,7 +301,6 @@ static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary:
|
|||
assign_ranges(t)
|
||||
elif was_ranged:
|
||||
drop_ranges(t)
|
||||
_apply_kind(t, s)
|
||||
var deck_reset := was_ranged != ranged or old_card != t.card_mode or (ranged and old_dice != t.dice)
|
||||
return {"ok": true, "error": "", "deck_reset": deck_reset}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,24 +1,20 @@
|
|||
class_name VariablesPanel
|
||||
extends VBoxContainer
|
||||
## The Variables tab of the result tray: every board variable ({@name}) — the
|
||||
## ones that are set and the ones variable cards declare — each editable, and
|
||||
## clearable or resettable. Text a roll table gave can be re-rolled from that
|
||||
## table. "Reset all…" puts everything back to its starting value after an
|
||||
## in-app confirmation. Below them, the last roll's chain variables (read
|
||||
## only).
|
||||
## The Variables tab of the result tray: the collection's persistent variables
|
||||
## ({@name}), each editable, re-rollable from the table that set it, or
|
||||
## clearable, and below them the last roll's chain variables (read only).
|
||||
|
||||
const HEIGHT := 112.0
|
||||
const HEIGHT := 132.0
|
||||
|
||||
var main: Main
|
||||
var _list: VBoxContainer
|
||||
var _reset_all: Button
|
||||
var _field: StyleBoxFlat
|
||||
var _field_focus: StyleBoxFlat
|
||||
|
||||
|
||||
func setup(p_main: Main) -> void:
|
||||
main = p_main
|
||||
add_theme_constant_override("separation", 6)
|
||||
add_theme_constant_override("separation", 0)
|
||||
_field = Style.bordered(Style.box(Color(1, 1, 1, 0.05), 6, [8, 3, 8, 3]), 1, Color(1, 1, 1, 0.12))
|
||||
_field_focus = Style.bordered(Style.box(Color(1, 1, 1, 0.1), 6, [8, 3, 8, 3]), 1, Style.BRASS)
|
||||
var scroll := ScrollContainer.new()
|
||||
|
|
@ -29,40 +25,20 @@ func setup(p_main: Main) -> void:
|
|||
_list.add_theme_constant_override("separation", 5)
|
||||
_list.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
scroll.add_child(_list)
|
||||
var foot := HBoxContainer.new()
|
||||
foot.alignment = BoxContainer.ALIGNMENT_END
|
||||
add_child(foot)
|
||||
_reset_all = Button.new()
|
||||
_reset_all.text = "Reset all…"
|
||||
_reset_all.tooltip_text = "Put every variable back to its starting value (variables without a card are cleared)"
|
||||
_reset_all.add_theme_font_size_override("font_size", 13)
|
||||
var n := Style.bordered(Style.box(Color(1, 1, 1, 0.04), 6, [10, 2, 10, 3]), 1, Color(1, 1, 1, 0.12))
|
||||
var h := Style.bordered(Style.box(Color(1, 1, 1, 0.1), 6, [10, 2, 10, 3]), 1, Color(Style.DANGER, 0.6))
|
||||
Style.skin_button(_reset_all, n, h, h, Style.ON_FELT_MUTED, Style.ON_FELT)
|
||||
_reset_all.pressed.connect(confirm_reset_all)
|
||||
foot.add_child(_reset_all)
|
||||
|
||||
|
||||
## Opens the "Reset all variables?" confirmation.
|
||||
func confirm_reset_all() -> ModalCard:
|
||||
var msg := "Every variable goes back to its starting value, and variables without a variable card are cleared. This can't be undone."
|
||||
var d := ModalCard.confirm("Reset all variables?", msg, "Reset all", main.reset_all_variables, true)
|
||||
main.add_child(d)
|
||||
return d
|
||||
|
||||
|
||||
func render() -> void:
|
||||
for c in _list.get_children():
|
||||
_list.remove_child(c)
|
||||
c.queue_free()
|
||||
var names := main.variable_names()
|
||||
_reset_all.disabled = names.is_empty()
|
||||
var names: Array = main.persistent_vars.keys()
|
||||
names.sort_custom(func(a: Variant, b: Variant) -> bool: return str(a).naturalnocasecmp_to(str(b)) < 0)
|
||||
if names.is_empty():
|
||||
var empty := RichText.label("No saved variables yet. A pipe that saves as [color=#%s]@name[/color], an effect such as [color=#%s]@hp = 10[/color], or [lb][lb]Table -> @name]] in a result, keeps its value here." % [Style.BRASS.to_html(false), Style.BRASS.to_html(false)],
|
||||
var empty := RichText.label("No saved variables yet. A pipe that saves as [color=#%s]@name[/color], or [lb][lb]Table -> @name]] in a result, keeps its value here." % Style.BRASS.to_html(false),
|
||||
14, Style.ON_FELT_MUTED, false)
|
||||
_list.add_child(empty)
|
||||
for n in names:
|
||||
_list.add_child(_var_row(n))
|
||||
_list.add_child(_var_row(str(n)))
|
||||
|
||||
var chain: Dictionary = main.current.get("chain_vars", {})
|
||||
if not chain.is_empty():
|
||||
|
|
@ -75,49 +51,36 @@ func render() -> void:
|
|||
var keys: Array = chain.keys()
|
||||
keys.sort()
|
||||
for k in keys:
|
||||
var line := RichText.label("[color=#%s]{%s}[/color] %s" % [RichText.VAR_INK_FELT.to_html(false), k, Expr.format_value(chain[k])],
|
||||
var line := RichText.label("[color=#%s]{%s}[/color] %s" % [RichText.VAR_INK_FELT.to_html(false), k, str(chain[k])],
|
||||
14, Style.ON_FELT, false)
|
||||
_list.add_child(line)
|
||||
|
||||
|
||||
## Shown text of a variable's value ("" when it isn't set).
|
||||
func _value_text(name: String) -> String:
|
||||
var raw: Variant = main.persistent_vars.get(name)
|
||||
if raw == null:
|
||||
return ""
|
||||
var v: Variant = (raw as Dictionary).get("value", "") if raw is Dictionary else raw
|
||||
return Expr.format_value(v)
|
||||
|
||||
|
||||
func _var_row(name: String) -> Control:
|
||||
var is_set := main.persistent_vars.has(name)
|
||||
var card := main.variable_card(name)
|
||||
var v: Dictionary = main.persistent_vars[name] if main.persistent_vars[name] is Dictionary else {"value": str(main.persistent_vars[name])}
|
||||
var row := HBoxContainer.new()
|
||||
row.add_theme_constant_override("separation", 6)
|
||||
var label := Style.make_label("@" + name, Style.body_bold(), 14, RichText.VAR_INK_FELT)
|
||||
label.custom_minimum_size = Vector2(84, 0)
|
||||
label.clip_text = true
|
||||
label.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
|
||||
label.tooltip_text = "{@%s}%s" % [name, (" · " + Formatter.strip_tags(card.name)) if card else ""]
|
||||
label.tooltip_text = "{@%s}" % name
|
||||
label.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
row.add_child(label)
|
||||
|
||||
var edit := LineEdit.new()
|
||||
edit.text = _value_text(name)
|
||||
edit.text = str(v.get("value", ""))
|
||||
edit.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
edit.custom_minimum_size = Vector2(60, 0)
|
||||
edit.add_theme_font_size_override("font_size", 14)
|
||||
edit.add_theme_color_override("font_color", Style.ON_FELT)
|
||||
edit.add_theme_color_override("caret_color", Style.ON_FELT)
|
||||
edit.add_theme_color_override("selection_color", Color(Style.BRASS, 0.4))
|
||||
edit.add_theme_color_override("font_placeholder_color", Color(Style.ON_FELT_MUTED, 0.7))
|
||||
edit.add_theme_stylebox_override("normal", _field)
|
||||
edit.add_theme_stylebox_override("focus", _field_focus)
|
||||
if not is_set and card:
|
||||
edit.placeholder_text = "not set · starts at %s" % (card.initial if card.initial != "" else "0")
|
||||
edit.tooltip_text = "Edit the value (BBCode ok); Enter to save"
|
||||
var commit := func() -> void:
|
||||
if edit.text != _value_text(name) and (main.persistent_vars.has(name) or edit.text != ""):
|
||||
if main.persistent_vars.has(name) and edit.text != str((main.persistent_vars[name] as Dictionary).get("value", "")):
|
||||
main.set_variable(name, edit.text)
|
||||
edit.text_submitted.connect(func(_t: String) -> void:
|
||||
commit.call()
|
||||
|
|
@ -125,21 +88,13 @@ func _var_row(name: String) -> Control:
|
|||
edit.focus_exited.connect(commit)
|
||||
row.add_child(edit)
|
||||
|
||||
if card:
|
||||
var reset := _icon_button("↺", "Reset @%s to its starting value" % name)
|
||||
reset.pressed.connect(func() -> void: main.reset_variable(name))
|
||||
row.add_child(reset)
|
||||
else:
|
||||
var v: Variant = main.persistent_vars.get(name)
|
||||
var source := str(v.get("source", "")) if v is Dictionary else ""
|
||||
var source := str(v.get("source", ""))
|
||||
var st := main.data.get_table(source) if source != "" else null
|
||||
var can := main.can_reroll_variable(name)
|
||||
var again := _icon_button("↻", ("Re-roll from %s" % Formatter.strip_tags(st.name)) if can else "Set by an effect or answer; no table to re-roll from")
|
||||
again.disabled = not can
|
||||
var again := _icon_button("↻", "Re-roll from %s" % Formatter.strip_tags(st.name) if st else "No table to re-roll from")
|
||||
again.disabled = st == null
|
||||
again.pressed.connect(func() -> void: main.reroll_variable(name))
|
||||
row.add_child(again)
|
||||
var clear := _icon_button("×", "Clear {@%s}" % name)
|
||||
clear.disabled = not is_set
|
||||
clear.pressed.connect(func() -> void: main.clear_variable(name))
|
||||
row.add_child(clear)
|
||||
return row
|
||||
|
|
|
|||
Loading…
Reference in a new issue