TableTower/core/effects.gd
RobinFiredrake 86d1b214c3 Dynamic pick options, show_if and indirect @[expr] names
Pick choice cards can take their options from variables (options_from:
@prefix_* or a @list, filtered by options_where with option, option_label
and option_value bound). A Chosen entry runs for whichever dynamic option
is picked; fixed entries stay as extras, listed first. Random weighs each
dynamic option as the Chosen entry and fixed ones by weight. Any pick
option can have show_if, which hides it from the pop-up and from Random;
with nothing offered the node stops with "No options available".

@[expr] reads or writes the variable named by expr in expressions,
effects (including reset) and text ({@[expr]}); bad computed names are
effect errors. JSON round trip, lint_options in lint_pipes, choice
pop-up value badges and previews, card and settings UI, docs, demo board
(Spend a find) and tests/test_options.gd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 18:55:38 -06:00

299 lines
11 KiB
GDScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class_name Effects
extends RefCounted
## Effect statements on entries (docs/LOGIC.md §5.2): one per line or
## separated by ";".
##
## @str = 2d6 set
## @terms += 1 add a number, or append ", item" to text/list if absent
## @credits -= 1000 subtract a number, or remove the item from text/list
## @age *= 2 multiply (/= divides, rounding down)
## reset @name back to the variable card's starting value, or deleted
## reset @skill_* every variable with that prefix
## @[expr] += 1 the variable named by expr (indirect), e.g.
## @[option] += 1, reset @["skill_" + option]
##
## A target without "@" is a chain variable. Unset counts as 0 (or "" when the
## value added is text). run() never stops on a bad statement: it logs an error
## line and carries on.
const OPS := ["+=", "-=", "*=", "/=", "="]
static var _stmt_re: RegEx = null
static var _reset_re: RegEx = null
## Splits effect text into statements: lines, and ";" outside quotes. Empty
## statements are dropped.
static func split(text: String) -> Array[String]:
var out: Array[String] = []
var cur := ""
var quote := ""
for c in text:
if quote != "":
cur += c
if c == quote:
quote = ""
elif c == "\"" or c == "'":
quote = c
cur += c
elif c == ";" or c == "\n":
if cur.strip_edges() != "":
out.append(cur.strip_edges())
cur = ""
else:
cur += c
if cur.strip_edges() != "":
out.append(cur.strip_edges())
return out
## Parses one statement. Returns {src, op ("=", "+=", "-=", "*=", "/=" or
## "reset"), target ("@name", "name", or "@prefix_*" for reset), expr} or
## {src, error}.
static func parse_statement(src: String) -> Dictionary:
_compile()
var s := src.strip_edges()
var ind := _parse_indirect(s)
if not ind.is_empty():
return ind
var m := _reset_re.search(s)
if m != null:
var target := "@" + m.get_string(1).to_lower() + m.get_string(2)
return {"src": s, "op": "reset", "target": target, "expr": ""}
if s.to_lower().begins_with("reset"):
return {"src": s, "error": "Write reset @name or reset @prefix_*"}
m = _stmt_re.search(s)
if m == null:
return {"src": s, "error": "Not a statement; try @name = value"}
var t := m.get_string(1)
if t.begins_with("@"):
t = t.to_lower()
var expr := m.get_string(3).strip_edges()
if expr == "":
return {"src": s, "error": "Nothing after %s" % m.get_string(2)}
return {"src": s, "op": m.get_string(2), "target": t, "expr": expr}
## An indirect statement ("@[expr] op value" or "reset @[expr]"), parsed into
## the same shape with "target_expr" (the expression naming the variable) and
## target "@[expr]"; {} when `s` isn't one.
static func _parse_indirect(s: String) -> Dictionary:
var at := -1
var is_reset := false
if s.begins_with("@["):
at = 1
elif s.to_lower().begins_with("reset") and s.substr(5).strip_edges().begins_with("@["):
is_reset = true
at = s.find("@[") + 1
if at < 0:
return {}
var close := Expr.bracket_end(s, at)
if close < 0:
return {"src": s, "error": "@[ is missing its closing ]"}
var inner := s.substr(at + 1, close - at - 1).strip_edges()
if inner == "":
return {"src": s, "error": "Write an expression inside @[ ], e.g. @[option]"}
var target := s.substr(at - 1, close - at + 2)
var rest := s.substr(close + 1).strip_edges()
if is_reset:
if rest != "":
return {"src": s, "error": "Write reset @[expr]"}
return {"src": s, "op": "reset", "target": target, "target_expr": inner, "expr": ""}
for op: String in ["+=", "-=", "*=", "/=", "="]:
if rest.begins_with(op) and not (op == "=" and rest.begins_with("==")):
var expr := rest.substr(op.length()).strip_edges()
if expr == "":
return {"src": s, "error": "Nothing after %s" % op}
return {"src": s, "op": op, "target": target, "target_expr": inner, "expr": expr}
return {"src": s, "error": "Not a statement; try @[name] = value"}
## The real target of a statement: its "target", or for an indirect one
## "@name" from its expression. {"target", "error"}: the error is set when
## the expression fails or doesn't give a valid name.
static func resolve_target(st: Dictionary, ctx: RollContext) -> Dictionary:
if not st.has("target_expr"):
return {"target": st["target"], "error": ""}
var r := Expr.evaluate(str(st["target_expr"]), ctx)
if r["error"] != "":
return {"target": "", "error": str(r["error"])}
var nm := Expr.indirect_name(r["value"])
if nm["error"] != "":
return {"target": "", "error": str(nm["error"])}
return {"target": "@" + str(nm["name"]), "error": ""}
## Problems in effect text for the Build-mode editor: Array of {index (0-based
## statement number), src, error}. Empty when everything parses.
static func validate(text: String) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var list := split(text)
for k in list.size():
var st := parse_statement(list[k])
var err := str(st.get("error", ""))
if err == "" and st.has("target_expr"):
err = Expr.check(st["target_expr"])
if err == "" and st["op"] != "reset":
err = Expr.check(st["expr"])
if err != "":
out.append({"index": k, "src": list[k], "error": err})
return out
## Runs every statement against the context. Returns the log, one line per
## statement: Array of {"text": String, "error": bool (only when true)}.
## `source_id` is stored as the variables' source table.
static func run(text: String, ctx: RollContext, source_id: String = "") -> Array[Dictionary]:
var log: Array[Dictionary] = []
if text.strip_edges() == "":
return log
for src in split(text):
var st := parse_statement(src)
if st.has("error"):
log.append({"text": "%s: %s" % [src, st["error"]], "error": true})
continue
if st.has("target_expr"):
var rt := resolve_target(st, ctx)
if rt["error"] != "":
log.append({"text": "%s: %s" % [src, rt["error"]], "error": true})
continue
st["target"] = rt["target"]
if st["op"] == "reset":
log.append(_reset(st["target"], ctx))
else:
log.append(_assign(st, ctx, source_id))
return log
## Plain log lines (errors included), for copying and history.
static func log_text(log: Array) -> PackedStringArray:
var out := PackedStringArray()
for l: Variant in log:
out.append(str((l as Dictionary).get("text", "")) if l is Dictionary else str(l))
return out
static func _assign(st: Dictionary, ctx: RollContext, source_id: String) -> Dictionary:
var target: String = st["target"]
var op: String = st["op"]
var r := Expr.evaluate(st["expr"], ctx)
if r["error"] != "":
return {"text": "%s: %s" % [st["src"], r["error"]], "error": true}
var rhs: Variant = Expr.normalize(r["value"])
var label := ctx.display_name(target) if target.begins_with("@") else target
var cur: Variant = ctx.get_value(target)
var type := ""
if target.begins_with("@"):
var card := ctx.declared(target)
if card != null:
type = card.var_type
var as_list := false
if op == "+=" or op == "-=":
if type == "text" or type == "list":
as_list = true
elif type == "number":
as_list = false
else:
as_list = not Expr.is_number(rhs) or (cur != null and not Expr.is_number(cur) and str(cur).strip_edges() != "")
var value: Variant
var line: String
match op:
"=":
if type == "number" and not Expr.is_number(rhs):
return {"text": "%s: %s is a number, not \"%s\"" % [st["src"], label, Expr.format_value(rhs)], "error": true}
value = Expr.to_value(rhs) if type == "number" else rhs
line = "%s = %s" % [label, _shown(value)]
"+=", "-=":
if as_list:
var items := Expr.list_items(cur if cur != null else "")
var item := Expr.format_value(rhs).strip_edges()
var at := -1
for k in items.size():
if items[k].to_lower() == item.to_lower():
at = k
break
if op == "+=" and at < 0 and item != "":
items.append(item)
elif op == "-=" and at >= 0:
items.remove_at(at)
value = ", ".join(items)
line = "%s %s %s → %s" % [label, "+" if op == "+=" else "−", item, _shown(value)]
else:
var a: Variant = Expr.to_value(cur) if cur != null and str(cur).strip_edges() != "" else 0
var b: Variant = Expr.to_value(rhs)
if not Expr.is_number(a) or not Expr.is_number(b):
return {"text": "%s: %s needs a number" % [st["src"], label], "error": true}
var delta: Variant = b if op == "+=" else -b
value = Expr.normalize(a + delta)
line = "%s %s → %s" % [label, _signed(delta), _shown(value)]
"*=", "/=":
var a2: Variant = Expr.to_value(cur) if cur != null and str(cur).strip_edges() != "" else 0
var b2: Variant = Expr.to_value(rhs)
if not Expr.is_number(a2) or not Expr.is_number(b2):
return {"text": "%s: %s needs a number" % [st["src"], label], "error": true}
if op == "*=":
value = Expr.normalize(a2 * b2)
line = "%s ×%s → %s" % [label, Expr.format_value(b2), _shown(value)]
else:
if b2 == 0:
return {"text": "%s: can't divide by 0" % st["src"], "error": true}
value = floori(float(a2) / float(b2))
line = "%s ÷%s → %s" % [label, Expr.format_value(b2), _shown(value)]
ctx.save(target, value, source_id)
return {"text": line}
static func _reset(target: String, ctx: RollContext) -> Dictionary:
if target.ends_with("*"):
var prefix := target.trim_prefix("@").trim_suffix("*")
var names := {}
for n: String in ctx.persistent_vars:
if n.begins_with(prefix):
names[n] = true
for n in ctx.declared_names():
if n.begins_with(prefix):
names[n] = true
var errors := PackedStringArray()
for n: String in names:
var r := reset_one(n, ctx)
if r != "":
errors.append(r)
if not errors.is_empty():
return {"text": "reset %s: %s" % [target, "; ".join(errors)], "error": true}
return {"text": "Reset %s (%d)" % [target, names.size()]}
var name := target.trim_prefix("@")
var err := reset_one(name, ctx)
if err != "":
return {"text": "reset %s: %s" % [target, err], "error": true}
var v: Variant = ctx.get_value("@" + name)
if v == null:
return {"text": "Reset %s (cleared)" % ctx.display_name(name)}
return {"text": "Reset %s → %s" % [ctx.display_name(name), _shown(v)]}
## Resets one board variable (no "@"): a declared one goes back to its starting
## value, an undeclared one is deleted. Returns an error message or "".
static func reset_one(name: String, ctx: RollContext) -> String:
var card := ctx.declared(name)
if card == null:
ctx.erase("@" + name)
return ""
var r := card.initial_value(ctx)
ctx.save("@" + name, r["value"], card.id)
return str(r["error"])
static func _shown(v: Variant) -> String:
var s := Expr.format_value(v)
return s if s != "" else "(none)"
static func _signed(v: Variant) -> String:
var s := Expr.format_value(v)
return s if s.begins_with("-") else "+" + s
static func _compile() -> void:
if _stmt_re == null:
_stmt_re = RegEx.create_from_string("^(@?[A-Za-z_][A-Za-z0-9_]*)\\s*(\\+=|-=|\\*=|/=|=)(?!=)\\s*(.*)$")
_reset_re = RegEx.create_from_string("^(?i:reset)\\s+@([A-Za-z_][A-Za-z0-9_]*|)(\\*?)\\s*$")