TableTower/core/effects.gd
RobinFiredrake 85b8a99ef5 Logic cards engine: expressions, effects, choice/loop/variable/sheet cards, coroutine roller
- Expr: @vars, chain vars, dice tokens, dm/has/count, lone = as ==, errors as values, parse cache
- Effects: = += -= *= /= and reset (with prefix), number vs list semantics, logs, validation
- RollTable kinds and per-kind fields with factories; expression dice with end clamping
- TableEntry effects and expression pipe counts; JSON round trip through JsonIO
- TextExpander: {@prefix_*}, {= expr}, number display, expand_async and live render()
- Roller: coroutine with an explicit work stack, prompts for choice cards, loops,
  10,000-action limit, partial tree on ctx.root, iterative flatten/collect_lit
- Variables keep numbers as numbers through StateStore
- Main: awaits the roll with a default (headless) prompt hook, iterative playback,
  long chains show at once

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

237 lines
8.2 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
##
## A target without "@" is a chain variable. Unset counts as 0 (or "" when the
## value added is text). run() never stops on a bad statement: it logs an error
## line and carries on.
const OPS := ["+=", "-=", "*=", "/=", "="]
static var _stmt_re: RegEx = null
static var _reset_re: RegEx = null
## Splits effect text into statements: lines, and ";" outside quotes. Empty
## statements are dropped.
static func split(text: String) -> Array[String]:
var out: Array[String] = []
var cur := ""
var quote := ""
for c in text:
if quote != "":
cur += c
if c == quote:
quote = ""
elif c == "\"" or c == "'":
quote = c
cur += c
elif c == ";" or c == "\n":
if cur.strip_edges() != "":
out.append(cur.strip_edges())
cur = ""
else:
cur += c
if cur.strip_edges() != "":
out.append(cur.strip_edges())
return out
## Parses one statement. Returns {src, op ("=", "+=", "-=", "*=", "/=" or
## "reset"), target ("@name", "name", or "@prefix_*" for reset), expr} or
## {src, error}.
static func parse_statement(src: String) -> Dictionary:
_compile()
var s := src.strip_edges()
var m := _reset_re.search(s)
if m != null:
var target := "@" + m.get_string(1).to_lower() + m.get_string(2)
return {"src": s, "op": "reset", "target": target, "expr": ""}
if s.to_lower().begins_with("reset"):
return {"src": s, "error": "Write reset @name or reset @prefix_*"}
m = _stmt_re.search(s)
if m == null:
return {"src": s, "error": "Not a statement; try @name = value"}
var t := m.get_string(1)
if t.begins_with("@"):
t = t.to_lower()
var expr := m.get_string(3).strip_edges()
if expr == "":
return {"src": s, "error": "Nothing after %s" % m.get_string(2)}
return {"src": s, "op": m.get_string(2), "target": t, "expr": expr}
## Problems in effect text for the Build-mode editor: Array of {index (0-based
## statement number), src, error}. Empty when everything parses.
static func validate(text: String) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var list := split(text)
for k in list.size():
var st := parse_statement(list[k])
var err := str(st.get("error", ""))
if err == "" and st["op"] != "reset":
err = Expr.check(st["expr"])
if err != "":
out.append({"index": k, "src": list[k], "error": err})
return out
## Runs every statement against the context. Returns the log, one line per
## statement: Array of {"text": String, "error": bool (only when true)}.
## `source_id` is stored as the variables' source table.
static func run(text: String, ctx: RollContext, source_id: String = "") -> Array[Dictionary]:
var log: Array[Dictionary] = []
if text.strip_edges() == "":
return log
for src in split(text):
var st := parse_statement(src)
if st.has("error"):
log.append({"text": "%s: %s" % [src, st["error"]], "error": true})
continue
if st["op"] == "reset":
log.append(_reset(st["target"], ctx))
else:
log.append(_assign(st, ctx, source_id))
return log
## Plain log lines (errors included), for copying and history.
static func log_text(log: Array) -> PackedStringArray:
var out := PackedStringArray()
for l: Variant in log:
out.append(str((l as Dictionary).get("text", "")) if l is Dictionary else str(l))
return out
static func _assign(st: Dictionary, ctx: RollContext, source_id: String) -> Dictionary:
var target: String = st["target"]
var op: String = st["op"]
var r := Expr.evaluate(st["expr"], ctx)
if r["error"] != "":
return {"text": "%s: %s" % [st["src"], r["error"]], "error": true}
var rhs: Variant = Expr.normalize(r["value"])
var label := ctx.display_name(target) if target.begins_with("@") else target
var cur: Variant = ctx.get_value(target)
var type := ""
if target.begins_with("@"):
var card := ctx.declared(target)
if card != null:
type = card.var_type
var as_list := false
if op == "+=" or op == "-=":
if type == "text" or type == "list":
as_list = true
elif type == "number":
as_list = false
else:
as_list = not Expr.is_number(rhs) or (cur != null and not Expr.is_number(cur) and str(cur).strip_edges() != "")
var value: Variant
var line: String
match op:
"=":
if type == "number" and not Expr.is_number(rhs):
return {"text": "%s: %s is a number, not \"%s\"" % [st["src"], label, Expr.format_value(rhs)], "error": true}
value = Expr.to_value(rhs) if type == "number" else rhs
line = "%s = %s" % [label, _shown(value)]
"+=", "-=":
if as_list:
var items := Expr.list_items(cur if cur != null else "")
var item := Expr.format_value(rhs).strip_edges()
var at := -1
for k in items.size():
if items[k].to_lower() == item.to_lower():
at = k
break
if op == "+=" and at < 0 and item != "":
items.append(item)
elif op == "-=" and at >= 0:
items.remove_at(at)
value = ", ".join(items)
line = "%s %s %s → %s" % [label, "+" if op == "+=" else "−", item, _shown(value)]
else:
var a: Variant = Expr.to_value(cur) if cur != null and str(cur).strip_edges() != "" else 0
var b: Variant = Expr.to_value(rhs)
if not Expr.is_number(a) or not Expr.is_number(b):
return {"text": "%s: %s needs a number" % [st["src"], label], "error": true}
var delta: Variant = b if op == "+=" else -b
value = Expr.normalize(a + delta)
line = "%s %s → %s" % [label, _signed(delta), _shown(value)]
"*=", "/=":
var a2: Variant = Expr.to_value(cur) if cur != null and str(cur).strip_edges() != "" else 0
var b2: Variant = Expr.to_value(rhs)
if not Expr.is_number(a2) or not Expr.is_number(b2):
return {"text": "%s: %s needs a number" % [st["src"], label], "error": true}
if op == "*=":
value = Expr.normalize(a2 * b2)
line = "%s ×%s → %s" % [label, Expr.format_value(b2), _shown(value)]
else:
if b2 == 0:
return {"text": "%s: can't divide by 0" % st["src"], "error": true}
value = floori(float(a2) / float(b2))
line = "%s ÷%s → %s" % [label, Expr.format_value(b2), _shown(value)]
ctx.save(target, value, source_id)
return {"text": line}
static func _reset(target: String, ctx: RollContext) -> Dictionary:
if target.ends_with("*"):
var prefix := target.trim_prefix("@").trim_suffix("*")
var names := {}
for n: String in ctx.persistent_vars:
if n.begins_with(prefix):
names[n] = true
for n in ctx.declared_names():
if n.begins_with(prefix):
names[n] = true
var errors := PackedStringArray()
for n: String in names:
var r := reset_one(n, ctx)
if r != "":
errors.append(r)
if not errors.is_empty():
return {"text": "reset %s: %s" % [target, "; ".join(errors)], "error": true}
return {"text": "Reset %s (%d)" % [target, names.size()]}
var name := target.trim_prefix("@")
var err := reset_one(name, ctx)
if err != "":
return {"text": "reset %s: %s" % [target, err], "error": true}
var v: Variant = ctx.get_value("@" + name)
if v == null:
return {"text": "Reset %s (cleared)" % ctx.display_name(name)}
return {"text": "Reset %s → %s" % [ctx.display_name(name), _shown(v)]}
## Resets one board variable (no "@"): a declared one goes back to its starting
## value, an undeclared one is deleted. Returns an error message or "".
static func reset_one(name: String, ctx: RollContext) -> String:
var card := ctx.declared(name)
if card == null:
ctx.erase("@" + name)
return ""
var r := card.initial_value(ctx)
ctx.save("@" + name, r["value"], card.id)
return str(r["error"])
static func _shown(v: Variant) -> String:
var s := Expr.format_value(v)
return s if s != "" else "(none)"
static func _signed(v: Variant) -> String:
var s := Expr.format_value(v)
return s if s.begins_with("-") else "+" + s
static func _compile() -> void:
if _stmt_re == null:
_stmt_re = RegEx.create_from_string("^(@?[A-Za-z_][A-Za-z0-9_]*)\\s*(\\+=|-=|\\*=|/=|=)(?!=)\\s*(.*)$")
_reset_re = RegEx.create_from_string("^(?i:reset)\\s+@([A-Za-z_][A-Za-z0-9_]*|)(\\*?)\\s*$")