Conditional pipes and router cards
Pipes can carry "when" (Only if) and "otherwise". When an entry is
chosen, its effects run, its text expands, then every pipe condition and
count is evaluated once as a snapshot before any pipe runs; when pipes
run if true, otherwise pipes if no when pipe was true, plain pipes
always. Condition errors count as false and show as error lines.
New router card (kind "router"): its entries are cases with an
entry-level "when"; the first true case is chosen (empty = Otherwise),
and "No case matched" stops the node. One action. JSON round trip for
entry/pipe when and pipe otherwise, including JsonIO.canonical and
edge labels. Roller.lint_pipes() and Roller.lint_router() for board
checks. A pick choice's save_as is now stored before the snapshot.
UI: Only if / Otherwise in the pipe popover with live validation, pipe
labels ("if @str >= 8", "otherwise") and a source-end diamond on
conditional pipes, router card with fork icon, per-case condition rows,
case editing / reordering in Build, router settings, "+ Table" entry,
router cases in table previews. Logic demo now routes through a router.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
14a0b6e6a4
commit
dbbb9750eb
14 changed files with 1179 additions and 46 deletions
|
|
@ -7,7 +7,8 @@ extends RefCounted
|
||||||
## expression) where the probability mass of each range sets its chance.
|
## expression) where the probability mass of each range sets its chance.
|
||||||
##
|
##
|
||||||
## Every table has a `kind` (docs/LOGIC.md §1): "roll" (the default), "choice",
|
## 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()
|
## "loop", "variable", "sheet" or "router", with the per-kind fields below
|
||||||
|
## (a router's cases are its entries, each with an entry-level `when`). Use create()
|
||||||
## for a well-formed card of each kind.
|
## for a well-formed card of each kind.
|
||||||
##
|
##
|
||||||
## Ranged tables also accept a full expression in `dice` ("2d6 + dm(@end)",
|
## Ranged tables also accept a full expression in `dice` ("2d6 + dm(@end)",
|
||||||
|
|
@ -22,7 +23,10 @@ const KIND_CHOICE := "choice"
|
||||||
const KIND_LOOP := "loop"
|
const KIND_LOOP := "loop"
|
||||||
const KIND_VARIABLE := "variable"
|
const KIND_VARIABLE := "variable"
|
||||||
const KIND_SHEET := "sheet"
|
const KIND_SHEET := "sheet"
|
||||||
const KINDS: Array[String] = [KIND_ROLL, KIND_CHOICE, KIND_LOOP, KIND_VARIABLE, KIND_SHEET]
|
const KIND_ROUTER := "router"
|
||||||
|
const KINDS: Array[String] = [KIND_ROLL, KIND_CHOICE, KIND_LOOP, KIND_VARIABLE, KIND_SHEET, KIND_ROUTER]
|
||||||
|
## A new router's first case condition (an even chance, so both cases can come up).
|
||||||
|
const ROUTER_DEFAULT_WHEN := "1d6 >= 4"
|
||||||
const CHOICES: Array[String] = ["pick", "number", "text"]
|
const CHOICES: Array[String] = ["pick", "number", "text"]
|
||||||
const LOOPS: Array[String] = ["times", "while", "until"]
|
const LOOPS: Array[String] = ["times", "while", "until"]
|
||||||
const VAR_TYPES: Array[String] = ["number", "text", "list"]
|
const VAR_TYPES: Array[String] = ["number", "text", "list"]
|
||||||
|
|
@ -78,7 +82,8 @@ func _init(p_id: String = "", p_name: String = "") -> void:
|
||||||
## the variable type ("number", "text", "list").
|
## the variable type ("number", "text", "list").
|
||||||
## roll: four "Result N" entries · choice pick: three options ·
|
## roll: four "Result N" entries · choice pick: three options ·
|
||||||
## choice number/text: one "Answer" entry · loop: "Each time" and
|
## choice number/text: one "Answer" entry · loop: "Each time" and
|
||||||
## "Afterwards" · variable: no entries · sheet: one template entry.
|
## "Afterwards" · variable: no entries · sheet: one template entry ·
|
||||||
|
## router: an "if …" case (when ROUTER_DEFAULT_WHEN) and an "Otherwise" case.
|
||||||
static func create(p_kind: String, p_id: String, p_name: String, sub: String = "") -> RollTable:
|
static func create(p_kind: String, p_id: String, p_name: String, sub: String = "") -> RollTable:
|
||||||
var t := RollTable.new(p_id, p_name)
|
var t := RollTable.new(p_id, p_name)
|
||||||
t.kind = p_kind if KINDS.has(p_kind) else KIND_ROLL
|
t.kind = p_kind if KINDS.has(p_kind) else KIND_ROLL
|
||||||
|
|
@ -110,9 +115,23 @@ static func create(p_kind: String, p_id: String, p_name: String, sub: String = "
|
||||||
t.initial = "0" if t.var_type == "number" else ""
|
t.initial = "0" if t.var_type == "number" else ""
|
||||||
KIND_SHEET:
|
KIND_SHEET:
|
||||||
t.entries.append(TableEntry.new("e1", "[b]%s[/b]" % p_name))
|
t.entries.append(TableEntry.new("e1", "[b]%s[/b]" % p_name))
|
||||||
|
KIND_ROUTER:
|
||||||
|
var first := TableEntry.new("e1", "if …")
|
||||||
|
first.when = ROUTER_DEFAULT_WHEN
|
||||||
|
t.entries.append(first)
|
||||||
|
t.entries.append(TableEntry.new("e2", "Otherwise"))
|
||||||
return t
|
return t
|
||||||
|
|
||||||
|
|
||||||
|
## Router cards: index of the first case that is an Otherwise case (empty
|
||||||
|
## `when`), or -1.
|
||||||
|
func otherwise_index() -> int:
|
||||||
|
for i in entries.size():
|
||||||
|
if entries[i].when.strip_edges() == "":
|
||||||
|
return i
|
||||||
|
return -1
|
||||||
|
|
||||||
|
|
||||||
func is_kind(k: String) -> bool:
|
func is_kind(k: String) -> bool:
|
||||||
return kind == k
|
return kind == k
|
||||||
|
|
||||||
|
|
|
||||||
187
core/roller.gd
187
core/roller.gd
|
|
@ -12,7 +12,8 @@ extends RefCounted
|
||||||
## and "stop": String when the chain couldn't continue (its summary then
|
## and "stop": String when the chain couldn't continue (its summary then
|
||||||
## explains why).
|
## explains why).
|
||||||
## Logic-card keys (docs/LOGIC.md), present only when they apply:
|
## Logic-card keys (docs/LOGIC.md), present only when they apply:
|
||||||
## kind: "choice" | "loop" | "sheet" (plain roll nodes have no kind)
|
## kind: "choice" | "loop" | "sheet" | "router" (plain roll nodes have no kind)
|
||||||
|
## case: int, on a router node: the index of the case that matched
|
||||||
## effects: Array of {"text": String, "error": true?}, the effect log
|
## effects: Array of {"text": String, "error": true?}, the effect log
|
||||||
## answer: the player's answer on a number/text choice (int or String)
|
## 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
|
## picked: true when the player picked a pick option; random: true for Random
|
||||||
|
|
@ -35,6 +36,7 @@ const MAX_DEPTH := RollContext.DEFAULT_MAX_DEPTH
|
||||||
## Most actions one top-level roll may take (matches RollContext).
|
## Most actions one top-level roll may take (matches RollContext).
|
||||||
const MAX_ACTIONS := RollContext.DEFAULT_MAX_ACTIONS
|
const MAX_ACTIONS := RollContext.DEFAULT_MAX_ACTIONS
|
||||||
const CANCELLED := "Cancelled"
|
const CANCELLED := "Cancelled"
|
||||||
|
const NO_CASE := "No case matched"
|
||||||
|
|
||||||
enum { OP_ROLL, OP_PIPE, OP_LOOP }
|
enum { OP_ROLL, OP_PIPE, OP_LOOP }
|
||||||
|
|
||||||
|
|
@ -204,6 +206,8 @@ static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack:
|
||||||
await _do_choice(t, f, ctx, stack)
|
await _do_choice(t, f, ctx, stack)
|
||||||
RollTable.KIND_LOOP:
|
RollTable.KIND_LOOP:
|
||||||
_start_loop(t, f, ctx, stack)
|
_start_loop(t, f, ctx, stack)
|
||||||
|
RollTable.KIND_ROUTER:
|
||||||
|
await _do_router(t, f, ctx, stack)
|
||||||
RollTable.KIND_SHEET:
|
RollTable.KIND_SHEET:
|
||||||
var sheet := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "",
|
var sheet := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "",
|
||||||
"kind": RollTable.KIND_SHEET}
|
"kind": RollTable.KIND_SHEET}
|
||||||
|
|
@ -261,12 +265,16 @@ static func _pick_node(t: RollTable, ctx: RollContext) -> Dictionary:
|
||||||
## The chosen entry happens: its effects run, its text expands (unless
|
## The chosen entry happens: its effects run, its text expands (unless
|
||||||
## `expand` is false, for answers) and its pipes are queued. `live` renders the
|
## `expand` is false, for answers) and its pipes are queued. `live` renders the
|
||||||
## text without rolling references (sheet cards).
|
## text without rolling references (sheet cards).
|
||||||
|
##
|
||||||
|
## Before any pipe runs, every pipe's condition and count is worked out once,
|
||||||
|
## as a snapshot (see pipe_plan()), so what an earlier pipe's subtree does to
|
||||||
|
## the variables can't change whether or how often a later pipe runs.
|
||||||
static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Array, expand: bool = true, live: bool = false) -> void:
|
static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Array, expand: bool = true, live: bool = false) -> void:
|
||||||
var t: RollTable = node["table"]
|
var t: RollTable = node["table"]
|
||||||
var e: TableEntry = node["entry"]
|
var e: TableEntry = node["entry"]
|
||||||
var depth := int(f.get("depth", 0))
|
var depth := int(f.get("depth", 0))
|
||||||
if e.effects.strip_edges() != "":
|
if e.effects.strip_edges() != "":
|
||||||
node["effects"] = Effects.run(e.effects, ctx, t.id)
|
_log(node, Effects.run(e.effects, ctx, t.id))
|
||||||
if expand:
|
if expand:
|
||||||
ctx.depth = depth + 1
|
ctx.depth = depth + 1
|
||||||
var ex: Dictionary = await TextExpander.expand_async(e.text, ctx, live)
|
var ex: Dictionary = await TextExpander.expand_async(e.text, ctx, live)
|
||||||
|
|
@ -282,20 +290,66 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr
|
||||||
if save != "":
|
if save != "":
|
||||||
var v: Variant = node["answer"] if node.has("answer") else Formatter.to_export_bbcode(str(node["summary"]))
|
var v: Variant = node["answer"] if node.has("answer") else Formatter.to_export_bbcode(str(node["summary"]))
|
||||||
ctx.save(save, v, t.id)
|
ctx.save(save, v, t.id)
|
||||||
for k in range(e.pipes.size() - 1, -1, -1):
|
# A picked option is saved under the choice's save_as before the pipe
|
||||||
var p := e.pipes[k]
|
# snapshot, so its own pipe conditions can read it.
|
||||||
stack.append({"op": OP_PIPE, "node": node, "entry": e, "to": p, "left": -1, "save": e.save_for(p), "depth": depth})
|
if t.kind == RollTable.KIND_CHOICE and t.save_as != "" and not node.has("answer"):
|
||||||
|
ctx.save(t.save_as, Formatter.strip_tags(str(node["summary"])).strip_edges(), t.id)
|
||||||
|
if e.pipes.is_empty():
|
||||||
|
return
|
||||||
|
var log: Array = []
|
||||||
|
var plan := pipe_plan(e, ctx, log)
|
||||||
|
_log(node, log)
|
||||||
|
for k in range(plan.size() - 1, -1, -1):
|
||||||
|
var item: Dictionary = plan[k]
|
||||||
|
if not item["run"]:
|
||||||
|
continue
|
||||||
|
var p: String = item["to"]
|
||||||
|
stack.append({"op": OP_PIPE, "node": node, "entry": e, "to": p, "left": int(item["count"]), "save": e.save_for(p), "depth": depth})
|
||||||
|
|
||||||
|
|
||||||
|
## Appends effect-log lines to a node's "effects".
|
||||||
|
static func _log(node: Dictionary, lines: Array) -> void:
|
||||||
|
if lines.is_empty():
|
||||||
|
return
|
||||||
|
if not node.has("effects"):
|
||||||
|
node["effects"] = []
|
||||||
|
(node["effects"] as Array).append_array(lines)
|
||||||
|
|
||||||
|
|
||||||
|
## The snapshot of an entry's pipes, taken once after the entry's effects ran
|
||||||
|
## and its text expanded: one item per pipe, in pipe order,
|
||||||
|
## {"to": table id, "run": bool, "count": int}.
|
||||||
|
## - A pipe with a condition ("when") runs only if it's true. An error
|
||||||
|
## counts as false and adds an error line to `log`.
|
||||||
|
## - An "otherwise" pipe runs only if none of the entry's conditions was true.
|
||||||
|
## - Any other pipe always runs.
|
||||||
|
## Counts are worked out only for pipes that run (0 for the others); an
|
||||||
|
## expression count's error gives 0 and an error line.
|
||||||
|
static func pipe_plan(e: TableEntry, ctx: RollContext, log: Array = []) -> Array:
|
||||||
|
var plan: Array = []
|
||||||
|
var any_true := false
|
||||||
|
for p in e.pipes:
|
||||||
|
var w := e.when_for(p)
|
||||||
|
var run := true
|
||||||
|
if w != "":
|
||||||
|
var r := Expr.evaluate(w, ctx)
|
||||||
|
if r["error"] != "":
|
||||||
|
log.append({"text": "Pipe condition %s: %s" % [w, r["error"]], "error": true})
|
||||||
|
run = false
|
||||||
|
else:
|
||||||
|
run = Expr.truthy(r["value"])
|
||||||
|
any_true = any_true or run
|
||||||
|
plan.append({"to": p, "run": run, "count": 0, "otherwise": w == "" and e.is_otherwise(p)})
|
||||||
|
for item: Dictionary in plan:
|
||||||
|
if item["otherwise"]:
|
||||||
|
item["run"] = not any_true
|
||||||
|
item.erase("otherwise")
|
||||||
|
if item["run"]:
|
||||||
|
item["count"] = e.count_value(str(item["to"]), ctx, log)
|
||||||
|
return plan
|
||||||
|
|
||||||
|
|
||||||
static func _do_pipe(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: Array) -> void:
|
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:
|
if int(f["left"]) <= 0:
|
||||||
return
|
return
|
||||||
var t := board.get_table(str(f["to"]))
|
var t := board.get_table(str(f["to"]))
|
||||||
|
|
@ -306,6 +360,39 @@ static func _do_pipe(board: TowerBoard, f: Dictionary, ctx: RollContext, stack:
|
||||||
stack.append({"op": OP_ROLL, "id": f["to"], "parent": f["node"], "save": f["save"], "depth": f["depth"]})
|
stack.append({"op": OP_ROLL, "id": f["to"], "parent": f["node"], "save": f["save"], "depth": f["depth"]})
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Routers ----------
|
||||||
|
|
||||||
|
## The index of the first router case whose condition is true (an empty
|
||||||
|
## condition, the Otherwise case, always matches), or -1. Errors count as
|
||||||
|
## false and add a line to `log`.
|
||||||
|
static func route(t: RollTable, ctx: RollContext, log: Array = []) -> int:
|
||||||
|
for k in t.entries.size():
|
||||||
|
var w := t.entries[k].when.strip_edges()
|
||||||
|
if w == "":
|
||||||
|
return k
|
||||||
|
var r := Expr.evaluate(w, ctx)
|
||||||
|
if r["error"] != "":
|
||||||
|
log.append({"text": "Case %s: %s" % [w, r["error"]], "error": true})
|
||||||
|
elif Expr.truthy(r["value"]):
|
||||||
|
return k
|
||||||
|
return -1
|
||||||
|
|
||||||
|
|
||||||
|
static func _do_router(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
|
||||||
|
var log: Array = []
|
||||||
|
var k := route(t, ctx, log)
|
||||||
|
if k < 0:
|
||||||
|
var stop := _stop(t, NO_CASE, {"kind": RollTable.KIND_ROUTER})
|
||||||
|
_log(stop, log)
|
||||||
|
_attach(f, stop, ctx)
|
||||||
|
return
|
||||||
|
var node := {"table": t, "index": k, "entry": t.entries[k], "children": [], "summary": "",
|
||||||
|
"kind": RollTable.KIND_ROUTER, "case": k}
|
||||||
|
_log(node, log)
|
||||||
|
_attach(f, node, ctx)
|
||||||
|
await _enter(node, f, ctx, stack)
|
||||||
|
|
||||||
|
|
||||||
# ---------- Loops ----------
|
# ---------- Loops ----------
|
||||||
|
|
||||||
static func _repeated(n: int) -> String:
|
static func _repeated(n: int) -> String:
|
||||||
|
|
@ -456,8 +543,6 @@ static func _do_choice(t: RollTable, f: Dictionary, ctx: RollContext, stack: Arr
|
||||||
if node.has("stop"):
|
if node.has("stop"):
|
||||||
return
|
return
|
||||||
await _enter(node, f, ctx, stack)
|
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:
|
static func _answered(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array, value: Variant, summary: String) -> void:
|
||||||
|
|
@ -486,7 +571,7 @@ static func _pick_weighted(t: RollTable, rng: RandomNumberGenerator) -> int:
|
||||||
## Ids of tables that can never finish rolling: every result they can give
|
## Ids of tables that can never finish rolling: every result they can give
|
||||||
## leads, through pipes, back into such a table. A table that loops on only
|
## leads, through pipes, back into such a table. A table that loops on only
|
||||||
## some of its entries is fine, and so is a pipe whose count is an expression
|
## some of its entries is fine, and so is a pipe whose count is an expression
|
||||||
## (it may come to 0).
|
## (it may come to 0) or a conditional pipe (it may not run).
|
||||||
static func endless_cycles(board: TowerBoard) -> Array[String]:
|
static func endless_cycles(board: TowerBoard) -> Array[String]:
|
||||||
var done := {}
|
var done := {}
|
||||||
var changed := true
|
var changed := true
|
||||||
|
|
@ -507,7 +592,7 @@ static func endless_cycles(board: TowerBoard) -> Array[String]:
|
||||||
|
|
||||||
static func _entry_finishes(e: TableEntry, board: TowerBoard, done: Dictionary) -> bool:
|
static func _entry_finishes(e: TableEntry, board: TowerBoard, done: Dictionary) -> bool:
|
||||||
for p in e.pipes:
|
for p in e.pipes:
|
||||||
if e.count_expr(p) != "":
|
if e.count_expr(p) != "" or e.is_conditional(p):
|
||||||
continue
|
continue
|
||||||
if board.get_table(p) != null and not done.has(p):
|
if board.get_table(p) != null and not done.has(p):
|
||||||
return false
|
return false
|
||||||
|
|
@ -541,7 +626,8 @@ static func _can_finish(t: RollTable, board: TowerBoard, done: Dictionary) -> bo
|
||||||
## One line of the result tray for a single node. Plain data only, because it
|
## One line of the result tray for a single node. Plain data only, because it
|
||||||
## is saved in the roll history. "text" is BBCode with internal markers.
|
## is saved in the roll history. "text" is BBCode with internal markers.
|
||||||
## Logic-card keys (only when they apply): kind, effects (Array of {text,
|
## Logic-card keys (only when they apply): kind, effects (Array of {text,
|
||||||
## error?}), answer, passes, pass, after, picked, random, limit, cancelled.
|
## error?}), answer, passes, pass, after, picked, random, limit, cancelled,
|
||||||
|
## case (router nodes: the matched case's index).
|
||||||
static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
|
static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
|
||||||
var t: RollTable = n["table"]
|
var t: RollTable = n["table"]
|
||||||
var step := {
|
var step := {
|
||||||
|
|
@ -567,7 +653,7 @@ static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
|
||||||
step["kind"] = n["kind"]
|
step["kind"] = n["kind"]
|
||||||
if n.has("effects"):
|
if n.has("effects"):
|
||||||
step["effects"] = (n["effects"] as Array).duplicate(true)
|
step["effects"] = (n["effects"] as Array).duplicate(true)
|
||||||
for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled"]:
|
for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled", "case"]:
|
||||||
if n.has(k):
|
if n.has(k):
|
||||||
step[k] = n[k]
|
step[k] = n[k]
|
||||||
return step
|
return step
|
||||||
|
|
@ -705,3 +791,66 @@ static func render_sheet(board: TowerBoard, persistent: Dictionary, t: RollTable
|
||||||
if t.entries.is_empty():
|
if t.entries.is_empty():
|
||||||
return ""
|
return ""
|
||||||
return TextExpander.render(t.entries[0].text, live_context(board, persistent))
|
return TextExpander.render(t.entries[0].text, live_context(board, persistent))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Lint ----------
|
||||||
|
|
||||||
|
## Problems with conditional pipes and router cards, for a board check. Pure:
|
||||||
|
## nothing is rolled. Each item: {table_id, entry_id ("" for the whole card),
|
||||||
|
## message}.
|
||||||
|
## - a pipe condition, or a router case condition, that doesn't parse
|
||||||
|
## - an entry whose "otherwise" pipe comes before one of its conditional
|
||||||
|
## pipes (a hint: it still works, since the snapshot is taken first)
|
||||||
|
## - an "otherwise" pipe on an entry with no conditional pipe (always runs)
|
||||||
|
## - a router with no cases, or whose Otherwise case isn't the last one
|
||||||
|
static func lint_pipes(board: TowerBoard) -> Array[Dictionary]:
|
||||||
|
var out: Array[Dictionary] = []
|
||||||
|
for t in board.tables:
|
||||||
|
out.append_array(lint_router(t))
|
||||||
|
for i in t.entries.size():
|
||||||
|
var e := t.entries[i]
|
||||||
|
var first_other := ""
|
||||||
|
var has_when := false
|
||||||
|
var warned := false
|
||||||
|
for p in e.pipes:
|
||||||
|
var pw := e.when_for(p)
|
||||||
|
if pw != "":
|
||||||
|
has_when = true
|
||||||
|
if Expr.check(pw) != "":
|
||||||
|
out.append({"table_id": t.id, "entry_id": e.id,
|
||||||
|
"message": "Pipe condition %s: %s" % [pw, Expr.check(pw)]})
|
||||||
|
if first_other != "" and not warned:
|
||||||
|
warned = true
|
||||||
|
out.append({"table_id": t.id, "entry_id": e.id,
|
||||||
|
"message": "The otherwise pipe to %s comes before a conditional pipe; put it last so it reads in order" % _table_name(board, first_other)})
|
||||||
|
elif e.is_otherwise(p) and first_other == "":
|
||||||
|
first_other = p
|
||||||
|
if first_other != "" and not has_when:
|
||||||
|
out.append({"table_id": t.id, "entry_id": e.id,
|
||||||
|
"message": "The otherwise pipe to %s always runs: no pipe on this entry has a condition" % _table_name(board, first_other)})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
## The router part of lint_pipes() for one card (empty for other kinds): no
|
||||||
|
## cases, an Otherwise case that isn't last, case conditions that don't parse.
|
||||||
|
static func lint_router(t: RollTable) -> Array[Dictionary]:
|
||||||
|
var out: Array[Dictionary] = []
|
||||||
|
if t.kind != RollTable.KIND_ROUTER:
|
||||||
|
return out
|
||||||
|
if t.entries.is_empty():
|
||||||
|
out.append({"table_id": t.id, "entry_id": "", "message": "This router has no cases"})
|
||||||
|
for i in t.entries.size():
|
||||||
|
var e := t.entries[i]
|
||||||
|
var w := e.when.strip_edges()
|
||||||
|
if w == "":
|
||||||
|
if i < t.entries.size() - 1:
|
||||||
|
out.append({"table_id": t.id, "entry_id": e.id,
|
||||||
|
"message": "The Otherwise case isn't last, so the cases after it can never be chosen"})
|
||||||
|
elif Expr.check(w) != "":
|
||||||
|
out.append({"table_id": t.id, "entry_id": e.id, "message": "Case %s: %s" % [w, Expr.check(w)]})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
static func _table_name(board: TowerBoard, id: String) -> String:
|
||||||
|
var t := board.get_table(id)
|
||||||
|
return Formatter.strip_tags(t.name) if t else id
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,15 @@ var pipes: Array[String] = []
|
||||||
var pipe_count: Dictionary = {}
|
var pipe_count: Dictionary = {}
|
||||||
## target table id -> variable name to save the result under (missing = none).
|
## target table id -> variable name to save the result under (missing = none).
|
||||||
var pipe_save: Dictionary = {}
|
var pipe_save: Dictionary = {}
|
||||||
|
## target table id -> condition expression: the pipe runs only when it's true
|
||||||
|
## (docs/LOGIC.md, Conditional pipes). Missing = always.
|
||||||
|
var pipe_when: Dictionary = {}
|
||||||
|
## target table id -> true: the pipe runs only when none of this entry's
|
||||||
|
## conditional pipes did. Ignored while the pipe has a condition.
|
||||||
|
var pipe_otherwise: Dictionary = {}
|
||||||
|
## Router cards: this case's condition. "" is the Otherwise case (always
|
||||||
|
## matches). Ignored on other kinds.
|
||||||
|
var when: String = ""
|
||||||
var has_range: bool = false
|
var has_range: bool = false
|
||||||
var range_lo: int = 1
|
var range_lo: int = 1
|
||||||
var range_hi: int = 1
|
var range_hi: int = 1
|
||||||
|
|
@ -98,6 +107,46 @@ func set_pipe_count(target: String, n: Variant) -> void:
|
||||||
pipe_count[target] = k
|
pipe_count[target] = k
|
||||||
|
|
||||||
|
|
||||||
|
## The pipe's condition, or "".
|
||||||
|
func when_for(target: String) -> String:
|
||||||
|
return str(pipe_when.get(target, ""))
|
||||||
|
|
||||||
|
|
||||||
|
## True when the pipe is an "otherwise" pipe (and has no condition).
|
||||||
|
func is_otherwise(target: String) -> bool:
|
||||||
|
return bool(pipe_otherwise.get(target, false)) and when_for(target) == ""
|
||||||
|
|
||||||
|
|
||||||
|
## True when the pipe has a condition or is an otherwise pipe.
|
||||||
|
func is_conditional(target: String) -> bool:
|
||||||
|
return when_for(target) != "" or is_otherwise(target)
|
||||||
|
|
||||||
|
|
||||||
|
## Sets the pipe's condition ("" for none). A condition clears "otherwise".
|
||||||
|
func set_pipe_when(target: String, expr: String) -> void:
|
||||||
|
expr = expr.strip_edges()
|
||||||
|
if expr == "":
|
||||||
|
pipe_when.erase(target)
|
||||||
|
else:
|
||||||
|
pipe_when[target] = expr
|
||||||
|
pipe_otherwise.erase(target)
|
||||||
|
|
||||||
|
|
||||||
|
func set_pipe_otherwise(target: String, on: bool) -> void:
|
||||||
|
if on and when_for(target) == "":
|
||||||
|
pipe_otherwise[target] = true
|
||||||
|
else:
|
||||||
|
pipe_otherwise.erase(target)
|
||||||
|
|
||||||
|
|
||||||
|
## True when any of this entry's pipes has a condition or is an otherwise pipe.
|
||||||
|
func has_conditional_pipes() -> bool:
|
||||||
|
for p in pipes:
|
||||||
|
if is_conditional(p):
|
||||||
|
return true
|
||||||
|
return false
|
||||||
|
|
||||||
|
|
||||||
func set_pipe_save(target: String, name: String) -> void:
|
func set_pipe_save(target: String, name: String) -> void:
|
||||||
name = name.strip_edges()
|
name = name.strip_edges()
|
||||||
if name == "":
|
if name == "":
|
||||||
|
|
@ -119,6 +168,8 @@ func remove_pipe(target: String) -> void:
|
||||||
pipes.erase(target)
|
pipes.erase(target)
|
||||||
pipe_count.erase(target)
|
pipe_count.erase(target)
|
||||||
pipe_save.erase(target)
|
pipe_save.erase(target)
|
||||||
|
pipe_when.erase(target)
|
||||||
|
pipe_otherwise.erase(target)
|
||||||
|
|
||||||
|
|
||||||
func to_dict() -> Dictionary:
|
func to_dict() -> Dictionary:
|
||||||
|
|
@ -129,13 +180,17 @@ func to_dict() -> Dictionary:
|
||||||
d["weight"] = weight
|
d["weight"] = weight
|
||||||
if effects != "":
|
if effects != "":
|
||||||
d["effects"] = effects
|
d["effects"] = effects
|
||||||
|
if when.strip_edges() != "":
|
||||||
|
d["when"] = when.strip_edges()
|
||||||
if not pipes.is_empty():
|
if not pipes.is_empty():
|
||||||
var list: Array = []
|
var list: Array = []
|
||||||
for p in pipes:
|
for p in pipes:
|
||||||
var expr := count_expr(p)
|
var expr := count_expr(p)
|
||||||
var n := count_for(p)
|
var n := count_for(p)
|
||||||
var s := save_for(p)
|
var s := save_for(p)
|
||||||
if expr == "" and n == 1 and s == "":
|
var w := when_for(p)
|
||||||
|
var other := is_otherwise(p)
|
||||||
|
if expr == "" and n == 1 and s == "" and w == "" and not other:
|
||||||
list.append(p)
|
list.append(p)
|
||||||
else:
|
else:
|
||||||
var po := {"table": p}
|
var po := {"table": p}
|
||||||
|
|
@ -145,6 +200,10 @@ func to_dict() -> Dictionary:
|
||||||
po["count"] = n
|
po["count"] = n
|
||||||
if s != "":
|
if s != "":
|
||||||
po["save_as"] = s
|
po["save_as"] = s
|
||||||
|
if w != "":
|
||||||
|
po["when"] = w
|
||||||
|
elif other:
|
||||||
|
po["otherwise"] = true
|
||||||
list.append(po)
|
list.append(po)
|
||||||
d["pipes"] = list
|
d["pipes"] = list
|
||||||
if has_range:
|
if has_range:
|
||||||
|
|
@ -157,12 +216,15 @@ static func from_dict(d: Dictionary) -> TableEntry:
|
||||||
e.details = str(d.get("details", ""))
|
e.details = str(d.get("details", ""))
|
||||||
e.weight = maxi(0, int(d.get("weight", 1)))
|
e.weight = maxi(0, int(d.get("weight", 1)))
|
||||||
e.effects = str(d.get("effects", ""))
|
e.effects = str(d.get("effects", ""))
|
||||||
|
e.when = str(d.get("when", "")).strip_edges() if d.get("when") != null else ""
|
||||||
for p: Variant in d.get("pipes", []):
|
for p: Variant in d.get("pipes", []):
|
||||||
if p is Dictionary:
|
if p is Dictionary:
|
||||||
var target := str(p.get("table", ""))
|
var target := str(p.get("table", ""))
|
||||||
if target != "":
|
if target != "":
|
||||||
var c: Variant = p.get("count", 1)
|
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, c if c is String else int(c), str(p.get("save_as", "")))
|
||||||
|
e.set_pipe_when(target, str(p.get("when", "")) if p.get("when") != null else "")
|
||||||
|
e.set_pipe_otherwise(target, bool(p.get("otherwise", false)))
|
||||||
elif str(p) != "":
|
elif str(p) != "":
|
||||||
e.add_pipe(str(p))
|
e.add_pipe(str(p))
|
||||||
var r: Variant = d.get("range")
|
var r: Variant = d.get("range")
|
||||||
|
|
|
||||||
|
|
@ -17,10 +17,12 @@ Every table has a `kind`. Existing tables are `roll`.
|
||||||
| `loop` | Runs its **Each time** entry repeatedly, then its **Afterwards** entry once (§3) | The loop rule and two rows |
|
| `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 |
|
| `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 |
|
| `sheet` | Prints its template with current values (§6) | The template, rendered live |
|
||||||
|
| `router` | Chooses the first of its cases whose condition is true (§3b) | A fork icon, one row per case with its condition |
|
||||||
|
|
||||||
Every kind except `variable` can be the start of a roll and can be the target of a pipe.
|
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
|
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`).
|
"save as" options, and a pipe count may now be an expression (`@terms`, `1d3`). A pipe may
|
||||||
|
also have a condition, or be an "otherwise" pipe (§3a).
|
||||||
|
|
||||||
## 2. Choice cards
|
## 2. Choice cards
|
||||||
|
|
||||||
|
|
@ -56,9 +58,67 @@ The chain variable `i` holds the pass number (1, 2, …) during Each time. A loo
|
||||||
reads "Repeated N times". Pipes may also form cycles (a table piping back to an earlier one).
|
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.
|
Both are bounded only by the action limit.
|
||||||
|
|
||||||
|
## 3a. Conditional pipes
|
||||||
|
|
||||||
|
A pipe may carry `"when": "<expression>"` (shown as **Only if** in the pipe's pop-up) and/or
|
||||||
|
`"otherwise": true`. A pipe with a `when` ignores `otherwise`.
|
||||||
|
|
||||||
|
When an entry is chosen (rolled, picked, answered, a loop pass, a router case):
|
||||||
|
|
||||||
|
1. Its effects run, its text expands, and any "save as" (the pipe's that led here, or a pick
|
||||||
|
choice's `save_as`) is stored.
|
||||||
|
2. **The snapshot.** Every `when` condition and every count of the entry's pipes is worked
|
||||||
|
out once, now, before any pipe runs.
|
||||||
|
3. The pipes run in list order:
|
||||||
|
- a pipe with `when` runs only if its condition was true;
|
||||||
|
- an `otherwise` pipe runs only if none of the entry's `when` pipes was true;
|
||||||
|
- any other pipe always runs.
|
||||||
|
|
||||||
|
So an earlier pipe's subtree can change variables without changing whether, or how many
|
||||||
|
times, a later pipe on the same entry runs. Pipes are not "else if": two true conditions both
|
||||||
|
run (use a router, §3b, for first-match). Counts are only worked out for pipes that run; a
|
||||||
|
skipped pipe's count dice are never rolled.
|
||||||
|
|
||||||
|
A condition that fails to evaluate counts as false and adds a red line to the node's effect
|
||||||
|
log ("Pipe condition …: …"), the way a bad pipe count does. Only the pipes actually taken
|
||||||
|
light up after a roll. On the board, a conditional pipe has a small diamond at its source
|
||||||
|
end (hollow for otherwise) and a label such as `if @str >= 8 ×2 → foe` or `otherwise`.
|
||||||
|
|
||||||
|
**Change from earlier versions.** Pipe counts used to be evaluated lazily: the second pipe's
|
||||||
|
count was read only after the first pipe's whole subtree had run, so a branch that changed a
|
||||||
|
variable could make a later pipe fire too ("both branches fired"). Counts now come from the
|
||||||
|
snapshot. Also, a pick choice's `save_as` is now stored before the snapshot (it used to be
|
||||||
|
stored after the option's pipes were queued, which made no difference while counts were
|
||||||
|
lazy). No existing test changed.
|
||||||
|
|
||||||
|
## 3b. Router cards
|
||||||
|
|
||||||
|
A router (`kind: "router"`, "Router" in the **+ Table ▾** menu, "if / else if / otherwise")
|
||||||
|
has no dice. Its entries are **cases**, each with an entry-level `when` expression.
|
||||||
|
|
||||||
|
- When the chain reaches it, the cases are checked top to bottom and the **first** true case
|
||||||
|
is chosen. A case with an empty `when` (shown as **Otherwise**) always matches, so it
|
||||||
|
should be the last one.
|
||||||
|
- The chosen case happens exactly like a rolled entry: its effects run, its text expands and
|
||||||
|
its pipes follow (with the snapshot rule of §3a).
|
||||||
|
- If no case matches, the node stops with a visible "No case matched". A case condition that
|
||||||
|
errors counts as false and adds a red line ("Case …: …") to the node.
|
||||||
|
- It counts as one action. The node and step have `kind: "router"` and `case` (the chosen
|
||||||
|
case's index). Routers have no ranges, weights or card mode.
|
||||||
|
- A new router has two cases: "if …" (with the condition `1d6 >= 4`, to be edited) and
|
||||||
|
"Otherwise". **+ Add case** on the card adds an `if false` case before Otherwise; cases can
|
||||||
|
be reordered and removed on the card, and their conditions edited there or in the
|
||||||
|
settings dialog.
|
||||||
|
|
||||||
|
`Roller.lint_pipes(board)` lists problems for a board check: `when` or case conditions that
|
||||||
|
don't parse, an otherwise pipe listed before a `when` pipe on the same entry (a hint: it still
|
||||||
|
works), an otherwise pipe on an entry with no `when` pipe (it always runs), and routers with
|
||||||
|
no cases or whose Otherwise case isn't last. Each item is `{table_id, entry_id, message}`.
|
||||||
|
|
||||||
## 4. Expressions
|
## 4. Expressions
|
||||||
|
|
||||||
Expressions appear in loop rules, pipe counts, `min`/`max`, dice fields and effects. They are
|
Expressions appear in loop rules, pipe counts, pipe conditions, router cases, `min`/`max`,
|
||||||
|
dice fields and effects. They are
|
||||||
evaluated with Godot's `Expression`, after a small rewrite.
|
evaluated with Godot's `Expression`, after a small rewrite.
|
||||||
|
|
||||||
- **Numbers and text:** `12`, `-3`, `"Aslan"`
|
- **Numbers and text:** `12`, `-3`, `"Aslan"`
|
||||||
|
|
@ -132,7 +192,7 @@ step's result.
|
||||||
|
|
||||||
## 7. Limits
|
## 7. Limits
|
||||||
- **Actions:** one top-level roll may take at most **10,000 actions**. One action is a table
|
- **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
|
being rolled or answered, a router choosing a case, or one loop pass. Past that, the roll stops with "Stopped after
|
||||||
10,000 actions", and everything up to that point is kept.
|
10,000 actions", and everything up to that point is kept.
|
||||||
- **Inline references:** `[[refs]]` inside text still nest at most 32 deep.
|
- **Inline references:** `[[refs]]` inside text still nest at most 32 deep.
|
||||||
- **Implementation:** pipes and loops must not use GDScript recursion proportional to chain
|
- **Implementation:** pipes and loops must not use GDScript recursion proportional to chain
|
||||||
|
|
@ -162,5 +222,7 @@ Table keys:
|
||||||
|
|
||||||
Entry keys:
|
Entry keys:
|
||||||
- `effects` (String)
|
- `effects` (String)
|
||||||
|
- `when` (String, router cases; empty or missing is Otherwise)
|
||||||
|
|
||||||
Pipe objects may have `"count": "<expression>"`.
|
Pipe objects may have `"count": "<expression>"`, `"when": "<expression>"` and
|
||||||
|
`"otherwise": true` (left out when the pipe has a `when`).
|
||||||
|
|
|
||||||
|
|
@ -98,7 +98,7 @@
|
||||||
"details": "One room check per room the player chose, then the way out.",
|
"details": "One room check per room the player chose, then the way out.",
|
||||||
"entries": [
|
"entries": [
|
||||||
{ "id": "e1", "text": "Room {i}", "pipes": ["room_check"] },
|
{ "id": "e1", "text": "Room {i}", "pipes": ["room_check"] },
|
||||||
{ "id": "e2", "text": "Head back up", "pipes": ["way_out"] }
|
{ "id": "e2", "text": "Head back up", "pipes": ["climb"] }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
@ -114,12 +114,25 @@
|
||||||
{ "id": "e3", "text": "A glinting cache", "effects": "@gold += 2d6\n@loot += \"gem\"", "range": [10, 12] }
|
{ "id": "e3", "text": "A glinting cache", "effects": "@gold += 2d6\n@loot += \"gem\"", "range": [10, 12] }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"id": "climb",
|
||||||
|
"name": "On the way up",
|
||||||
|
"kind": "router",
|
||||||
|
"x": 680,
|
||||||
|
"y": 330,
|
||||||
|
"details": "Checks the delver's state once, top to bottom: the first case that's true is the one that happens.",
|
||||||
|
"entries": [
|
||||||
|
{ "id": "e1", "text": "Carried up by a passing patrol", "when": "@hp <= 0", "effects": "@hp = 1", "pipes": ["report"] },
|
||||||
|
{ "id": "e2", "text": "Pockets heavy with gold", "when": "@gold >= 12", "details": "The guard at the top has noticed.", "pipes": ["way_out"] },
|
||||||
|
{ "id": "e3", "text": "Up the stairs", "pipes": ["way_out"] }
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"id": "way_out",
|
"id": "way_out",
|
||||||
"name": "Way out",
|
"name": "Way out",
|
||||||
"kind": "choice",
|
"kind": "choice",
|
||||||
"prompt": "{@name} has {@gold} gold and {@hp} HP left. How do they leave?",
|
"prompt": "{@name} has {@gold} gold and {@hp} HP left. How do they leave?",
|
||||||
"x": 680,
|
"x": 1000,
|
||||||
"y": 330,
|
"y": 330,
|
||||||
"entries": [
|
"entries": [
|
||||||
{ "id": "e1", "text": "Sneak past the guard", "details": "Quiet and slow. Luck grows.", "effects": "@luck += 1", "pipes": ["report"] },
|
{ "id": "e1", "text": "Sneak past the guard", "details": "Quiet and slow. Luck grows.", "effects": "@luck += 1", "pipes": ["report"] },
|
||||||
|
|
@ -131,7 +144,7 @@
|
||||||
"id": "report",
|
"id": "report",
|
||||||
"name": "Delve report",
|
"name": "Delve report",
|
||||||
"kind": "sheet",
|
"kind": "sheet",
|
||||||
"x": 1000,
|
"x": 1320,
|
||||||
"y": 330,
|
"y": 330,
|
||||||
"entries": [
|
"entries": [
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -10,9 +10,10 @@ extends RefCounted
|
||||||
## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode],
|
## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode],
|
||||||
## [deck_empty], [kind], [choice], [prompt], [save_as], [min], [max],
|
## [deck_empty], [kind], [choice], [prompt], [save_as], [min], [max],
|
||||||
## [loop], [loop_expr], [var_name], [var_type], [initial], entries
|
## [loop], [loop_expr], [var_name], [var_type], [initial], entries
|
||||||
## entry: id, text, [details], [weight], [range], [effects], [pipes]
|
## entry: id, text, [details], [weight], [range], [effects], [when], [pipes]
|
||||||
## pipe: a table id String, or {"table": id, "count": n or "<expression>",
|
## pipe: a table id String, or {"table": id, "count": n or "<expression>",
|
||||||
## "save_as": name}
|
## "save_as": name, "when": "<expression>", "otherwise": true}
|
||||||
|
## ("otherwise" is dropped when the pipe has a "when")
|
||||||
## The logic-card keys (docs/LOGIC.md §9) are Strings, and are left out when
|
## The logic-card keys (docs/LOGIC.md §9) are Strings, and are left out when
|
||||||
## they have their default value.
|
## they have their default value.
|
||||||
|
|
||||||
|
|
@ -154,6 +155,8 @@ static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Di
|
||||||
ed["details"] = clean.call(str(ed["details"]))
|
ed["details"] = clean.call(str(ed["details"]))
|
||||||
if ed.has("effects"):
|
if ed.has("effects"):
|
||||||
ed["effects"] = clean.call(str(ed["effects"]))
|
ed["effects"] = clean.call(str(ed["effects"]))
|
||||||
|
if ed.has("when"):
|
||||||
|
ed["when"] = clean.call(str(ed["when"]))
|
||||||
if ed.has("range"):
|
if ed.has("range"):
|
||||||
var r: Array = ed["range"]
|
var r: Array = ed["range"]
|
||||||
if int(r[0]) > int(r[1]):
|
if int(r[0]) > int(r[1]):
|
||||||
|
|
@ -175,6 +178,8 @@ static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Di
|
||||||
np["table"] = target
|
np["table"] = target
|
||||||
if np.has("save_as"):
|
if np.has("save_as"):
|
||||||
np["save_as"] = clean.call(str(np["save_as"]))
|
np["save_as"] = clean.call(str(np["save_as"]))
|
||||||
|
if np.has("when"):
|
||||||
|
np["when"] = clean.call(str(np["when"]))
|
||||||
pipes.append(np)
|
pipes.append(np)
|
||||||
else:
|
else:
|
||||||
pipes.append(target)
|
pipes.append(target)
|
||||||
|
|
@ -337,6 +342,9 @@ static func _canon_entry(ev: Variant) -> Dictionary:
|
||||||
var effects := str(ed.get("effects", "")) if ed.get("effects") != null else ""
|
var effects := str(ed.get("effects", "")) if ed.get("effects") != null else ""
|
||||||
if effects.strip_edges() != "":
|
if effects.strip_edges() != "":
|
||||||
e["effects"] = effects
|
e["effects"] = effects
|
||||||
|
var when := str(ed.get("when", "")).strip_edges() if ed.get("when") != null else ""
|
||||||
|
if when != "":
|
||||||
|
e["when"] = when
|
||||||
var src_pipes: Variant = ed.get("pipes", ed.get("triggers", []))
|
var src_pipes: Variant = ed.get("pipes", ed.get("triggers", []))
|
||||||
var pipes: Array = []
|
var pipes: Array = []
|
||||||
if src_pipes is Array:
|
if src_pipes is Array:
|
||||||
|
|
@ -353,6 +361,11 @@ static func _canon_entry(ev: Variant) -> Dictionary:
|
||||||
np["count"] = int(cnt if cnt != null else 1)
|
np["count"] = int(cnt if cnt != null else 1)
|
||||||
if str(p.get("save_as", "")) != "":
|
if str(p.get("save_as", "")) != "":
|
||||||
np["save_as"] = str(p["save_as"])
|
np["save_as"] = str(p["save_as"])
|
||||||
|
var pw := str(p.get("when", "")).strip_edges() if p.get("when") != null else ""
|
||||||
|
if pw != "":
|
||||||
|
np["when"] = pw
|
||||||
|
elif p.get("otherwise", false) is bool and bool(p.get("otherwise", false)):
|
||||||
|
np["otherwise"] = true
|
||||||
pipes.append(np)
|
pipes.append(np)
|
||||||
if not pipes.is_empty():
|
if not pipes.is_empty():
|
||||||
e["pipes"] = pipes
|
e["pipes"] = pipes
|
||||||
|
|
@ -393,22 +406,30 @@ static func unique_id(base: String, used: Dictionary) -> String:
|
||||||
|
|
||||||
|
|
||||||
## Normalizes a pipe (String or Dictionary) to {"table", "count", "save_as",
|
## Normalizes a pipe (String or Dictionary) to {"table", "count", "save_as",
|
||||||
## "count_expr"}. An expression count ("@terms") reads as count 1, with the
|
## "count_expr", "when", "otherwise"}. An expression count ("@terms") reads as
|
||||||
## expression in "count_expr" ("" otherwise).
|
## count 1, with the expression in "count_expr" ("" otherwise). "when" is the
|
||||||
|
## pipe's condition ("" for none); "otherwise" is true only without one.
|
||||||
static func pipe_info(p: Variant) -> Dictionary:
|
static func pipe_info(p: Variant) -> Dictionary:
|
||||||
if p is Dictionary:
|
if p is Dictionary:
|
||||||
var c: Variant = p.get("count", 1)
|
var c: Variant = p.get("count", 1)
|
||||||
var expr := ""
|
var expr := ""
|
||||||
if c is String and _num(c, null) == null and (c as String).strip_edges() != "":
|
if c is String and _num(c, null) == null and (c as String).strip_edges() != "":
|
||||||
expr = (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}
|
var w := str(p.get("when", "")).strip_edges() if p.get("when") != null else ""
|
||||||
return {"table": str(p), "count": 1, "save_as": "", "count_expr": ""}
|
return {"table": str(p.get("table", "")), "count": int(_num(c, 1)), "save_as": str(p.get("save_as", "")), "count_expr": expr,
|
||||||
|
"when": w, "otherwise": w == "" and p.get("otherwise", false) is bool and bool(p.get("otherwise", false))}
|
||||||
|
return {"table": str(p), "count": 1, "save_as": "", "count_expr": "", "when": "", "otherwise": false}
|
||||||
|
|
||||||
|
|
||||||
## Edge label for a pipe: "" (plain), "×2", "→ weapon" or "×2 → weapon"
|
## Edge label for a pipe: "" (plain), "×2", "→ weapon" or "×2 → weapon"
|
||||||
## ("×@terms" for an expression count).
|
## ("×@terms" for an expression count), led by "if <condition>" or
|
||||||
|
## "otherwise" on a conditional pipe ("if @str >= 8 ×2").
|
||||||
static func pipe_label(info: Dictionary) -> String:
|
static func pipe_label(info: Dictionary) -> String:
|
||||||
var parts: Array[String] = []
|
var parts: Array[String] = []
|
||||||
|
if str(info.get("when", "")) != "":
|
||||||
|
parts.append("if " + str(info["when"]))
|
||||||
|
elif bool(info.get("otherwise", false)):
|
||||||
|
parts.append("otherwise")
|
||||||
if str(info.get("count_expr", "")) != "":
|
if str(info.get("count_expr", "")) != "":
|
||||||
parts.append("×" + str(info["count_expr"]))
|
parts.append("×" + str(info["count_expr"]))
|
||||||
elif int(info["count"]) != 1:
|
elif int(info["count"]) != 1:
|
||||||
|
|
|
||||||
424
tests/test_router.gd
Normal file
424
tests/test_router.gd
Normal file
|
|
@ -0,0 +1,424 @@
|
||||||
|
extends SceneTree
|
||||||
|
## Headless checks for conditional pipes and router cards (docs/LOGIC.md §3a
|
||||||
|
## and §3b): when / otherwise selection, the snapshot rule, expression errors,
|
||||||
|
## first-match routing, "No case matched", the file format, lint_pipes() and a
|
||||||
|
## small board where a router replaces a chain-variable workaround.
|
||||||
|
## Run: godot --headless --path . -s res://tests/test_router.gd
|
||||||
|
|
||||||
|
var _failures := 0
|
||||||
|
|
||||||
|
|
||||||
|
func _init() -> void:
|
||||||
|
_test_when_otherwise()
|
||||||
|
_test_snapshot()
|
||||||
|
_test_errors()
|
||||||
|
_test_router()
|
||||||
|
_test_no_case()
|
||||||
|
_test_json()
|
||||||
|
_test_lint()
|
||||||
|
_test_cycles()
|
||||||
|
await _test_mini_board()
|
||||||
|
_test_ui_helpers()
|
||||||
|
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
|
||||||
|
quit(1 if _failures else 0)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- helpers
|
||||||
|
|
||||||
|
func _rng(seed_value: int = 1) -> RandomNumberGenerator:
|
||||||
|
var r := RandomNumberGenerator.new()
|
||||||
|
r.seed = seed_value
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
func _board(tables: Array) -> TowerBoard:
|
||||||
|
var b := TowerBoard.new()
|
||||||
|
b.id = "router-test"
|
||||||
|
for t in tables:
|
||||||
|
b.tables.append(t)
|
||||||
|
return b
|
||||||
|
|
||||||
|
|
||||||
|
## A one-entry roll table.
|
||||||
|
func _one(id: String, text: String, effects: String = "") -> RollTable:
|
||||||
|
var t := RollTable.new(id, id.capitalize())
|
||||||
|
var e := TableEntry.new("e1", text)
|
||||||
|
e.effects = effects
|
||||||
|
t.entries.append(e)
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
|
func _roll(b: TowerBoard, id: String, vars: Dictionary = {}) -> Dictionary:
|
||||||
|
var ctx := Roller.new_context(b, _rng(), vars)
|
||||||
|
return Roller.roll(b, id, ctx.rng, 0, {}, ctx)
|
||||||
|
|
||||||
|
|
||||||
|
## Table ids of a tree's steps, in roll order.
|
||||||
|
func _ids(tree: Dictionary) -> Array:
|
||||||
|
var out := []
|
||||||
|
for s: Dictionary in Roller.flatten(tree):
|
||||||
|
out.append(str(s["table_id"]))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
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 _errors(tree: Dictionary) -> Array:
|
||||||
|
var out := []
|
||||||
|
for s: Dictionary in Roller.flatten(tree):
|
||||||
|
for fx: Dictionary in s.get("effects", []):
|
||||||
|
if fx.get("error", false):
|
||||||
|
out.append(str(fx["text"]))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- when / otherwise
|
||||||
|
|
||||||
|
## start --if @str >= 8--> strong, --if @str < 4--> weak, --otherwise--> plain,
|
||||||
|
## --(always)--> after.
|
||||||
|
func _branch_board(str_value: int) -> TowerBoard:
|
||||||
|
var start := _one("start", "Begin", "@str = %d" % str_value)
|
||||||
|
var e := start.entries[0]
|
||||||
|
e.add_pipe("strong")
|
||||||
|
e.set_pipe_when("strong", "@str >= 8")
|
||||||
|
e.add_pipe("weak")
|
||||||
|
e.set_pipe_when("weak", "@str < 4")
|
||||||
|
e.add_pipe("plain")
|
||||||
|
e.set_pipe_otherwise("plain", true)
|
||||||
|
e.add_pipe("after")
|
||||||
|
return _board([start, _one("strong", "Strong"), _one("weak", "Weak"), _one("plain", "Plain"), _one("after", "After")])
|
||||||
|
|
||||||
|
|
||||||
|
func _test_when_otherwise() -> void:
|
||||||
|
_eq(_ids(_roll(_branch_board(10), "start")), ["start", "strong", "after"], "a true condition runs its pipe; otherwise is skipped")
|
||||||
|
_eq(_ids(_roll(_branch_board(2), "start")), ["start", "weak", "after"], "the second condition can be the true one")
|
||||||
|
_eq(_ids(_roll(_branch_board(6), "start")), ["start", "plain", "after"], "no condition true: the otherwise pipe runs")
|
||||||
|
# Two true conditions both run (pipes aren't else-if; use a router for that).
|
||||||
|
var b := _branch_board(10)
|
||||||
|
b.get_table("start").entries[0].set_pipe_when("weak", "@str > 1")
|
||||||
|
_eq(_ids(_roll(b, "start")), ["start", "strong", "weak", "after"], "every true condition runs, in pipe order")
|
||||||
|
# A condition clears otherwise, and otherwise can't be set while there's a condition.
|
||||||
|
var e := TableEntry.new("e1", "x")
|
||||||
|
e.add_pipe("y")
|
||||||
|
e.set_pipe_otherwise("y", true)
|
||||||
|
_check(e.is_otherwise("y"), "otherwise is set")
|
||||||
|
e.set_pipe_when("y", "@a = 1")
|
||||||
|
_check(not e.is_otherwise("y") and e.when_for("y") == "@a = 1", "a condition replaces otherwise")
|
||||||
|
e.set_pipe_otherwise("y", true)
|
||||||
|
_check(not e.is_otherwise("y"), "otherwise is refused while a condition is set")
|
||||||
|
e.remove_pipe("y")
|
||||||
|
_check(e.pipe_when.is_empty() and e.pipe_otherwise.is_empty(), "remove_pipe clears the condition")
|
||||||
|
# Only the pipes taken light up.
|
||||||
|
var lit_e := {}
|
||||||
|
var lit_p := {}
|
||||||
|
Roller.collect_lit(_roll(_branch_board(10), "start"), lit_e, lit_p)
|
||||||
|
_check(lit_p.has(Roller.pipe_key("start", "e1", "strong")) and lit_p.has(Roller.pipe_key("start", "e1", "after")), "taken pipes light")
|
||||||
|
_check(not lit_p.has(Roller.pipe_key("start", "e1", "weak")) and not lit_p.has(Roller.pipe_key("start", "e1", "plain")), "skipped pipes stay dark")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- snapshot
|
||||||
|
|
||||||
|
func _test_snapshot() -> void:
|
||||||
|
# The first pipe's subtree changes @x and @n; the later pipes still see the
|
||||||
|
# values from when the entry was chosen.
|
||||||
|
var start := _one("start", "Begin", "@x = 0; @n = 1")
|
||||||
|
var e := start.entries[0]
|
||||||
|
e.add_pipe("first")
|
||||||
|
e.set_pipe_when("first", "@x = 0")
|
||||||
|
e.add_pipe("second")
|
||||||
|
e.set_pipe_when("second", "@x = 0")
|
||||||
|
e.add_pipe("third")
|
||||||
|
e.set_pipe_count("third", "@n")
|
||||||
|
e.add_pipe("fallback")
|
||||||
|
e.set_pipe_otherwise("fallback", true)
|
||||||
|
var first := _one("first", "First", "@x = 1; @n = 4")
|
||||||
|
var b := _board([start, first, _one("second", "Second"), _one("third", "Third"), _one("fallback", "Fallback")])
|
||||||
|
var vars := {}
|
||||||
|
var ids := _ids(_roll(b, "start", vars))
|
||||||
|
_eq(ids, ["start", "first", "second", "third"], "conditions and counts come from the snapshot, not the changed variables")
|
||||||
|
_eq(_var(vars, "x"), 1, "the first pipe's subtree did change @x")
|
||||||
|
# An otherwise pipe doesn't fire because a when pipe's subtree made the
|
||||||
|
# conditions false afterwards.
|
||||||
|
_check(not ids.has("fallback"), "otherwise reads the snapshot too")
|
||||||
|
# A self-pipe with a counting condition still counts up (the condition is
|
||||||
|
# checked each time the entry is chosen).
|
||||||
|
var link := _one("link", "Link {@k}", "@k += 1")
|
||||||
|
link.entries[0].add_pipe("link")
|
||||||
|
link.entries[0].set_pipe_when("link", "@k < 5")
|
||||||
|
var v2 := {}
|
||||||
|
_eq(_ids(_roll(_board([link]), "link", v2)).size(), 5, "a conditional self-pipe stops when its condition turns false")
|
||||||
|
_eq(_var(v2, "k"), 5, "it ran five times")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- errors
|
||||||
|
|
||||||
|
func _test_errors() -> void:
|
||||||
|
var start := _one("start", "Begin")
|
||||||
|
var e := start.entries[0]
|
||||||
|
e.add_pipe("bad")
|
||||||
|
e.set_pipe_when("bad", "@x + * 2")
|
||||||
|
e.add_pipe("other")
|
||||||
|
e.set_pipe_otherwise("other", true)
|
||||||
|
var tree := _roll(_board([start, _one("bad", "Bad"), _one("other", "Other")]), "start")
|
||||||
|
_eq(_ids(tree), ["start", "other"], "a condition that errors counts as false (so otherwise runs)")
|
||||||
|
var errs := _errors(tree)
|
||||||
|
_check(errs.size() == 1 and str(errs[0]).begins_with("Pipe condition @x + * 2"), "the error shows as an error line on the node: %s" % str(errs))
|
||||||
|
var step: Dictionary = Roller.flatten(tree)[0]
|
||||||
|
_check((step.get("effects", []) as Array).size() == 1, "the error line is in the step's effects")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- routers
|
||||||
|
|
||||||
|
func _router_board() -> TowerBoard:
|
||||||
|
var r := RollTable.create(RollTable.KIND_ROUTER, "route", "Route")
|
||||||
|
r.entries.clear()
|
||||||
|
var cases := [["@species = \"Aslan\"", "Aslan path", "aslan"], ["@str >= 8", "Strong path", "strong"], ["", "Otherwise", "plain"]]
|
||||||
|
for i in cases.size():
|
||||||
|
var c := TableEntry.new("c%d" % (i + 1), cases[i][1])
|
||||||
|
c.when = cases[i][0]
|
||||||
|
c.effects = "@took = \"%s\"" % cases[i][2]
|
||||||
|
c.add_pipe(cases[i][2])
|
||||||
|
r.entries.append(c)
|
||||||
|
return _board([r, _one("aslan", "Aslan"), _one("strong", "Strong"), _one("plain", "Plain")])
|
||||||
|
|
||||||
|
|
||||||
|
func _test_router() -> void:
|
||||||
|
var t := RollTable.create(RollTable.KIND_ROUTER, "r", "Router")
|
||||||
|
_eq(t.kind, "router", "create makes a router")
|
||||||
|
_eq(t.entries.size(), 2, "a new router has two cases")
|
||||||
|
_eq(t.entries[0].text, "if …", "its first case")
|
||||||
|
_check(t.entries[0].when != "" and Expr.check(t.entries[0].when) == "", "the first case has a valid condition")
|
||||||
|
_check(t.entries[1].text == "Otherwise" and t.entries[1].when == "", "the second is Otherwise")
|
||||||
|
_eq(t.otherwise_index(), 1, "otherwise_index")
|
||||||
|
var b := _router_board()
|
||||||
|
var vars := {"species": {"value": "Aslan", "source": ""}, "str": {"value": 10, "source": ""}}
|
||||||
|
var tree := _roll(b, "route", vars)
|
||||||
|
_eq(_ids(tree), ["route", "aslan"], "the first true case wins, even when a later one is true too")
|
||||||
|
_eq(str(tree.get("kind", "")), "router", "the node's kind is router")
|
||||||
|
_eq(tree.get("case"), 0, "the node's case index")
|
||||||
|
_eq(_var(vars, "took"), "aslan", "the case's effects ran")
|
||||||
|
_eq(Formatter.strip_tags(str(tree["summary"])), "Aslan path", "the case's text is the summary")
|
||||||
|
var step: Dictionary = Roller.flatten(tree)[0]
|
||||||
|
_check(step.get("kind") == "router" and step.get("case") == 0 and str(step.get("num", "")) == "", "the step has kind and case, and no rolled number: %s" % str(step))
|
||||||
|
var v2 := {"str": {"value": 9, "source": ""}}
|
||||||
|
_eq(_ids(_roll(b, "route", v2)), ["route", "strong"], "the second case")
|
||||||
|
_eq(_ids(_roll(b, "route", {})), ["route", "plain"], "nothing true: Otherwise")
|
||||||
|
# One action per router.
|
||||||
|
var ctx := Roller.new_context(b, _rng(), {})
|
||||||
|
Roller.roll(b, "route", ctx.rng, 0, {}, ctx)
|
||||||
|
_eq(ctx.actions, 2, "a router is one action (plus the table it pipes to)")
|
||||||
|
# A case condition with an error counts as false and is reported.
|
||||||
|
b.get_table("route").entries[0].when = "@species = = 3 +"
|
||||||
|
var t3 := _roll(b, "route", {})
|
||||||
|
_eq(_ids(t3), ["route", "plain"], "an erroring case is skipped")
|
||||||
|
var errs := _errors(t3)
|
||||||
|
_check(errs.size() == 1 and str(errs[0]).begins_with("Case "), "the case error is on the router node: %s" % str(errs))
|
||||||
|
# Lighting: the matched case is lit.
|
||||||
|
var le := {}
|
||||||
|
var lp := {}
|
||||||
|
Roller.collect_lit(_roll(_router_board(), "route", {}), le, lp)
|
||||||
|
_check(le.has(Roller.entry_key("route", "c3")) and not le.has(Roller.entry_key("route", "c1")), "only the matched case lights")
|
||||||
|
|
||||||
|
|
||||||
|
func _test_no_case() -> void:
|
||||||
|
var b := _router_board()
|
||||||
|
var r := b.get_table("route")
|
||||||
|
r.entries.remove_at(2) # no Otherwise
|
||||||
|
var tree := _roll(b, "route", {})
|
||||||
|
_check(tree.has("stop") and str(tree["summary"]) == Roller.NO_CASE, "nothing matched: the node stops with \"No case matched\"")
|
||||||
|
_eq(str(tree.get("kind", "")), "router", "the stop node is a router node")
|
||||||
|
_eq(_ids(tree), ["route"], "nothing follows")
|
||||||
|
var step: Dictionary = Roller.flatten(tree)[0]
|
||||||
|
_check(step.get("stop", false) and str(step["text"]) == "No case matched", "the step shows it")
|
||||||
|
# A router with no cases at all.
|
||||||
|
r.entries.clear()
|
||||||
|
_check(_roll(b, "route", {}).has("stop"), "an empty router stops")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- file format
|
||||||
|
|
||||||
|
func _test_json() -> void:
|
||||||
|
var b := _router_board()
|
||||||
|
var e := b.get_table("route").entries[1]
|
||||||
|
e.add_pipe("aslan", 2, "who")
|
||||||
|
e.set_pipe_when("aslan", "@str > 9")
|
||||||
|
e.add_pipe("plain")
|
||||||
|
e.set_pipe_otherwise("plain", true)
|
||||||
|
var d := b.get_table("route").to_dict()
|
||||||
|
_eq(str(d.get("kind", "")), "router", "kind is written")
|
||||||
|
var ed: Dictionary = d["entries"][1]
|
||||||
|
_eq(str(ed.get("when", "")), "@str >= 8", "an entry's when is written")
|
||||||
|
_check(not (d["entries"][2] as Dictionary).has("when"), "the Otherwise case has no when")
|
||||||
|
var pipes: Array = ed["pipes"]
|
||||||
|
_eq(pipes[1], {"table": "aslan", "count": 2, "save_as": "who", "when": "@str > 9"}, "a pipe's when is written with its other options")
|
||||||
|
_eq(pipes[2], {"table": "plain", "otherwise": true}, "an otherwise pipe")
|
||||||
|
_eq(pipes[0], "strong", "a plain pipe stays a bare id")
|
||||||
|
var back := RollTable.from_dict(d)
|
||||||
|
var be := back.entries[1]
|
||||||
|
_check(back.kind == "router" and be.when == "@str >= 8" and be.when_for("aslan") == "@str > 9" and be.is_otherwise("plain") and be.count_for("aslan") == 2 and be.save_for("aslan") == "who", "the table round-trips")
|
||||||
|
_eq(back.to_dict(), d, "to_dict(from_dict(d)) == d")
|
||||||
|
# Canonical form keeps them, drops bad values, and drops otherwise next to a when.
|
||||||
|
var raw := {"tables": [{"id": "x", "name": "X", "kind": "router", "entries": [
|
||||||
|
{"id": "a", "text": "A", "when": " @a = 1 ", "pipes": [{"table": "y", "when": "@b", "otherwise": true}, {"table": "z", "otherwise": true}, {"table": "w", "otherwise": "yes"}, {"table": "v", "when": ""}]},
|
||||||
|
{"id": "b", "text": "B", "when": ""}]}]}
|
||||||
|
var c := JsonIO.canonical(raw)
|
||||||
|
var ce: Dictionary = c["tables"][0]["entries"][0]
|
||||||
|
_eq(str(c["tables"][0].get("kind", "")), "router", "canonical keeps kind router")
|
||||||
|
_eq(str(ce.get("when", "")), "@a = 1", "canonical keeps (trimmed) entry when")
|
||||||
|
_check(not (c["tables"][0]["entries"][1] as Dictionary).has("when"), "canonical drops an empty when")
|
||||||
|
_eq(ce["pipes"], [{"table": "y", "when": "@b"}, {"table": "z", "otherwise": true}, {"table": "w"}, {"table": "v"}], "canonical pipe conditions")
|
||||||
|
var text := JsonIO.export_json(b.to_dict())
|
||||||
|
var imp := JsonIO.import_json(text)
|
||||||
|
_check(imp["ok"], "the export imports")
|
||||||
|
var b2 := TowerBoard.new()
|
||||||
|
b2.load_dict(imp["collection"])
|
||||||
|
var e2 := b2.get_table("route").entries[1]
|
||||||
|
_check(e2.when == "@str >= 8" and e2.when_for("aslan") == "@str > 9" and e2.is_otherwise("plain"), "a JSON export round-trips conditions")
|
||||||
|
_eq(JsonIO.pipe_label(JsonIO.pipe_info({"table": "y", "when": "@str >= 8", "count": 2, "save_as": "w"})), "if @str >= 8 ×2 → w", "edge label for a conditional pipe")
|
||||||
|
_eq(JsonIO.pipe_label(JsonIO.pipe_info({"table": "y", "otherwise": true})), "otherwise", "edge label for an otherwise pipe")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- lint
|
||||||
|
|
||||||
|
func _test_lint() -> void:
|
||||||
|
_eq(Roller.lint_pipes(_router_board()), [] as Array[Dictionary], "a clean board has no lint")
|
||||||
|
var b := _router_board()
|
||||||
|
var r := b.get_table("route")
|
||||||
|
# Otherwise first: the cases after it can't be chosen.
|
||||||
|
var other := r.entries[2]
|
||||||
|
r.entries.remove_at(2)
|
||||||
|
r.entries.insert(0, other)
|
||||||
|
r.entries[1].when = "@str >= = 8"
|
||||||
|
var start := _one("start", "Begin")
|
||||||
|
var e := start.entries[0]
|
||||||
|
e.add_pipe("plain")
|
||||||
|
e.set_pipe_otherwise("plain", true)
|
||||||
|
e.add_pipe("strong")
|
||||||
|
e.set_pipe_when("strong", "(((")
|
||||||
|
var lonely := _one("lonely", "Lonely")
|
||||||
|
lonely.entries[0].add_pipe("plain")
|
||||||
|
lonely.entries[0].set_pipe_otherwise("plain", true)
|
||||||
|
var empty := RollTable.create(RollTable.KIND_ROUTER, "empty", "Empty")
|
||||||
|
empty.entries.clear()
|
||||||
|
b.tables.append_array([start, lonely, empty])
|
||||||
|
var lint := Roller.lint_pipes(b)
|
||||||
|
var msgs := {}
|
||||||
|
for item: Dictionary in lint:
|
||||||
|
_check(item.has("table_id") and item.has("entry_id") and item.has("message"), "lint items have table_id, entry_id, message")
|
||||||
|
msgs["%s:%s" % [item["table_id"], item["entry_id"]]] = str(msgs.get("%s:%s" % [item["table_id"], item["entry_id"]], "")) + str(item["message"]) + "|"
|
||||||
|
_check(str(msgs.get("route:c3", "")).contains("Otherwise case isn't last"), "Otherwise case not last: %s" % str(lint))
|
||||||
|
_check(str(msgs.get("route:c1", "")).begins_with("Case @str >= = 8"), "a bad case condition: %s" % str(lint))
|
||||||
|
_check(str(msgs.get("start:e1", "")).contains("Pipe condition (((") and str(msgs.get("start:e1", "")).contains("comes before a conditional pipe"), "a bad pipe condition, and otherwise before when: %s" % str(lint))
|
||||||
|
_check(str(msgs.get("lonely:e1", "")).contains("always runs"), "otherwise with no conditional pipe: %s" % str(lint))
|
||||||
|
_check(str(msgs.get("empty:", "")).contains("no cases"), "a router with no cases: %s" % str(lint))
|
||||||
|
_eq(lint.size(), 6, "six lint items")
|
||||||
|
|
||||||
|
|
||||||
|
func _test_cycles() -> void:
|
||||||
|
# A table whose only pipe back to itself is conditional can finish.
|
||||||
|
var link := _one("link", "Link", "@k += 1")
|
||||||
|
link.entries[0].add_pipe("link")
|
||||||
|
link.entries[0].set_pipe_when("link", "@k < 3")
|
||||||
|
_eq(Roller.endless_cycles(_board([link])), [] as Array[String], "a conditional self-pipe is not an endless cycle")
|
||||||
|
var r := RollTable.create(RollTable.KIND_ROUTER, "r", "R")
|
||||||
|
r.entries[0].add_pipe("r")
|
||||||
|
_eq(Roller.endless_cycles(_board([r])), [] as Array[String], "a router with a case that finishes is fine")
|
||||||
|
r.entries[1].add_pipe("r")
|
||||||
|
_eq(Roller.endless_cycles(_board([r])), ["r"] as Array[String], "a router whose every case loops back is endless")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- mini board
|
||||||
|
|
||||||
|
## The workaround a big board used before routers: the Species choice's
|
||||||
|
## answer sets a chain flag, and two pipes count on it (1 or 0 times). With
|
||||||
|
## lazy counts, the second count was read after the first branch had run, so
|
||||||
|
## a branch that changed @species made both fire. The router version checks
|
||||||
|
## once and picks one case.
|
||||||
|
func _species_board(use_router: bool) -> TowerBoard:
|
||||||
|
var species := RollTable.create(RollTable.KIND_CHOICE, "species", "Species", "pick")
|
||||||
|
species.save_as = "@species"
|
||||||
|
species.entries[0].text = "Aslan"
|
||||||
|
species.entries[1].text = "Human"
|
||||||
|
species.entries.resize(2)
|
||||||
|
# The Aslan branch rewrites @species (e.g. a clan name), which used to
|
||||||
|
# confuse the flag on the second pipe.
|
||||||
|
var aslan := _one("aslan", "Clan training", "@species = \"Aslan (Hkasuao)\"; @path += \"aslan\"")
|
||||||
|
var human := _one("human", "Human schooling", "@path += \"human\"")
|
||||||
|
var sheet := RollTable.create(RollTable.KIND_SHEET, "sheet", "Sheet")
|
||||||
|
sheet.entries[0].text = "{@species}: {@path}"
|
||||||
|
var tables: Array = [species, aslan, human, sheet]
|
||||||
|
for e in species.entries:
|
||||||
|
if use_router:
|
||||||
|
e.add_pipe("route")
|
||||||
|
else:
|
||||||
|
e.effects = "is_aslan = if(@species = \"Aslan\", 1, 0)"
|
||||||
|
e.add_pipe("aslan", "if(@species = \"Aslan\", 1, 0)")
|
||||||
|
e.add_pipe("human", "if(@species = \"Aslan\", 0, 1)")
|
||||||
|
e.add_pipe("sheet")
|
||||||
|
if use_router:
|
||||||
|
var route := RollTable.create(RollTable.KIND_ROUTER, "route", "Which upbringing")
|
||||||
|
route.entries[0].text = "Aslan upbringing"
|
||||||
|
route.entries[0].when = "@species = \"Aslan\""
|
||||||
|
route.entries[0].add_pipe("aslan")
|
||||||
|
route.entries[1].text = "Human upbringing"
|
||||||
|
route.entries[1].add_pipe("human")
|
||||||
|
for c in route.entries:
|
||||||
|
c.add_pipe("sheet")
|
||||||
|
tables.append(route)
|
||||||
|
return _board(tables)
|
||||||
|
|
||||||
|
|
||||||
|
func _pick(index: int) -> Callable:
|
||||||
|
return func(_req: Dictionary) -> Variant: return index
|
||||||
|
|
||||||
|
|
||||||
|
func _test_mini_board() -> void:
|
||||||
|
for use_router in [false, true]:
|
||||||
|
for pick in [0, 1]:
|
||||||
|
var b := _species_board(use_router)
|
||||||
|
var vars := {}
|
||||||
|
var ctx := Roller.new_context(b, _rng(), vars)
|
||||||
|
ctx.prompt = _pick(pick)
|
||||||
|
var tree: Dictionary = await Roller.roll_async(b, "species", ctx)
|
||||||
|
var ids := _ids(tree)
|
||||||
|
var label := "%s, picked %s" % ["router" if use_router else "workaround", "Aslan" if pick == 0 else "Human"]
|
||||||
|
_check(ids.has("aslan") != ids.has("human"), "%s: exactly one branch runs: %s" % [label, str(ids)])
|
||||||
|
_check(ids.has("aslan" if pick == 0 else "human"), "%s: the right branch: %s" % [label, str(ids)])
|
||||||
|
_eq(_var(vars, "path"), "aslan" if pick == 0 else "human", "%s: @path" % label)
|
||||||
|
_check(_errors(tree).is_empty(), "%s: no errors" % label)
|
||||||
|
if use_router:
|
||||||
|
_check(ids.has("route") and ids.has("sheet"), "%s: through the router to the sheet" % label)
|
||||||
|
# The router version lints clean and has no cycles.
|
||||||
|
_eq(Roller.lint_pipes(_species_board(true)), [] as Array[Dictionary], "the router board lints clean")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- UI helpers
|
||||||
|
|
||||||
|
func _test_ui_helpers() -> void:
|
||||||
|
_eq(PipePopover.when_error(""), "", "an empty Only if is fine (always)")
|
||||||
|
_eq(PipePopover.when_error("@str >= 8"), "", "a valid condition")
|
||||||
|
_check(PipePopover.when_error("@str >= = 8") != "", "a bad condition is caught")
|
||||||
|
var r := RollTable.create(RollTable.KIND_ROUTER, "r", "R")
|
||||||
|
_eq(TableCard.case_label(r.entries[0]), "if " + RollTable.ROUTER_DEFAULT_WHEN, "case label")
|
||||||
|
_eq(TableCard.case_label(r.entries[1]), "Otherwise", "Otherwise label")
|
||||||
|
var bad := TableSettingsDialog.apply_settings(r, {"name": "R", "cases": ["@a = = 1", ""]})
|
||||||
|
_check(not bad["ok"] and str(bad["error"]).begins_with("Case 1"), "settings refuse a bad case: %s" % str(bad))
|
||||||
|
var ok := TableSettingsDialog.apply_settings(r, {"name": "R", "cases": ["@a = 1", ""], "card_mode": true, "ranged": true})
|
||||||
|
_check(ok["ok"] and r.entries[0].when == "@a = 1" and not r.card_mode and not r.is_ranged(), "settings set case conditions; no card mode or ranges: %s" % str(ok))
|
||||||
|
_check(TableSettingsDialog.router_hint(["", "@a"]) != "" and TableSettingsDialog.router_hint(["@a", ""]) == "", "router order hint")
|
||||||
|
_eq(TablePreview.kind_line(r), "Router · if / else if / otherwise", "preview kind line")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- checks
|
||||||
|
|
||||||
|
func _eq(got: Variant, want: Variant, what: String) -> void:
|
||||||
|
_check(typeof(got) == typeof(want) and got == want or (got is Array and want is Array and str(got) == str(want)), "%s\n got: %s\n want: %s" % [what, str(got), str(want)])
|
||||||
|
|
||||||
|
|
||||||
|
func _check(ok: bool, what: String) -> void:
|
||||||
|
if not ok:
|
||||||
|
_failures += 1
|
||||||
|
print(" ✗ ", what)
|
||||||
1
tests/test_router.gd.uid
Normal file
1
tests/test_router.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
uid://dhnma5n37bxmw
|
||||||
|
|
@ -435,6 +435,7 @@ const ADD_KINDS := [
|
||||||
["Choice: how many", RollTable.KIND_CHOICE, "number", "How many?"],
|
["Choice: how many", RollTable.KIND_CHOICE, "number", "How many?"],
|
||||||
["Choice: open ended", RollTable.KIND_CHOICE, "text", "What is it?"],
|
["Choice: open ended", RollTable.KIND_CHOICE, "text", "What is it?"],
|
||||||
["Loop", RollTable.KIND_LOOP, "times", "Repeat"],
|
["Loop", RollTable.KIND_LOOP, "times", "Repeat"],
|
||||||
|
["Router: if / else if / otherwise", RollTable.KIND_ROUTER, "", "Router"],
|
||||||
["Variable", RollTable.KIND_VARIABLE, "number", "New variable"],
|
["Variable", RollTable.KIND_VARIABLE, "number", "New variable"],
|
||||||
["Sheet", RollTable.KIND_SHEET, "", "Sheet"],
|
["Sheet", RollTable.KIND_SHEET, "", "Sheet"],
|
||||||
]
|
]
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,10 @@ extends Control
|
||||||
## [[References]] in an entry's text draw as thinner dashed pipes. They come from
|
## [[References]] in an entry's text draw as thinner dashed pipes. They come from
|
||||||
## the text, so they can't be clicked or removed here.
|
## the text, so they can't be clicked or removed here.
|
||||||
##
|
##
|
||||||
|
## Conditional pipes (an "Only if" condition, or "otherwise") have a small
|
||||||
|
## diamond at their source end and a label ("if @str >= 8", "otherwise"), so
|
||||||
|
## the branches of an entry read at a glance.
|
||||||
|
##
|
||||||
## Pipes to or from tables hidden in a collapsed group attach to that group's
|
## Pipes to or from tables hidden in a collapsed group attach to that group's
|
||||||
## card instead (GroupCard.inlet_point / anchor_for). They keep their keys, so
|
## card instead (GroupCard.inlet_point / anchor_for). They keep their keys, so
|
||||||
## they still light up and carry the bead; pipes inside one collapsed group
|
## they still light up and carry the bead; pipes inside one collapsed group
|
||||||
|
|
@ -28,6 +32,7 @@ var _rerouted: Dictionary = {}
|
||||||
## Vector2i -> lit: where pipes leave collapsed group cards, for PortLayer.
|
## Vector2i -> lit: where pipes leave collapsed group cards, for PortLayer.
|
||||||
var group_ports: Dictionary = {}
|
var group_ports: Dictionary = {}
|
||||||
var _label_box: StyleBoxFlat
|
var _label_box: StyleBoxFlat
|
||||||
|
var _lit_label_box: StyleBoxFlat
|
||||||
|
|
||||||
|
|
||||||
func _init() -> void:
|
func _init() -> void:
|
||||||
|
|
@ -36,6 +41,8 @@ func _init() -> void:
|
||||||
size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE)
|
size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE)
|
||||||
_label_box = Style.box(Style.CARD, 7, [6, 1, 6, 2])
|
_label_box = Style.box(Style.CARD, 7, [6, 1, 6, 2])
|
||||||
Style.bordered(_label_box, 1, Style.COPPER_DARK)
|
Style.bordered(_label_box, 1, Style.COPPER_DARK)
|
||||||
|
_lit_label_box = Style.box(Style.LIT, 7, [6, 1, 6, 2])
|
||||||
|
Style.bordered(_lit_label_box, 1, Style.BRASS_DARK)
|
||||||
|
|
||||||
|
|
||||||
func _process(_delta: float) -> void:
|
func _process(_delta: float) -> void:
|
||||||
|
|
@ -59,6 +66,7 @@ func _draw() -> void:
|
||||||
var lit_list: Array = []
|
var lit_list: Array = []
|
||||||
var lit_refs: Array = []
|
var lit_refs: Array = []
|
||||||
var labels: Array = []
|
var labels: Array = []
|
||||||
|
var diamonds: Array = [] # [point, lit, otherwise]
|
||||||
var drawn := {} # endpoints of rerouted pipes already drawn (they overlap)
|
var drawn := {} # endpoints of rerouted pipes already drawn (they overlap)
|
||||||
var build := main.mode == Main.Mode.BUILD
|
var build := main.mode == Main.Mode.BUILD
|
||||||
# Tables hidden in a collapsed group -> that group's card. Their pipes leave
|
# Tables hidden in a collapsed group -> that group's card. Their pipes leave
|
||||||
|
|
@ -100,8 +108,14 @@ func _draw() -> void:
|
||||||
if src_g:
|
if src_g:
|
||||||
var pk := Vector2i(a["pos"])
|
var pk := Vector2i(a["pos"])
|
||||||
group_ports[pk] = bool(group_ports.get(pk, false)) or main.is_entry_lit(t.id, e.id)
|
group_ports[pk] = bool(group_ports.get(pk, false)) or main.is_entry_lit(t.id, e.id)
|
||||||
|
if not is_ref and not rerouted and e.is_conditional(to):
|
||||||
|
diamonds.append([pts, lit, e.is_otherwise(to)])
|
||||||
if lit:
|
if lit:
|
||||||
(lit_refs if is_ref else lit_list).append(pts)
|
(lit_refs if is_ref else lit_list).append(pts)
|
||||||
|
if not is_ref and not rerouted and e.is_conditional(to):
|
||||||
|
var lt := _pipe_tag(e, to)
|
||||||
|
if lt != "":
|
||||||
|
labels.append([pts, lt, true])
|
||||||
continue
|
continue
|
||||||
if rerouted:
|
if rerouted:
|
||||||
var dk := "%s|%s|%s" % [Vector2i(a["pos"]), Vector2i(end), is_ref]
|
var dk := "%s|%s|%s" % [Vector2i(a["pos"]), Vector2i(end), is_ref]
|
||||||
|
|
@ -117,14 +131,16 @@ func _draw() -> void:
|
||||||
if not is_ref and not rerouted:
|
if not is_ref and not rerouted:
|
||||||
var tag := _pipe_tag(e, to)
|
var tag := _pipe_tag(e, to)
|
||||||
if tag != "":
|
if tag != "":
|
||||||
labels.append([pts, tag])
|
labels.append([pts, tag, false])
|
||||||
# Lit pipes go on top so the path of the last roll reads clearly.
|
# Lit pipes go on top so the path of the last roll reads clearly.
|
||||||
for pts in lit_refs:
|
for pts in lit_refs:
|
||||||
_draw_ref(pts, true)
|
_draw_ref(pts, true)
|
||||||
for pts in lit_list:
|
for pts in lit_list:
|
||||||
_draw_pipe(pts, true, false)
|
_draw_pipe(pts, true, false)
|
||||||
|
for d in diamonds:
|
||||||
|
_draw_diamond(d[0], d[1], d[2])
|
||||||
for l in labels:
|
for l in labels:
|
||||||
_draw_tag(l[0], l[1])
|
_draw_tag(l[0], l[1], l[2])
|
||||||
if pulse_key != "" and _paths.has(pulse_key):
|
if pulse_key != "" and _paths.has(pulse_key):
|
||||||
var p := point_along(_paths[pulse_key], pulse_t)
|
var p := point_along(_paths[pulse_key], pulse_t)
|
||||||
var r := 0.75 if Roller.is_ref_key(pulse_key) else 1.0
|
var r := 0.75 if Roller.is_ref_key(pulse_key) else 1.0
|
||||||
|
|
@ -133,9 +149,14 @@ func _draw() -> void:
|
||||||
draw_circle(p, 7.0 * r, Style.PULSE)
|
draw_circle(p, 7.0 * r, Style.PULSE)
|
||||||
|
|
||||||
|
|
||||||
## "×2 → foe" for a pipe with options, or "".
|
## "if @str >= 8 ×2 → foe" / "otherwise" for a pipe with options, or "".
|
||||||
static func _pipe_tag(e: TableEntry, to: String) -> String:
|
static func _pipe_tag(e: TableEntry, to: String) -> String:
|
||||||
var parts := PackedStringArray()
|
var parts := PackedStringArray()
|
||||||
|
var w := e.when_for(to)
|
||||||
|
if w != "":
|
||||||
|
parts.append("if " + (w if w.length() <= 24 else w.substr(0, 23) + "…"))
|
||||||
|
elif e.is_otherwise(to):
|
||||||
|
parts.append("otherwise")
|
||||||
if e.count_expr(to) != "":
|
if e.count_expr(to) != "":
|
||||||
var ex := e.count_expr(to)
|
var ex := e.count_expr(to)
|
||||||
parts.append("×" + (ex if ex.length() <= 18 else ex.substr(0, 17) + "…"))
|
parts.append("×" + (ex if ex.length() <= 18 else ex.substr(0, 17) + "…"))
|
||||||
|
|
@ -146,14 +167,31 @@ static func _pipe_tag(e: TableEntry, to: String) -> String:
|
||||||
return " ".join(parts)
|
return " ".join(parts)
|
||||||
|
|
||||||
|
|
||||||
func _draw_tag(pts: PackedVector2Array, text: String) -> void:
|
func _draw_tag(pts: PackedVector2Array, text: String, lit: bool = false) -> void:
|
||||||
var font := Style.body_bold(true)
|
var font := Style.body_bold(true)
|
||||||
var fs := 12
|
var fs := 12
|
||||||
var w := font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
|
var w := font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
|
||||||
var mid := point_along(pts, 0.5)
|
var mid := point_along(pts, 0.5)
|
||||||
var r := Rect2(mid - Vector2(w / 2.0 + 6.0, 10.0), Vector2(w + 12.0, 19.0))
|
var r := Rect2(mid - Vector2(w / 2.0 + 6.0, 10.0), Vector2(w + 12.0, 19.0))
|
||||||
draw_style_box(_label_box, r)
|
draw_style_box(_lit_label_box if lit else _label_box, r)
|
||||||
draw_string(font, Vector2(r.position.x + 6.0, r.position.y + 14.0), text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, Style.COPPER_DARK)
|
draw_string(font, Vector2(r.position.x + 6.0, r.position.y + 14.0), text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, Style.INK if lit else Style.COPPER_DARK)
|
||||||
|
|
||||||
|
|
||||||
|
## The mark of a conditional pipe: a small diamond near its source end
|
||||||
|
## (hollow for "otherwise", filled for a condition), far enough along that
|
||||||
|
## the branches of one entry have started to fan out.
|
||||||
|
func _draw_diamond(pts: PackedVector2Array, lit: bool, otherwise: bool) -> void:
|
||||||
|
if pts.size() < 2:
|
||||||
|
return
|
||||||
|
var c := point_along(pts, 0.2)
|
||||||
|
var r := 7.5
|
||||||
|
var poly := PackedVector2Array([c + Vector2(0, -r), c + Vector2(r, 0), c + Vector2(0, r), c + Vector2(-r, 0)])
|
||||||
|
var edge := Style.BRASS_DARK if lit else Style.COPPER_DARK
|
||||||
|
draw_colored_polygon(poly, edge)
|
||||||
|
var inner_r := r - 2.5
|
||||||
|
var inner := PackedVector2Array([c + Vector2(0, -inner_r), c + Vector2(inner_r, 0), c + Vector2(0, inner_r), c + Vector2(-inner_r, 0)])
|
||||||
|
var fill := Style.CARD if otherwise else (Style.BRASS if lit else Style.COPPER.lightened(0.25))
|
||||||
|
draw_colored_polygon(inner, fill)
|
||||||
|
|
||||||
|
|
||||||
func _draw_pipe(pts: PackedVector2Array, lit: bool, hovered: bool) -> void:
|
func _draw_pipe(pts: PackedVector2Array, lit: bool, hovered: bool) -> void:
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
class_name PipePopover
|
class_name PipePopover
|
||||||
extends PopupPanel
|
extends PopupPanel
|
||||||
## Build mode: the options for one pipe, opened by clicking it. How many times
|
## Build mode: the options for one pipe, opened by clicking it. How many times
|
||||||
## it rolls, the variable it saves its result as, and Remove.
|
## it rolls, its condition ("Only if", or "Otherwise"), the variable it saves
|
||||||
|
## its result as, and Remove.
|
||||||
|
|
||||||
const SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$"
|
const SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$"
|
||||||
|
|
||||||
|
|
@ -13,6 +14,10 @@ var _title: RichTextLabel
|
||||||
var _count: LineEdit
|
var _count: LineEdit
|
||||||
var _count_msg: Label
|
var _count_msg: Label
|
||||||
var _save: LineEdit
|
var _save: LineEdit
|
||||||
|
var _when: LineEdit
|
||||||
|
var _when_msg: Label
|
||||||
|
var _otherwise: CheckBox
|
||||||
|
var _field_focus: StyleBoxFlat
|
||||||
var _save_ok: StyleBoxFlat
|
var _save_ok: StyleBoxFlat
|
||||||
var _save_bad: StyleBoxFlat
|
var _save_bad: StyleBoxFlat
|
||||||
var _re := RegEx.new()
|
var _re := RegEx.new()
|
||||||
|
|
@ -28,6 +33,7 @@ func setup(p_main: Main) -> void:
|
||||||
add_theme_stylebox_override("panel", sb)
|
add_theme_stylebox_override("panel", sb)
|
||||||
popup_hide.connect(func() -> void:
|
popup_hide.connect(func() -> void:
|
||||||
_commit_save()
|
_commit_save()
|
||||||
|
_commit_when()
|
||||||
if main.board:
|
if main.board:
|
||||||
main.board.pipes.select_key = ""
|
main.board.pipes.select_key = ""
|
||||||
)
|
)
|
||||||
|
|
@ -43,6 +49,7 @@ func setup(p_main: Main) -> void:
|
||||||
var field_focus := Style.bordered(Style.box(Color.WHITE, 5, [7, 3, 7, 3]), 1, Style.COPPER)
|
var field_focus := Style.bordered(Style.box(Color.WHITE, 5, [7, 3, 7, 3]), 1, Style.COPPER)
|
||||||
_save_ok = field_ok
|
_save_ok = field_ok
|
||||||
_save_bad = Style.bordered(Style.box(Color.WHITE, 5, [7, 3, 7, 3]), 1, Style.DANGER)
|
_save_bad = Style.bordered(Style.box(Color.WHITE, 5, [7, 3, 7, 3]), 1, Style.DANGER)
|
||||||
|
_field_focus = field_focus
|
||||||
|
|
||||||
var count_row := HBoxContainer.new()
|
var count_row := HBoxContainer.new()
|
||||||
count_row.add_theme_constant_override("separation", 6)
|
count_row.add_theme_constant_override("separation", 6)
|
||||||
|
|
@ -81,6 +88,55 @@ func setup(p_main: Main) -> void:
|
||||||
_count_msg.hide()
|
_count_msg.hide()
|
||||||
v.add_child(_count_msg)
|
v.add_child(_count_msg)
|
||||||
|
|
||||||
|
var when_row := HBoxContainer.new()
|
||||||
|
when_row.add_theme_constant_override("separation", 6)
|
||||||
|
v.add_child(when_row)
|
||||||
|
var wl := Style.make_label("Only if", Style.body(), 14, Style.MUTED)
|
||||||
|
wl.custom_minimum_size = Vector2(62, 0)
|
||||||
|
when_row.add_child(wl)
|
||||||
|
_when = LineEdit.new()
|
||||||
|
_when.placeholder_text = "always (or e.g. @str >= 8)"
|
||||||
|
_when.size_flags_horizontal = Control.SIZE_EXPAND_FILL
|
||||||
|
_when.max_length = 200
|
||||||
|
_when.tooltip_text = "The pipe runs only when this is true. Every condition on the entry is checked once, before any of its pipes run."
|
||||||
|
_when.add_theme_stylebox_override("normal", field_ok)
|
||||||
|
_when.add_theme_stylebox_override("focus", field_focus)
|
||||||
|
_when.text_changed.connect(func(_s: String) -> void: _check_when())
|
||||||
|
_when.text_submitted.connect(func(_s: String) -> void:
|
||||||
|
_commit_when()
|
||||||
|
hide()
|
||||||
|
)
|
||||||
|
_when.focus_exited.connect(_commit_when)
|
||||||
|
when_row.add_child(_when)
|
||||||
|
_when_msg = Style.make_label("", Style.body(), 12, Style.DANGER_INK)
|
||||||
|
_when_msg.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||||
|
_when_msg.custom_minimum_size = Vector2(260, 0)
|
||||||
|
_when_msg.hide()
|
||||||
|
v.add_child(_when_msg)
|
||||||
|
var other_row := HBoxContainer.new()
|
||||||
|
other_row.add_theme_constant_override("separation", 6)
|
||||||
|
v.add_child(other_row)
|
||||||
|
var pad := Control.new()
|
||||||
|
pad.custom_minimum_size = Vector2(62, 0)
|
||||||
|
other_row.add_child(pad)
|
||||||
|
_otherwise = CheckBox.new()
|
||||||
|
_otherwise.text = "Otherwise"
|
||||||
|
_otherwise.tooltip_text = "Runs only when none of this result's \"Only if\" pipes is true"
|
||||||
|
_otherwise.add_theme_font_override("font", Style.body())
|
||||||
|
_otherwise.add_theme_font_size_override("font_size", 14)
|
||||||
|
_otherwise.add_theme_color_override("font_color", Style.INK)
|
||||||
|
_otherwise.add_theme_color_override("font_hover_color", Style.INK)
|
||||||
|
_otherwise.add_theme_color_override("font_pressed_color", Style.INK)
|
||||||
|
_otherwise.add_theme_color_override("font_hover_pressed_color", Style.INK)
|
||||||
|
_otherwise.add_theme_color_override("font_disabled_color", Style.MUTED)
|
||||||
|
_otherwise.toggled.connect(func(on: bool) -> void:
|
||||||
|
if _entry == null or on == _entry.is_otherwise(_to):
|
||||||
|
return
|
||||||
|
_entry.set_pipe_otherwise(_to, on)
|
||||||
|
main.mark_dirty()
|
||||||
|
)
|
||||||
|
other_row.add_child(_otherwise)
|
||||||
|
|
||||||
var save_row := HBoxContainer.new()
|
var save_row := HBoxContainer.new()
|
||||||
save_row.add_theme_constant_override("separation", 6)
|
save_row.add_theme_constant_override("separation", 6)
|
||||||
v.add_child(save_row)
|
v.add_child(save_row)
|
||||||
|
|
@ -114,6 +170,7 @@ func setup(p_main: Main) -> void:
|
||||||
remove.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN
|
remove.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN
|
||||||
remove.pressed.connect(func() -> void:
|
remove.pressed.connect(func() -> void:
|
||||||
var k := key
|
var k := key
|
||||||
|
_commit_when()
|
||||||
_entry = null
|
_entry = null
|
||||||
hide()
|
hide()
|
||||||
main.remove_pipe(k)
|
main.remove_pipe(k)
|
||||||
|
|
@ -148,6 +205,9 @@ func open(pipe_key: String, at: Vector2) -> void:
|
||||||
_count_msg.hide()
|
_count_msg.hide()
|
||||||
_save.text = _entry.save_for(_to)
|
_save.text = _entry.save_for(_to)
|
||||||
_save.add_theme_stylebox_override("normal", _save_ok)
|
_save.add_theme_stylebox_override("normal", _save_ok)
|
||||||
|
_when.text = _entry.when_for(_to)
|
||||||
|
_otherwise.set_pressed_no_signal(_entry.is_otherwise(_to))
|
||||||
|
_check_when()
|
||||||
main.board.pipes.select_key = pipe_key
|
main.board.pipes.select_key = pipe_key
|
||||||
reset_size()
|
reset_size()
|
||||||
var view := main.get_viewport_rect().size
|
var view := main.get_viewport_rect().size
|
||||||
|
|
@ -179,6 +239,41 @@ static func _count_error(text: String) -> String:
|
||||||
return "" if err == "" else "Not a number or expression: " + err
|
return "" if err == "" else "Not a number or expression: " + err
|
||||||
|
|
||||||
|
|
||||||
|
## "" when `text` is a usable condition (empty means always), else why not.
|
||||||
|
static func when_error(text: String) -> String:
|
||||||
|
var s := text.strip_edges()
|
||||||
|
if s == "":
|
||||||
|
return ""
|
||||||
|
var err := Expr.check(TemplateKit.probe(s))
|
||||||
|
return "" if err == "" else "Not a valid condition: " + err
|
||||||
|
|
||||||
|
|
||||||
|
## Live validation of the Only if field; Otherwise is off while it's filled.
|
||||||
|
func _check_when() -> void:
|
||||||
|
var err := when_error(_when.text)
|
||||||
|
var ok := err == ""
|
||||||
|
_when.add_theme_stylebox_override("normal", _save_ok if ok else _save_bad)
|
||||||
|
_when.add_theme_stylebox_override("focus", _field_focus if ok else _save_bad)
|
||||||
|
_when_msg.text = err
|
||||||
|
_when_msg.visible = not ok
|
||||||
|
var filled := _when.text.strip_edges() != ""
|
||||||
|
_otherwise.disabled = filled
|
||||||
|
if filled:
|
||||||
|
_otherwise.set_pressed_no_signal(false)
|
||||||
|
elif _entry != null:
|
||||||
|
_otherwise.set_pressed_no_signal(_entry.is_otherwise(_to))
|
||||||
|
reset_size()
|
||||||
|
|
||||||
|
|
||||||
|
func _commit_when() -> void:
|
||||||
|
if _entry == null or when_error(_when.text) != "":
|
||||||
|
return
|
||||||
|
var s := _when.text.strip_edges()
|
||||||
|
if s != _entry.when_for(_to):
|
||||||
|
_entry.set_pipe_when(_to, s)
|
||||||
|
main.mark_dirty()
|
||||||
|
|
||||||
|
|
||||||
func _commit_save() -> void:
|
func _commit_save() -> void:
|
||||||
if _entry == null:
|
if _entry == null:
|
||||||
return
|
return
|
||||||
|
|
|
||||||
184
ui/table_card.gd
184
ui/table_card.gd
|
|
@ -8,7 +8,9 @@ extends PanelContainer
|
||||||
## badge, its question and its options (or one Answer row); a loop card shows
|
## 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
|
## 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
|
## 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
|
## template; a router card has a fork icon in place of the die and one row
|
||||||
|
## per case, showing its condition ("if @str >= 8", "Otherwise") with its
|
||||||
|
## outlet. Live text (values, sheets, prompts) is only re-rendered by
|
||||||
## refresh_live(), which Main calls after rolls and edits, never per frame.
|
## refresh_live(), which Main calls after rolls and edits, never per frame.
|
||||||
|
|
||||||
const WIDTH := 256.0
|
const WIDTH := 256.0
|
||||||
|
|
@ -171,6 +173,8 @@ func rebuild() -> void:
|
||||||
continue
|
continue
|
||||||
if table.kind == RollTable.KIND_SHEET:
|
if table.kind == RollTable.KIND_SHEET:
|
||||||
_list_box.add_child(_make_sheet_row(e, build))
|
_list_box.add_child(_make_sheet_row(e, build))
|
||||||
|
elif table.kind == RollTable.KIND_ROUTER and build:
|
||||||
|
_list_box.add_child(_make_case_row(e, i, numw))
|
||||||
else:
|
else:
|
||||||
_list_box.add_child(_make_row(e, i, build, ranged, numw))
|
_list_box.add_child(_make_row(e, i, build, ranged, numw))
|
||||||
_set_row_state(e.id, RowState.LIT if lit else RowState.NORMAL)
|
_set_row_state(e.id, RowState.LIT if lit else RowState.NORMAL)
|
||||||
|
|
@ -341,6 +345,8 @@ func _subtitle() -> String:
|
||||||
RollTable.KIND_CHOICE:
|
RollTable.KIND_CHOICE:
|
||||||
if table.collapsed:
|
if table.collapsed:
|
||||||
return "%d options" % table.entries.size()
|
return "%d options" % table.entries.size()
|
||||||
|
RollTable.KIND_ROUTER:
|
||||||
|
return "if / else if / otherwise · %d %s" % [table.entries.size(), "case" if table.entries.size() == 1 else "cases"]
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -370,6 +376,14 @@ func _make_go_button() -> Button:
|
||||||
icon.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
|
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))
|
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)
|
b.add_child(icon)
|
||||||
|
RollTable.KIND_ROUTER:
|
||||||
|
b.custom_minimum_size = Vector2(38, 32)
|
||||||
|
b.tooltip_text = "Route %s: the first case that's true is chosen" % Formatter.strip_tags(table.name)
|
||||||
|
var fork := Control.new()
|
||||||
|
fork.mouse_filter = MOUSE_FILTER_IGNORE
|
||||||
|
fork.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
|
||||||
|
fork.draw.connect(func() -> void: draw_fork(fork, fork.size / 2.0 + Vector2(0, 0), 8.0, Style.BRASS, 2.2))
|
||||||
|
b.add_child(fork)
|
||||||
RollTable.KIND_SHEET:
|
RollTable.KIND_SHEET:
|
||||||
b.text = "Print"
|
b.text = "Print"
|
||||||
b.add_theme_font_override("font", Style.body_bold(true))
|
b.add_theme_font_override("font", Style.body_bold(true))
|
||||||
|
|
@ -433,6 +447,13 @@ func _make_kind_header(_build: bool) -> Control:
|
||||||
chip.add_child(l)
|
chip.add_child(l)
|
||||||
chip.tooltip_text = err
|
chip.tooltip_text = err
|
||||||
return chip
|
return chip
|
||||||
|
RollTable.KIND_ROUTER:
|
||||||
|
if not _build:
|
||||||
|
return null
|
||||||
|
var rl := Style.make_label("Router · the first true case is chosen", Style.body(true), 12, Style.MUTED)
|
||||||
|
rl.mouse_filter = MOUSE_FILTER_IGNORE
|
||||||
|
rl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||||
|
return rl
|
||||||
RollTable.KIND_VARIABLE:
|
RollTable.KIND_VARIABLE:
|
||||||
var txt := "@%s · %s" % [table.var_name, table.var_type]
|
var txt := "@%s · %s" % [table.var_name, table.var_type]
|
||||||
var l := Style.make_label(txt, Style.body(true), 12, Style.MUTED)
|
var l := Style.make_label(txt, Style.body(true), 12, Style.MUTED)
|
||||||
|
|
@ -441,6 +462,30 @@ func _make_kind_header(_build: bool) -> Control:
|
||||||
return null
|
return null
|
||||||
|
|
||||||
|
|
||||||
|
## A fork: one stem splitting into two branches, each ending in a dot (the
|
||||||
|
## router card's go button). `r` is about half the icon's height.
|
||||||
|
static func draw_fork(ci: CanvasItem, c: Vector2, r: float, color: Color, width: float = 2.0) -> void:
|
||||||
|
var base := c + Vector2(-r, 0)
|
||||||
|
var split := c + Vector2(-r * 0.15, 0)
|
||||||
|
ci.draw_line(base, split, color, width, true)
|
||||||
|
var up := c + Vector2(r * 0.85, -r * 0.75)
|
||||||
|
var down := c + Vector2(r * 0.85, r * 0.75)
|
||||||
|
for tip: Vector2 in [up, down]:
|
||||||
|
var pts := PackedVector2Array()
|
||||||
|
for k in 9:
|
||||||
|
var u := float(k) / 8.0
|
||||||
|
pts.append(split.bezier_interpolate(split + Vector2(r * 0.5, 0), tip - Vector2(r * 0.45, 0), tip, u))
|
||||||
|
ci.draw_polyline(pts, color, width, true)
|
||||||
|
ci.draw_circle(tip, width * 1.25, color)
|
||||||
|
ci.draw_circle(base, width * 0.9, color)
|
||||||
|
|
||||||
|
|
||||||
|
## A router case's condition as shown: "if @str >= 8", or "Otherwise".
|
||||||
|
static func case_label(e: TableEntry) -> String:
|
||||||
|
var w := e.when.strip_edges()
|
||||||
|
return "Otherwise" if w == "" else "if " + w
|
||||||
|
|
||||||
|
|
||||||
## "× @answer", "while @alive = 1", "until @done".
|
## "× @answer", "while @alive = 1", "until @done".
|
||||||
static func loop_rule(t: RollTable) -> String:
|
static func loop_rule(t: RollTable) -> String:
|
||||||
var e := t.loop_expr.strip_edges()
|
var e := t.loop_expr.strip_edges()
|
||||||
|
|
@ -509,7 +554,7 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
|
||||||
r.add_child(_range_edit(e, false))
|
r.add_child(_range_edit(e, false))
|
||||||
h.add_child(r)
|
h.add_child(r)
|
||||||
else:
|
else:
|
||||||
num = Style.make_label("" if fixed else table.num_label(e, index), Style.display(true), 16, Style.MUTED)
|
num = Style.make_label("" if fixed else (str(index + 1) if table.kind == RollTable.KIND_ROUTER else table.num_label(e, index)), Style.display(true), 16, Style.MUTED)
|
||||||
num.custom_minimum_size = Vector2(numw, 0)
|
num.custom_minimum_size = Vector2(numw, 0)
|
||||||
num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
|
num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
|
||||||
num.size_flags_vertical = SIZE_SHRINK_CENTER
|
num.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||||
|
|
@ -581,6 +626,123 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
|
||||||
return row
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
## Build mode: one router case. The first line is its condition (empty means
|
||||||
|
## Otherwise), validated as you type, with move up / down and delete; the
|
||||||
|
## second is its result text with the effects and details toggles.
|
||||||
|
func _make_case_row(e: TableEntry, index: int, numw: float) -> Control:
|
||||||
|
var row := PanelContainer.new()
|
||||||
|
row.mouse_filter = MOUSE_FILTER_PASS
|
||||||
|
row.custom_minimum_size = Vector2(0, 36)
|
||||||
|
var outer := _hbox(4)
|
||||||
|
row.add_child(outer)
|
||||||
|
var num := Style.make_label(str(index + 1), 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_BEGIN
|
||||||
|
outer.add_child(num)
|
||||||
|
var v := _vbox(3)
|
||||||
|
v.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||||
|
outer.add_child(v)
|
||||||
|
|
||||||
|
var top := _hbox(4)
|
||||||
|
v.add_child(top)
|
||||||
|
var if_label := Style.make_label("if", Style.body_bold(true), 14, Style.COPPER_DARK)
|
||||||
|
if_label.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||||
|
top.add_child(if_label)
|
||||||
|
var cond := LineEdit.new()
|
||||||
|
cond.text = e.when
|
||||||
|
cond.placeholder_text = "Otherwise"
|
||||||
|
cond.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||||
|
cond.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||||
|
cond.custom_minimum_size = Vector2(40, 0)
|
||||||
|
cond.add_theme_font_override("font", Style.body_bold(true))
|
||||||
|
cond.add_theme_font_size_override("font_size", 14)
|
||||||
|
cond.add_theme_color_override("font_color", Style.COPPER_DARK)
|
||||||
|
var ok_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Color(Style.BRASS_DARK, 0.4))
|
||||||
|
var focus_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.COPPER)
|
||||||
|
var bad_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.DANGER_INK)
|
||||||
|
var check := func() -> void:
|
||||||
|
var src := TemplateKit.probe(cond.text.strip_edges())
|
||||||
|
var err := Expr.check(src) if src != "" else ""
|
||||||
|
cond.add_theme_stylebox_override("normal", bad_box if err != "" else ok_box)
|
||||||
|
cond.add_theme_stylebox_override("focus", bad_box if err != "" else focus_box)
|
||||||
|
cond.tooltip_text = ("⚠ " + err) if err != "" else "This case is chosen when this is true (cases are checked top to bottom). Leave it empty for Otherwise."
|
||||||
|
if_label.text = "if" if cond.text.strip_edges() != "" else "else"
|
||||||
|
cond.text_changed.connect(func(t: String) -> void:
|
||||||
|
e.when = t.strip_edges()
|
||||||
|
check.call()
|
||||||
|
_update_warning()
|
||||||
|
main.mark_dirty()
|
||||||
|
)
|
||||||
|
check.call()
|
||||||
|
top.add_child(cond)
|
||||||
|
top.add_child(_mini_button("↑", "Move this case up", index > 0, func() -> void: _move_case(index, -1)))
|
||||||
|
top.add_child(_mini_button("↓", "Move this case down", index < table.entries.size() - 1, func() -> void: _move_case(index, 1)))
|
||||||
|
top.add_child(_mini_button("×", "Delete this case", true, func() -> void: main.delete_entry(table.id, e.id)))
|
||||||
|
|
||||||
|
var bottom := _hbox(4)
|
||||||
|
v.add_child(bottom)
|
||||||
|
var edit := LineEdit.new()
|
||||||
|
edit.text = e.text
|
||||||
|
edit.placeholder_text = "Result 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)
|
||||||
|
edit.text_changed.connect(func(t: String) -> void:
|
||||||
|
e.text = t
|
||||||
|
main.mark_dirty()
|
||||||
|
)
|
||||||
|
bottom.add_child(edit)
|
||||||
|
bottom.add_child(_toggle_button("ƒ", "Effects: statements such as @hp -= 1 that run when this case is chosen",
|
||||||
|
_open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(TemplateKit.probe(e.effects)).is_empty()))
|
||||||
|
bottom.add_child(_toggle_button("i", "Details shown when hovering this case",
|
||||||
|
_open_details, e.id, e.details.strip_edges() != "", false))
|
||||||
|
rows[e.id] = row
|
||||||
|
_row_parts[e.id] = {"num": num, "text": null, "entry": e, "index": index}
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
func _mini_button(glyph: String, tip: String, enabled: bool, on_press: Callable) -> Button:
|
||||||
|
var b := Button.new()
|
||||||
|
b.text = glyph
|
||||||
|
b.tooltip_text = tip
|
||||||
|
b.disabled = not enabled
|
||||||
|
b.custom_minimum_size = Vector2(22, 22)
|
||||||
|
b.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||||
|
b.add_theme_font_size_override("font_size", 16 if glyph == "×" else 13)
|
||||||
|
Style.skin_button(b, Style.box(Color(0, 0, 0, 0), 5), Style.box(Color("#e6dfcd"), 5), Style.box(Color("#e6dfcd"), 5), Style.MUTED, Style.DANGER_INK if glyph == "×" else Style.INK)
|
||||||
|
b.add_theme_color_override("font_disabled_color", Color(Style.MUTED, 0.35))
|
||||||
|
b.pressed.connect(on_press)
|
||||||
|
return b
|
||||||
|
|
||||||
|
|
||||||
|
## Moves router case `index` up (-1) or down (+1).
|
||||||
|
func _move_case(index: int, by: int) -> void:
|
||||||
|
var to := index + by
|
||||||
|
if to < 0 or to >= table.entries.size():
|
||||||
|
return
|
||||||
|
var e := table.entries[index]
|
||||||
|
table.entries.remove_at(index)
|
||||||
|
table.entries.insert(to, e)
|
||||||
|
rebuild()
|
||||||
|
main.mark_dirty()
|
||||||
|
|
||||||
|
|
||||||
|
## Adds a router case just before the Otherwise case (or at the end). It
|
||||||
|
## starts as "if false", so it never matches until its condition is written.
|
||||||
|
func add_case() -> void:
|
||||||
|
var e := TableEntry.new(TowerBoard.new_id("e"), "New case")
|
||||||
|
e.when = "false"
|
||||||
|
var at := table.otherwise_index()
|
||||||
|
if at < 0 or at != table.entries.size() - 1:
|
||||||
|
at = table.entries.size()
|
||||||
|
table.entries.insert(at, e)
|
||||||
|
table.collapsed = false
|
||||||
|
rebuild()
|
||||||
|
main.mark_dirty()
|
||||||
|
|
||||||
|
|
||||||
const LOOP_ROWS := ["Each time", "Afterwards"]
|
const LOOP_ROWS := ["Each time", "Afterwards"]
|
||||||
## Longest effects summary shown on a Play-mode chip.
|
## Longest effects summary shown on a Play-mode chip.
|
||||||
const CHIP_CHARS := 30
|
const CHIP_CHARS := 30
|
||||||
|
|
@ -628,6 +790,14 @@ func _row_text(e: TableEntry) -> String:
|
||||||
s = "[b]%s[/b]" % cap
|
s = "[b]%s[/b]" % cap
|
||||||
else:
|
else:
|
||||||
s = "[color=#%s]%s ·[/color] %s" % [muted, cap, s]
|
s = "[color=#%s]%s ·[/color] %s" % [muted, cap, s]
|
||||||
|
elif table.kind == RollTable.KIND_ROUTER:
|
||||||
|
var bad := e.when.strip_edges() != "" and Expr.check(e.when.strip_edges()) != ""
|
||||||
|
var cond := "[color=#%s][b]%s[/b][/color]" % [(Style.DANGER_INK if bad else Style.COPPER_DARK).to_html(false), RichText.plain(case_label(e))]
|
||||||
|
var plain_text := Formatter.strip_tags(e.text).strip_edges()
|
||||||
|
if plain_text == "" or plain_text == case_label(e) or plain_text == "if …" or (plain_text == "Otherwise" and e.when.strip_edges() == ""):
|
||||||
|
s = cond
|
||||||
|
else:
|
||||||
|
s = "%s\n%s" % [cond, s]
|
||||||
elif table.kind == RollTable.KIND_CHOICE and table.choice != "pick":
|
elif table.kind == RollTable.KIND_CHOICE and table.choice != "pick":
|
||||||
if rolled != "":
|
if rolled != "":
|
||||||
s = "[color=#%s]Answer ·[/color] [b]%s[/b]" % [muted, RichText.decorate(rolled)]
|
s = "[color=#%s]Answer ·[/color] [b]%s[/b]" % [muted, RichText.decorate(rolled)]
|
||||||
|
|
@ -993,6 +1163,11 @@ func _make_warning() -> Control:
|
||||||
|
|
||||||
func _update_warning() -> void:
|
func _update_warning() -> void:
|
||||||
var problems := table.range_problems()
|
var problems := table.range_problems()
|
||||||
|
var lines := PackedStringArray()
|
||||||
|
for item: Dictionary in Roller.lint_router(table):
|
||||||
|
lines.append(str(item["message"]))
|
||||||
|
if not lines.is_empty():
|
||||||
|
problems = ("%s\n" % problems if problems != "" else "") + "\n".join(lines)
|
||||||
_warn_label.text = problems
|
_warn_label.text = problems
|
||||||
_warn_panel.visible = problems != ""
|
_warn_panel.visible = problems != ""
|
||||||
|
|
||||||
|
|
@ -1011,6 +1186,11 @@ func _make_footer(ranged: bool) -> Control:
|
||||||
var add := _footer_button(label, Style.INK)
|
var add := _footer_button(label, Style.INK)
|
||||||
add.pressed.connect(func() -> void: main.add_entry(table.id))
|
add.pressed.connect(func() -> void: main.add_entry(table.id))
|
||||||
h.add_child(add)
|
h.add_child(add)
|
||||||
|
elif table.kind == RollTable.KIND_ROUTER:
|
||||||
|
var addc := _footer_button("+ Add case", Style.INK)
|
||||||
|
addc.tooltip_text = "Add a case before Otherwise"
|
||||||
|
addc.pressed.connect(add_case)
|
||||||
|
h.add_child(addc)
|
||||||
var det := _footer_button("Details", Style.INK)
|
var det := _footer_button("Details", Style.INK)
|
||||||
det.tooltip_text = "Details shown when hovering the table's name"
|
det.tooltip_text = "Details shown when hovering the table's name"
|
||||||
if table.details.strip_edges() != "":
|
if table.details.strip_edges() != "":
|
||||||
|
|
|
||||||
|
|
@ -89,6 +89,8 @@ static func kind_line(t: RollTable) -> String:
|
||||||
return "Variable card"
|
return "Variable card"
|
||||||
RollTable.KIND_SHEET:
|
RollTable.KIND_SHEET:
|
||||||
return "Sheet card"
|
return "Sheet card"
|
||||||
|
RollTable.KIND_ROUTER:
|
||||||
|
return "Router · if / else if / otherwise"
|
||||||
var s := "Roll table · " + t.dice_label()
|
var s := "Roll table · " + t.dice_label()
|
||||||
return s + " · deck" if t.card_mode else s
|
return s + " · deck" if t.card_mode else s
|
||||||
|
|
||||||
|
|
@ -115,6 +117,8 @@ static func summary_line(t: RollTable) -> String:
|
||||||
return "Repeats %s times" % (e if e != "" else "?")
|
return "Repeats %s times" % (e if e != "" else "?")
|
||||||
RollTable.KIND_VARIABLE:
|
RollTable.KIND_VARIABLE:
|
||||||
return "Holds @%s (%s)" % [t.var_name, t.var_type]
|
return "Holds @%s (%s)" % [t.var_name, t.var_type]
|
||||||
|
RollTable.KIND_ROUTER:
|
||||||
|
return "Goes on with the first case that's true"
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -130,6 +134,11 @@ static func _row(t: RollTable, e: TableEntry, index: int) -> Control:
|
||||||
col.add_theme_constant_override("separation", 0)
|
col.add_theme_constant_override("separation", 0)
|
||||||
col.size_flags_horizontal = Control.SIZE_EXPAND_FILL
|
col.size_flags_horizontal = Control.SIZE_EXPAND_FILL
|
||||||
col.mouse_filter = Control.MOUSE_FILTER_IGNORE
|
col.mouse_filter = Control.MOUSE_FILTER_IGNORE
|
||||||
|
if t.kind == RollTable.KIND_ROUTER:
|
||||||
|
var cond := _label(TableCard.case_label(e), 12, Style.COPPER_DARK, true, true)
|
||||||
|
cond.max_lines_visible = 2
|
||||||
|
cond.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
|
||||||
|
col.add_child(cond)
|
||||||
var tx := Formatter.strip_tags(e.text).strip_edges()
|
var tx := Formatter.strip_tags(e.text).strip_edges()
|
||||||
var text := _label(tx if tx != "" else "(empty)", 13, Style.INK, false, true)
|
var text := _label(tx if tx != "" else "(empty)", 13, Style.INK, false, true)
|
||||||
text.max_lines_visible = 2
|
text.max_lines_visible = 2
|
||||||
|
|
@ -155,6 +164,8 @@ static func row_label(t: RollTable, e: TableEntry, index: int) -> String:
|
||||||
return str(index + 1) if t.choice == "pick" else "Answer"
|
return str(index + 1) if t.choice == "pick" else "Answer"
|
||||||
RollTable.KIND_LOOP:
|
RollTable.KIND_LOOP:
|
||||||
return "Each" if index == 0 else "After"
|
return "Each" if index == 0 else "After"
|
||||||
|
RollTable.KIND_ROUTER:
|
||||||
|
return str(index + 1)
|
||||||
return t.num_label(e, index)
|
return t.num_label(e, index)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -50,6 +50,9 @@ var _var_type := "number"
|
||||||
var _initial: LineEdit
|
var _initial: LineEdit
|
||||||
var _template: TextEdit
|
var _template: TextEdit
|
||||||
var _template_preview: RichTextLabel
|
var _template_preview: RichTextLabel
|
||||||
|
## Router cards: one condition field per case, in order.
|
||||||
|
var _cases: Array[LineEdit] = []
|
||||||
|
var _case_note: Label
|
||||||
|
|
||||||
const TITLES := {
|
const TITLES := {
|
||||||
RollTable.KIND_ROLL: "Table settings",
|
RollTable.KIND_ROLL: "Table settings",
|
||||||
|
|
@ -57,6 +60,7 @@ const TITLES := {
|
||||||
RollTable.KIND_LOOP: "Loop settings",
|
RollTable.KIND_LOOP: "Loop settings",
|
||||||
RollTable.KIND_VARIABLE: "Variable settings",
|
RollTable.KIND_VARIABLE: "Variable settings",
|
||||||
RollTable.KIND_SHEET: "Sheet settings",
|
RollTable.KIND_SHEET: "Sheet settings",
|
||||||
|
RollTable.KIND_ROUTER: "Router settings",
|
||||||
}
|
}
|
||||||
const CHOICE_LABELS := ["Which option", "How many", "Open ended"]
|
const CHOICE_LABELS := ["Which option", "How many", "Open ended"]
|
||||||
const LOOP_LABELS := ["Times", "While", "Until"]
|
const LOOP_LABELS := ["Times", "While", "Until"]
|
||||||
|
|
@ -275,6 +279,11 @@ func settings() -> Dictionary:
|
||||||
s["initial"] = _initial.text.strip_edges()
|
s["initial"] = _initial.text.strip_edges()
|
||||||
RollTable.KIND_SHEET:
|
RollTable.KIND_SHEET:
|
||||||
s["template"] = _template.text
|
s["template"] = _template.text
|
||||||
|
RollTable.KIND_ROUTER:
|
||||||
|
var cases: Array = []
|
||||||
|
for le in _cases:
|
||||||
|
cases.append(le.text.strip_edges())
|
||||||
|
s["cases"] = cases
|
||||||
return s
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -369,6 +378,23 @@ func _build_kind() -> void:
|
||||||
pbox.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.05), 7, [10, 7, 10, 7]))
|
pbox.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.05), 7, [10, 7, 10, 7]))
|
||||||
pbox.add_child(_template_preview)
|
pbox.add_child(_template_preview)
|
||||||
box.add_child(pbox)
|
box.add_child(pbox)
|
||||||
|
RollTable.KIND_ROUTER:
|
||||||
|
box.add_child(section("Cases (if / else if / otherwise)"))
|
||||||
|
box.add_child(note("Checked top to bottom when the chain arrives; the first true case is chosen, and its effects, text and pipes run like a rolled result. An empty condition is Otherwise: it always matches, so keep it last. Add, remove and reorder cases on the card."))
|
||||||
|
for i in table.entries.size():
|
||||||
|
var e := table.entries[i]
|
||||||
|
var le := LineEdit.new()
|
||||||
|
le.text = e.when
|
||||||
|
le.placeholder_text = "Otherwise (always)"
|
||||||
|
style_line_edit(le)
|
||||||
|
le.text_changed.connect(func(_t: String) -> void: _refresh())
|
||||||
|
_cases.append(le)
|
||||||
|
var label := Formatter.strip_tags(e.text).strip_edges()
|
||||||
|
box.add_child(field("Case %d%s" % [i + 1, (" · " + label) if label != "" else ""], le))
|
||||||
|
if table.entries.is_empty():
|
||||||
|
box.add_child(note("This router has no cases yet: add some on the card."))
|
||||||
|
_case_note = note("", Style.WARN_INK)
|
||||||
|
box.add_child(_case_note)
|
||||||
_:
|
_:
|
||||||
box.free() # roll tables have no kind fields
|
box.free() # roll tables have no kind fields
|
||||||
return
|
return
|
||||||
|
|
@ -409,6 +435,13 @@ func _refresh_kind() -> void:
|
||||||
var ctx := Roller.live_context(table_board(), _live_vars())
|
var ctx := Roller.live_context(table_board(), _live_vars())
|
||||||
_template_preview.text = RichText.decorate(TextExpander.render(_template.text, ctx)) if _template.text.strip_edges() != "" \
|
_template_preview.text = RichText.decorate(TextExpander.render(_template.text, ctx)) if _template.text.strip_edges() != "" \
|
||||||
else "[color=#69726b]Preview appears here.[/color]"
|
else "[color=#69726b]Preview appears here.[/color]"
|
||||||
|
RollTable.KIND_ROUTER:
|
||||||
|
var cases: Array = s["cases"]
|
||||||
|
for i in _cases.size():
|
||||||
|
_mark(_cases[i], when_error(str(cases[i])) == "")
|
||||||
|
var hint := router_hint(cases)
|
||||||
|
_case_note.text = hint
|
||||||
|
_case_note.visible = hint != ""
|
||||||
# The ranged/card-mode sections only apply to roll tables and pick choices.
|
# 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")
|
var rolls := table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and _choice == "pick")
|
||||||
_type_box.visible = rolls
|
_type_box.visible = rolls
|
||||||
|
|
@ -500,6 +533,12 @@ static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray:
|
||||||
out.append("The loop needs a count or a condition.")
|
out.append("The loop needs a count or a condition.")
|
||||||
elif Expr.check(src) != "":
|
elif Expr.check(src) != "":
|
||||||
out.append("Loop rule: " + Expr.check(src))
|
out.append("Loop rule: " + Expr.check(src))
|
||||||
|
RollTable.KIND_ROUTER:
|
||||||
|
var cases: Array = s.get("cases", [])
|
||||||
|
for i in cases.size():
|
||||||
|
var err := when_error(str(cases[i]))
|
||||||
|
if err != "":
|
||||||
|
out.append("Case %d: %s" % [i + 1, err])
|
||||||
RollTable.KIND_VARIABLE:
|
RollTable.KIND_VARIABLE:
|
||||||
var n := TemplateKit.probe(str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@"))
|
var n := TemplateKit.probe(str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@"))
|
||||||
if _re(VAR_PATTERN).search(n) == null:
|
if _re(VAR_PATTERN).search(n) == null:
|
||||||
|
|
@ -510,6 +549,20 @@ static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray:
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
## "" when a router case condition is usable (empty is Otherwise), else why not.
|
||||||
|
static func when_error(src: String) -> String:
|
||||||
|
src = TemplateKit.probe(src.strip_edges())
|
||||||
|
return Expr.check(src) if src != "" else ""
|
||||||
|
|
||||||
|
|
||||||
|
## A hint about the order of router cases (an Otherwise that isn't last), or "".
|
||||||
|
static func router_hint(cases: Array) -> String:
|
||||||
|
for i in cases.size():
|
||||||
|
if str(cases[i]).strip_edges() == "" and i < cases.size() - 1:
|
||||||
|
return "Case %d is Otherwise, so the cases after it can never be chosen. Move it to the end." % (i + 1)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
static func _initial_error(src: String, type: String) -> String:
|
static func _initial_error(src: String, type: String) -> String:
|
||||||
src = TemplateKit.probe(src.strip_edges())
|
src = TemplateKit.probe(src.strip_edges())
|
||||||
if src == "":
|
if src == "":
|
||||||
|
|
@ -573,6 +626,10 @@ static func _apply_kind(t: RollTable, s: Dictionary) -> void:
|
||||||
if RollTable.VAR_TYPES.has(vt):
|
if RollTable.VAR_TYPES.has(vt):
|
||||||
t.var_type = vt
|
t.var_type = vt
|
||||||
t.initial = str(s.get("initial", t.initial)).strip_edges()
|
t.initial = str(s.get("initial", t.initial)).strip_edges()
|
||||||
|
RollTable.KIND_ROUTER:
|
||||||
|
var cases: Array = s.get("cases", [])
|
||||||
|
for i in mini(cases.size(), t.entries.size()):
|
||||||
|
t.entries[i].when = str(cases[i]).strip_edges()
|
||||||
RollTable.KIND_SHEET:
|
RollTable.KIND_SHEET:
|
||||||
if s.has("template"):
|
if s.has("template"):
|
||||||
if t.entries.is_empty():
|
if t.entries.is_empty():
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue