TableTower/core/builder_scales.gd

65 lines
2.7 KiB
GDScript3
Raw Permalink Normal View History

class_name BuilderScales
extends RefCounted
## The scale forms of Builder's effect model (Scales, docs/PLAIN.md §2):
## step_up @climate += 1 (amount "1")
## step_down @climate -= 2 (amount "2")
## toward @climate = toward(@climate, "Temperate") (amount "Temperate")
## at_least @atmo = max(@atmo, "Medium") (amount "Medium")
## at_most @atmo = min(@atmo, "Thin") (amount "Thin")
## step_up/step_down are += / -= on a value a scale card declares, so they
## need the board (or the caller's word) to tell them apart from add/subtract;
## the other three are read from the text alone. Their amount is the step's
## name without quotes, like append/remove.
const OPS: Array[String] = ["step_up", "step_down", "toward", "at_least", "at_most"]
const _FNS := {"toward": "toward", "at_least": "max", "at_most": "min"}
const _OP_OF := {"toward": "toward", "max": "at_least", "min": "at_most"}
## True when `v` ("@climate") is declared by a scale card on `board`.
static func is_scale(v: String, board: TowerBoard) -> bool:
return card_for(v, board) != null
## The scale card that declares `v` ("@climate"), or null.
static func card_for(v: String, board: TowerBoard) -> RollTable:
if board == null or not v.begins_with("@"):
return null
var n := v.substr(1).to_lower()
for t in board.tables:
if t.is_scale() and t.var_name == n:
return t
return null
## A model with its scale form read: a "set" of toward/max/min(<the same
## value>, "Step") becomes toward/at_least/at_most, and add/subtract on a
## scale (`scale` true) becomes step_up/step_down. Anything else as it is.
static func refine(m: Dictionary, scale: bool) -> Dictionary:
if not m.get("ok", false):
return m
var op := str(m["op"])
var v := str(m["var"])
if op == "set":
var t := Builder.tokens(str(m["amount"]))
if t.size() == 6 and t[0]["t"] == "name" and _OP_OF.has(t[0]["s"]) and t[1]["s"] == "(" and t[2]["t"] == "var" \
and t[2]["s"] == v and t[3]["s"] == "," and t[4]["t"] == "str" and t[5]["s"] == ")":
return {"ok": true, "op": _OP_OF[t[0]["s"]], "var": v, "amount": Builder.unquote(str(t[4]["s"]))}
elif scale and (op == "add" or op == "subtract"):
return {"ok": true, "op": "step_up" if op == "add" else "step_down", "var": v, "amount": str(m["amount"])}
return m
## The statement for a scale model, or "" when it isn't one (or not filled in).
static func text(op: String, v: String, amount: String) -> String:
if amount == "":
return ""
match op:
"step_up":
return "%s += %s" % [v, amount]
"step_down":
return "%s -= %s" % [v, amount]
"toward", "at_least", "at_most":
return "%s = %s(%s, %s)" % [v, _FNS[op], v, Builder.quote(amount)]
return ""