files-game/engine/engine.gd
2026-10-01 17:22:18 -04:00

1050 lines
39 KiB
GDScript3

class_name RulesEngine
## Files TCG rules engine (engine.ts, rules.md). The state is plain data. `decider` says who must
## act, `legal_actions` lists what they may do, and `apply_action` does it. Between decisions the
## engine runs queued tasks (combat, captures, card triggers) until it needs a player again: a turn
## step, a response window, or a choice a card asks for.
##
## An action is a Dictionary shaped like the TS Action union, e.g. {type: "end"},
## {type: "attack", slot, to} or {type: "play", card, target, args, from}. `action_key` gives each a
## stable string, the same as TS's, so game records replay in either engine.
## No limit, for executionActions and abilityActions (TS uses Infinity).
const NO_LIMIT := 1 << 60
## Combat Cores for an Anomaly standing on `at`, outside any combat. For bots pricing an attack.
## `at` defaults to where it stands (pass "" for that), `loc` to `at` when defending.
static func anomaly_cores(s: Dictionary, p: int, slot: int, role: String, at: Variant = "", loc: Variant = "") -> int:
if at is String and at == "":
at = s.players[p].anomalies[slot - 1].at
if loc is String and loc == "":
loc = at if role == "defend" else null
return Query.cores_of(s, {"ref": State.ref(p, slot), "role": role, "at": at, "loc": loc, "combat": null})
## The first defender on a location, if any.
static func defender_at(s: Dictionary, loc: String) -> Variant:
var d := State.defenders_at(s, loc)
return null if d.is_empty() else d[0]
# ---------------------------------------------------------------------------------------------
# Setup
static func _new_stats() -> Dictionary:
var out := {}
for k in Types.STAT_KEYS:
out[k] = [0, 0]
return out
## Recruit rule: an Anomaly's printed Bandwidth is its price, which is also what it salvages for.
static func _with_price(def: Dictionary, rules: Dictionary) -> Dictionary:
if not rules.recruit.on or def.kind != "anomaly":
return def
var priced := def.duplicate()
priced.bandwidth = rules.recruit.price + rules.recruit.pricePerCore * def.cores
return priced
## Recruit rule: slots `p` can recruit into. The first empty one while there's room, or any Anomaly
## to retire.
static func recruit_slots(s: Dictionary, p: int) -> Array:
var avs: Array = s.players[p].anomalies.slice(0, 4)
var out := []
var empty := -1
for i in avs.size():
if avs[i].card < 0:
empty = i
break
if empty >= 0 and Query.anomaly_room(s, p):
out.append(empty + 1)
for i in avs.size():
var declared := false
for d in s.declarations:
if d.ref.player == p and State.original_of(d.ref).slot == i + 1:
declared = true
if avs[i].card >= 0 and not declared:
out.append(i + 1)
return out
## Buy-Anomalies rule: the next Anomaly `p` can buy, as {slot, price}, or null.
static func anomaly_for_sale(s: Dictionary, p: int) -> Variant:
if not s.rules.buyAnomalies.on:
return null
var i := -1
for k in 4:
if not s.players[p].anomalies[k].faceUp:
i = k
break
return null if i < 1 else {"slot": i + 1, "price": s.rules.buyAnomalies.prices[i - 1]}
static func _new_anomaly(card: int, face_up: bool, copy_of: Variant) -> Dictionary:
return {
"card": card,
"faceUp": face_up,
"at": null,
"hardware": [],
"damage": 0,
"placed": false,
"advanced": false,
"attacks": 0,
"infection": 0,
"bugs": 0,
"permanentInfection": 0,
"mods": [],
"disabledUntil": 0,
"rootedUntil": 0,
"breachedTurn": 0,
"copyOf": copy_of,
"createdTurn": 0,
"unlockedTurn": 0,
}
## Starts a game from {pool, decks: [deck, deck], seed, rules?, log?}. A deck is {anomalies, servers,
## main}, lists of card names. Returns null (and records an error) if a deck is illegal.
static func create_game(o: Dictionary) -> Variant:
var pool: Dictionary = o.pool
var decks: Array = o.decks
var rules: Dictionary = o.get("rules", Rules.defaults())
for p in 2:
var errors := Deck.validate_deck(pool, decks[p], rules)
if not errors.is_empty():
return Util.fail("%s deck is illegal:\n %s" % [State.player_name(p), "\n ".join(errors)])
GameMap.use_board(rules.board)
var rng := Rng.make(o.seed)
var locations := {}
for loc in GameMap.LOCATIONS:
locations[loc] = {"owner": null, "server": null, "programs": [], "rootAccess": [0, 0]}
var s := {
"rules": rules,
"rng": rng,
"defs": {},
"cards": [],
"players": [],
"locations": locations,
"firewalls": {},
"firstPlayer": 0,
"active": 0,
"turn": 0,
"clock": 0,
"step": "deploy",
"declarations": [],
"tasks": [],
"stack": [],
"choice": null,
"combat": null,
"virtuals": [],
"used": {},
"seq": 0,
"over": false,
"winner": null,
"endReason": null,
"stats": _new_stats(),
"cardUse": {},
"log": [] if o.get("log", false) else null,
}
var add := func(card_name: String, owner: int) -> int:
s.defs[card_name] = _with_price(pool.by_name[card_name], rules)
var id: int = s.cards.size()
s.cards.append({"id": id, "name": card_name, "owner": owner, "disabledUntil": 0, "ignoredUntil": 0, "installedTurn": 0})
return id
for p in 2:
var deck: Dictionary = decks[p]
# Recruit rule: slots after the starting Anomaly begin empty (-1).
var anomalies := Rng.shuffle(rng, deck.anomalies.map(func(n): return add.call(n, p)))
var slots := []
for i in 4:
slots.append(anomalies[i] if i < anomalies.size() else -1)
var main := Rng.shuffle(rng, deck.main.map(func(n): return add.call(n, p)))
var servers := Rng.shuffle(rng, deck.servers.map(func(n): return add.call(n, p)))
var avs := []
for i in 4:
avs.append(_new_anomaly(slots[i], slots[i] >= 0 and i < rules.startingAnomalies, null))
for i in 4:
avs.append(_new_anomaly(slots[i], false, i + 1))
s.players.append({
"bandwidth": 0,
"hand": [],
"deck": main,
"discard": [],
"serverPile": servers,
"anomalies": avs,
"unlockedLevel": 1,
})
for p in 2:
var me: Dictionary = s.players[p]
var start: Dictionary = s.locations[GameMap.START_LOC[p]]
var server: int = me.serverPile.pop_front()
start.owner = p
start.server = server
me.bandwidth = rules.startingBandwidth + CardScripts.of(s.cards[server].name).get("bandwidthOnPlace", 0)
State.played(s, s.cards[server].name, p)
for i in rules.openingHand:
Flow.draw_now(s, p)
State.say(s, "%s starts on %s with %d Gb. Anomaly 1: %s." % [State.player_name(p), State.name_of(s, server), me.bandwidth, State.name_of(s, me.anomalies[0].card)], {"tag": "game", "player": p})
s.firstPlayer = Rng.rand_int(rng, 2)
s.active = s.firstPlayer
var p2 := State.other(s.firstPlayer)
var second: Dictionary = s.players[p2]
second.bandwidth += rules.secondPlayer.bandwidth
for av in second.anomalies.slice(0, rules.startingAnomalies + rules.secondPlayer.anomalies):
av.faceUp = av.card >= 0
for i in rules.secondPlayer.cards:
Flow.draw_now(s, p2)
if rules.secondPlayer.locations > 0:
# The location next to the starting Server, with a Server from the pile: no Bandwidth, no unlock.
var line: Dictionary = GameMap.LINES_AT[GameMap.START_LOC[p2]][0]
var L: Dictionary = s.locations[GameMap.other_end(line, GameMap.START_LOC[p2])]
L.owner = p2
L.server = second.serverPile.pop_front()
State.played(s, s.cards[L.server].name, p2)
s.stats.cardsDrawn = [0, 0]
State.say(s, "%s goes first." % State.player_name(s.firstPlayer), {"tag": "game", "player": s.firstPlayer})
_begin_turn(s, not rules.firstTurn.draw)
run(s)
return s
static func _begin_turn(s: Dictionary, skip_draw: bool) -> void:
var cmd: bool = s.rules.commands.on
if s.turn >= s.rules.maxTurns * (s.rules.commands.perPlayer if cmd else 1):
s.over = true
s.endReason = "turnLimit"
State.say(s, "Turn limit reached: draw (South %d, North %d locations)." % [State.grid_count(s, 0), State.grid_count(s, 1)], {"tag": "game"})
return
s.turn += 1
s.clock = State.start_of(s.turn)
# Command rule: a player's turn is their commands in a round, so its refreshes come at the first.
var fresh: bool = not cmd or State.first_command(s, s.turn)
if not cmd or State.round_of(s, s.turn) != State.round_of(s, s.turn - 1):
s.used = {}
_tidy(s)
var me: Dictionary = s.players[s.active]
if fresh:
for av in me.anomalies:
av.placed = false
av.advanced = false
av.attacks = 0
s.declarations = []
s.step = "deploy"
var title := ("Round %d, command %d" % [State.round_of(s, s.turn), s.turn]) if cmd else "Turn %d" % s.turn
State.say(s, "\n— %s: %s (%d Gb, %d cards, %d locations) —" % [title, State.player_name(s.active), me.bandwidth, me.hand.size(), State.grid_count(s, s.active)], {"tag": "turn", "player": s.active})
var draws: int = s.rules.drawPerTurn + (s.rules.secondPlayer.firstDraw if s.turn == 2 else 0)
if fresh and not skip_draw:
Flow.draw_cards(s, s.active, draws)
if fresh:
Query.emit(s, "onTurnStart", null)
## Command rule: this game turn's command is spent (an advance or attack is declared).
static func _command_spent(s: Dictionary) -> bool:
return s.rules.commands.on and not s.declarations.is_empty()
## Command rule: an Anomaly unlocked this round waits in its slot until the next round.
static func _waits_for_round(s: Dictionary, av: Dictionary) -> bool:
return s.rules.commands.on and av.at == null and av.unlockedTurn > 0 \
and State.round_of(s, av.unlockedTurn) == State.round_of(s, s.turn)
static func _end_turn(s: Dictionary) -> void:
s.clock = State.end_of(s.turn)
# Push Update: the extra Hardware leaves at the end of its controller's turn.
for pl in s.players:
for av in pl.anomalies:
for hw in av.hardware.duplicate():
var until = s.cards[hw].get("pushedUntil")
if until != null and not State.running(s, until):
State.remove_from(av.hardware, hw)
State.to_discard(s, hw)
State.say(s, "%s (Push Update) is discarded." % State.name_of(s, hw))
_tidy(s)
s.active = State.commander_of(s, s.turn + 1) if s.rules.commands.on else State.other(s.active)
_begin_turn(s, false)
## Drops expired statuses so the state stays small. Status checks don't rely on this.
static func _tidy(s: Dictionary) -> void:
s.virtuals = s.virtuals.filter(func(v): return State.running(s, v.until))
for pl in s.players:
for av in pl.anomalies:
av.mods = av.mods.filter(func(m): return m.has("combat") or State.running(s, m.get("until", 0)))
# ---------------------------------------------------------------------------------------------
# Who decides
## The player who must act now, or null when the game is over.
static func decider(s: Dictionary) -> Variant:
if s.over:
return null
if s.choice != null:
return s.choice.player
if not s.tasks.is_empty() and s.tasks[0].t == "window":
return s.tasks[0].priority
return s.active
## The open response window, when the decider is responding, or null.
static func open_window(s: Dictionary) -> Variant:
if s.choice == null and not s.tasks.is_empty() and s.tasks[0].t == "window":
return s.tasks[0]
return null
# ---------------------------------------------------------------------------------------------
# Legal actions
static func _targeted(s: Dictionary, loc: String) -> bool:
for d in s.declarations:
if d.to == loc:
return true
return false
## Grid locations `p` may advance to: unowned or undefended enemy, next to its territory.
static func advance_targets(s: Dictionary, p: int) -> Array:
return GameMap.GRID.filter(func(loc):
var owner = s.locations[loc].owner
if owner == p or _targeted(s, loc):
return false
if owner != null and not State.defenders_at(s, loc).is_empty():
return false
for line in GameMap.LINES_AT[loc]:
if State.is_open(s, line) and State.controls(s, p, GameMap.other_end(line, loc)):
return true
return false)
## Infinite Loop lets an Anomaly attacking from its location attack twice.
static func max_attacks(s: Dictionary, r: Dictionary) -> int:
var at = State.anomaly(s, r).at
var extra := 0
for x in Query.sources(s):
if x.at == at and x.controller == r.player:
extra = maxi(extra, CardScripts.of(x.name).get("extraAttacks", 0))
return 1 + extra
static func attack_targets(s: Dictionary, r: Dictionary) -> Array:
var av := State.anomaly(s, r)
if not av.faceUp or av.at == null or av.advanced or av.attacks >= max_attacks(s, r) or not State.can_act(s, r) or State.fresh_copy(s, r):
return []
var opp := State.other(r.player)
var out := []
for line in GameMap.LINES_AT[av.at]:
if not State.is_open(s, line):
continue
var to := GameMap.other_end(line, av.at)
if not GameMap.is_start(to) and State.controls(s, opp, to) and not State.defenders_at(s, to).is_empty() and not _targeted(s, to):
out.append(to)
return out
static func _push_clears(s: Dictionary, p: int, out: Array) -> void:
for line_id in s.firewalls:
var level: int = s.firewalls[line_id]
var l: Dictionary = GameMap.LINE_BY_ID[line_id]
if (State.controls(s, p, l.a) or State.controls(s, p, l.b)) and State.firewall_cost(s, level) <= s.players[p].bandwidth:
out.append({"type": "clearFirewall", "line": line_id})
## Whether a first-turn rule variant stops p playing cards from hand right now.
static func _cards_blocked(s: Dictionary, p: int) -> bool:
return s.turn == 1 and p == s.firstPlayer and not s.rules.firstTurn.cards
## Latency Spike: the attacking player can't play Executions before the roll.
static func _latency_blocked(s: Dictionary, p: int) -> bool:
var c = s.combat
var w = open_window(s)
if c == null or c.ended or w == null or w.kind != "preRoll" or c.attacker.player != p:
return false
return not Query.enemy_flag_at(s, c.loc, p, func(sc): return sc.get("blocksAttackerExecutions", false)).is_empty()
## Force Reboot: a Server that can't perform Executions for the rest of the turn.
static func exec_blocked(s: Dictionary, loc: String) -> bool:
return State.used_this_turn(s, "noExec:%s" % loc) > 0
## Servers worth naming as an Execution's performer: null (any of your Servers), plus each Server
## where one of your Anomalies wears Hardware that cares (Dedicated GPU, Quantum Coprocessor).
static func _performers(s: Dictionary, p: int) -> Array:
var out := [null]
for r in State.refs_in_play(s, p):
var at: String = State.anomaly(s, r).at
if State.is_copy(r) or not State.controls(s, p, at) or exec_blocked(s, at):
continue
var cares := Query.wears(s, r, func(sc): return sc.get("executionPower", 0) or sc.get("copiesExecutions", false))
if not cares.is_empty() and not out.has(at):
out.append(at)
return out
## Dedicated GPU: extra effect for Executions performed by `from`, from its Anomalies' Hardware.
static func execution_power(s: Dictionary, p: int, from: Variant) -> int:
if from == null:
return 0
var n := 0
for r in State.refs_in_play(s, p):
if State.is_copy(r) or State.anomaly(s, r).at != from:
continue
for hw in Query.wears(s, r, func(sc): return sc.get("executionPower", 0)):
n += CardScripts.of(s.cards[hw].name).executionPower
return n
## Enemy Anomalies an Execution targets. `item` needs player, target, args and name.
static func execution_hostiles(s: Dictionary, item: Dictionary) -> Array:
var ex: Dictionary = CardScripts.of(item.name).get("execution", {})
if not ex.has("targetsAnomalies"):
return []
return ex.targetsAnomalies.call(s, item).filter(func(r): return r.player != item.player)
static func execution_cost(s: Dictionary, p: int, card: int, target: Variant, args: Dictionary, all: Variant = null) -> int:
var hostile := execution_hostiles(s, {"player": p, "target": target, "args": args, "name": s.cards[card].name})
return Query.cost_of(s, {"kind": "execution", "player": p, "card": card, "at": target, "hostile": hostile}, all)
## Execution plays for `p`. `budget` "now" keeps plays affordable with current Bandwidth;
## "reachable" also counts Salvage; "any" ignores Bandwidth.
static func execution_actions(s: Dictionary, p: int, budget: String, limit := NO_LIMIT) -> Array:
var out := []
if _latency_blocked(s, p) or _cards_blocked(s, p):
return out
var seen := {}
var who = null
var all = null
for card in s.players[p].hand:
var card_name: String = s.cards[card].name
if seen.has(card_name):
continue
seen[card_name] = true
var ex: Dictionary = CardScripts.of(card_name).get("execution", {})
if ex.is_empty():
continue
var cap: int = NO_LIMIT
if budget == "now":
cap = s.players[p].bandwidth
elif budget == "reachable":
cap = Query.reachable_bandwidth(s, p, card)
if budget != "any" and State.def_of(s, card).bandwidth - 3 > cap:
continue # no discount is bigger than 2
if all == null:
all = Query.sources(s)
for play in ex.plays.call(s, p):
if execution_cost(s, p, card, play.target, play.args, all) > cap:
continue
if who == null:
who = _performers(s, p)
for from in who:
out.append({"type": "play", "card": card, "target": play.target, "args": play.args, "from": from})
if out.size() >= limit:
return out
return out
static func ability_source(s: Dictionary, card: int, ability_name: String) -> Variant:
for x in Query.sources(s):
if x.id == card and x.name == ability_name and activatable(x) and CardScripts.of(x.name).has("ability"):
return x
return null
static func ability_cost(s: Dictionary, src: Dictionary) -> int:
if src.kind == "anomaly":
var d := State.def_of(s, src.id)
return d.ability.cost if d.has("ability") else 0
return CardScripts.of(src.name).get("ability", {}).get("cost", 0)
## Sources whose ability can be activated: real cards, plus Server abilities Duplicate Server copies.
static func activatable(src: Dictionary) -> bool:
return src.get("virtual") == null or src.virtual == -2
static func ability_key(src: Dictionary) -> String:
return "ability:%d:%s" % [src.id, src.name]
## Whether an ability source may be used now (once per turn, not disabled, Desynchronization).
static func ability_ready(s: Dictionary, src: Dictionary) -> bool:
var ab: Dictionary = CardScripts.of(src.name).get("ability", {})
if ab.is_empty() or not activatable(src):
return false
if src.kind == "anomaly" and not State.can_act(s, src.ref):
return false
if src.kind == "hardware":
if HardwareCards.hardware_uses_left(s, src.id) <= 0:
return false
return not (ab.get("hardwareOncePerTurn", false) and Query.desynced(s, src.ref))
return State.used_this_turn(s, ability_key(src)) == 0
static func _extra_cost(s: Dictionary, src: Dictionary, args: Dictionary) -> int:
var ab: Dictionary = CardScripts.of(src.name).ability
return ab.extraCost.call(s, src, args) if ab.has("extraCost") else 0
static func ability_actions(s: Dictionary, p: int, budget: String, limit := NO_LIMIT) -> Array:
var out := []
var cap: int = NO_LIMIT
if budget == "now":
cap = s.players[p].bandwidth
elif budget == "reachable":
cap = Query.reachable_bandwidth(s, p)
for src in Query.sources(s):
if src.controller != p or not CardScripts.of(src.name).has("ability") or not ability_ready(s, src):
continue
var ab: Dictionary = CardScripts.of(src.name).ability
var base := ability_cost(s, src)
if base > cap:
continue
for args in ab.uses.call(s, src):
if base + _extra_cost(s, src, args) > cap:
continue
out.append({"type": "activate", "card": src.id, "name": src.name, "args": args})
if out.size() >= limit:
return out
return out
static func _has_response(s: Dictionary, p: int) -> bool:
return not execution_actions(s, p, "reachable", 1).is_empty() or not ability_actions(s, p, "reachable", 1).is_empty()
static func hardware_cost(s: Dictionary, card: int, r: Dictionary, all: Variant = null) -> int:
return Query.cost_of(s, {"kind": "hardware", "player": r.player, "card": card, "ref": r, "at": State.anomaly(s, r).at}, all)
static func program_cost(s: Dictionary, p: int, card: int, at: String, all: Variant = null) -> int:
return Query.cost_of(s, {"kind": "program", "player": p, "card": card, "at": at}, all)
static func place_firewall_cost(s: Dictionary, p: int, line: String, level: int, all: Variant = null) -> int:
return Query.cost_of(s, {"kind": "firewall", "player": p, "line": line, "level": level}, all)
## Whether Hardware can go on an Anomaly now (Expansion Slots permitting).
static func can_wear(s: Dictionary, card: int, r: Dictionary) -> bool:
if State.is_copy(r) or State.anomaly(s, r).at == null:
return false
return CardScripts.of(s.cards[card].name).get("noSlot", false) or Query.slots_free(s, r) > 0
static func legal_actions(s: Dictionary) -> Array:
var p = decider(s)
if p == null:
return []
var me: Dictionary = s.players[p]
var salvage := []
for card in me.hand:
salvage.append({"type": "salvage", "card": card})
if s.choice != null:
var options := []
for index in s.choice.options.size():
if s.choice.options[index].get("cost", 0) <= me.bandwidth:
options.append({"type": "choose", "index": index})
return options + salvage
if open_window(s) != null:
return [{"type": "pass"}] + salvage + execution_actions(s, p, "now") + ability_actions(s, p, "now")
var out := [{"type": "end"}] + salvage
if s.step == "resolve":
return out
out.append_array(execution_actions(s, p, "now"))
out.append_array(ability_actions(s, p, "now"))
if s.step == "deploy":
var placement_open: bool = s.declarations.is_empty()
var targets := [] if s.turn == 1 and not s.rules.firstTurn.advance else advance_targets(s, p)
for i in me.anomalies.size():
var av: Dictionary = me.anomalies[i]
var r := State.ref(p, i + 1)
if not av.faceUp or av.advanced or av.attacks > 0:
continue
if av.at != null and not State.can_act(s, r):
continue
if placement_open and not av.placed and not _waits_for_round(s, av):
for to in GameMap.LOCATIONS:
if to != av.at and Query.has_room(s, p, to):
out.append({"type": "place", "slot": i + 1, "to": to})
if s.rules.health.on and s.rules.health.recall and av.at != null and not State.is_copy(r):
out.append({"type": "recall", "slot": i + 1})
if av.at != null and not State.fresh_copy(s, r) and not _command_spent(s):
for to in targets:
out.append({"type": "advance", "slot": i + 1, "to": to})
_push_clears(s, p, out)
elif s.step == "attack":
for i in me.anomalies.size():
if _command_spent(s):
continue
for to in attack_targets(s, State.ref(p, i + 1)):
out.append({"type": "attack", "slot": i + 1, "to": to})
_push_clears(s, p, out)
else:
var seen := {}
var all := Query.sources(s)
for card in ([] if _cards_blocked(s, p) else me.hand):
var d := State.def_of(s, card)
if seen.has(d.name):
continue
seen[d.name] = true
if d.kind == "hardware":
for r in State.refs_in_play(s, p):
if can_wear(s, card, r) and hardware_cost(s, card, r, all) <= me.bandwidth:
out.append({"type": "installHardware", "card": card, "slot": r.slot})
elif d.kind == "anomaly" and s.rules.recruit.on:
if d.bandwidth <= me.bandwidth:
for slot in recruit_slots(s, p):
out.append({"type": "recruit", "card": card, "slot": slot})
elif d.kind == "program":
for at in GameMap.LOCATIONS:
if State.controls(s, p, at) and s.locations[at].programs.size() < Query.program_slots(s, at) \
and program_cost(s, p, card, at, all) <= me.bandwidth:
out.append({"type": "installProgram", "card": card, "at": at})
var sale = anomaly_for_sale(s, p)
if sale != null and sale.price <= me.bandwidth:
out.append({"type": "buyAnomaly", "slot": sale.slot})
for line in GameMap.LINES:
if not line.gateway or not (State.controls(s, p, line.a) or State.controls(s, p, line.b)):
continue
for level in range(s.firewalls.get(line.id, 0) + 1, s.rules.firewallCost.size() + 1):
if place_firewall_cost(s, p, line.id, level, all) <= me.bandwidth:
out.append({"type": "firewall", "line": line.id, "level": level})
return out
## Bandwidth an action costs, before any Salvage.
static func action_cost(s: Dictionary, a: Dictionary) -> int:
var p = decider(s)
if p == null:
p = s.active
match a.type:
"firewall":
return place_firewall_cost(s, p, a.line, a.level)
"clearFirewall":
return State.firewall_cost(s, s.firewalls.get(a.line, 0))
"installHardware":
return hardware_cost(s, a.card, State.ref(p, a.slot))
"recruit":
return State.def_of(s, a.card).bandwidth
"buyAnomaly":
var sale = anomaly_for_sale(s, p)
return sale.price if sale != null else 0
"installProgram":
return program_cost(s, p, a.card, a.at)
"play":
return execution_cost(s, p, a.card, a.target, a.args)
"activate":
var src = ability_source(s, a.card, a.name)
return ability_cost(s, src) + _extra_cost(s, src, a.args) if src != null else 0
"choose":
if s.choice != null and a.index < s.choice.options.size():
return s.choice.options[a.index].get("cost", 0)
return 0
return 0
static func _args_key(a: Dictionary) -> String:
var parts := [
"%d.%d" % [a.ref.player, a.ref.slot] if a.get("ref") != null else "",
str(a.card) if a.get("card") != null else "",
",".join(a.cards.map(func(id): return str(id))) if a.get("cards") != null else "",
a.get("to", "") if a.get("to") != null else "",
a.get("mode", "") if a.get("mode") != null else "",
str(a.k) if a.get("k") != null else "",
]
return "|".join(parts)
## Stable identity for comparing actions, the same string as TS's actionKey.
static func action_key(a: Dictionary) -> String:
match a.type:
"end", "pass":
return a.type
"choose":
return "choose:%d" % a.index
"place", "advance", "attack":
return "%s:%d:%s" % [a.type, a.slot, a.to]
"recall":
return "recall:%d" % a.slot
"clearFirewall":
return "clear:%s" % a.line
"firewall":
return "firewall:%s:%d" % [a.line, a.level]
"salvage":
return "salvage:%d" % a.card
"installHardware":
return "hw:%d:%d" % [a.card, a.slot]
"recruit":
return "recruit:%d:%d" % [a.card, a.slot]
"buyAnomaly":
return "buy:%d" % a.slot
"installProgram":
return "prog:%d:%s" % [a.card, a.at]
"play":
return "play:%d:%s:%s:%s" % [a.card, Util.js(a.target), _args_key(a.args), Util.js(a.from)]
"activate":
return "act:%d:%s:%s" % [a.card, a.name, _args_key(a.args)]
return Util.fail("Unknown action type %s" % a.type)
# ---------------------------------------------------------------------------------------------
# Applying actions
## Opens (or continues) a response window after `actor` declares or plays something.
static func _respond_to(s: Dictionary, actor: int, base: int) -> void:
var w = open_window(s)
if w != null:
w.passes = 1
w.priority = State.other(actor)
return
State.push_tasks(s, [{"t": "window", "kind": "response", "priority": State.other(actor), "passes": 1, "base": base, "resolving": false}])
## Applies `a` for the deciding player, then runs the game until the next decision. Pass `legal` when
## you already have the current legal actions. Returns false (and records an error) if `a` isn't legal.
static func apply_action(s: Dictionary, a: Dictionary, legal: Variant = null) -> bool:
if legal == null:
legal = legal_actions(s)
var key := action_key(a)
var found := false
for x in legal:
if action_key(x) == key:
found = true
break
if not found:
Util.fail("Illegal action at turn %d: %s" % [s.turn, key])
return false
var p: int = decider(s)
var me: Dictionary = s.players[p]
var who := State.player_name(p)
match a.type:
"end":
_end_step(s)
"pass":
var w: Dictionary = open_window(s)
w.passes += 1
w.priority = State.other(w.priority)
"choose":
var ch: Dictionary = s.choice
var option: Dictionary = ch.options[a.index]
s.choice = null
var meta := {"tag": "choice", "player": p}
if ch.get("secret", false):
meta.to = p
meta.public = "%s makes a secret choice (%s)." % [who, ch.kind.split(":")[0]]
State.say(s, "%s chooses: %s." % [who, option.label], meta)
var resume: Dictionary = CardScripts.of(ch.resume.name).get("resume", {})
if not resume.has(ch.resume.fn):
Util.fail("No resume %s.%s" % [ch.resume.name, ch.resume.fn])
else:
resume[ch.resume.fn].call(s, ch.resume.data, option.value)
"buyAnomaly":
var price: int = anomaly_for_sale(s, p).price
var av: Dictionary = me.anomalies[a.slot - 1]
me.bandwidth -= price
State.stat(s, "bandwidthOnAnomalies", p, price)
State.stat(s, "anomaliesBought", p)
av.faceUp = true
State.say(s, "%s buys Anomaly %d: %s (-%d Gb, now %d)." % [who, a.slot, State.name_of(s, av.card), price, me.bandwidth], {"tag": "card", "player": p})
"recruit":
var cost: int = State.def_of(s, a.card).bandwidth
var av: Dictionary = me.anomalies[a.slot - 1]
if av.card >= 0:
Flow.retire_anomaly(s, State.ref(p, a.slot))
State.remove_from(me.hand, a.card)
me.bandwidth -= cost
State.stat(s, "bandwidthOnCards", p, cost)
State.stat(s, "anomaliesRecruited", p)
State.played(s, State.name_of(s, a.card), p)
av.merge(_new_anomaly(a.card, true, null), true)
me.anomalies[a.slot + 3].card = a.card
State.say(s, "%s recruits %s as Anomaly %d (-%d Gb, now %d)." % [who, State.name_of(s, a.card), a.slot, cost, me.bandwidth], {"tag": "card", "player": p})
"salvage":
var gain: int = State.def_of(s, a.card).bandwidth
State.remove_from(me.hand, a.card)
State.to_discard(s, a.card)
me.bandwidth += gain
State.stat(s, "bandwidthFromSalvage", p, gain)
State.stat(s, "cardsSalvaged", p)
State.say(s, "%s salvages %s (+%d Gb, now %d)." % [who, State.name_of(s, a.card), gain, me.bandwidth], {"tag": "card", "player": p})
"place":
var av: Dictionary = me.anomalies[a.slot - 1]
var r := State.ref(p, a.slot)
var text := "%s places %s on %s." % [who, State.anomaly_name(s, r), a.to] if av.at == null \
else "%s moves %s %s → %s." % [who, State.anomaly_name(s, r), av.at, a.to]
State.say(s, text, {"tag": "move", "player": p, "loc": a.to, "ref": r})
av.at = a.to
av.placed = true
"recall":
Flow.recall_anomaly(s, State.ref(p, a.slot))
"advance", "attack":
var r := State.ref(p, a.slot)
var av := State.anomaly(s, r)
var second: bool = a.type == "attack" and av.attacks > 0
if a.type == "advance":
av.advanced = true
else:
av.attacks += 1
s.declarations.append({"kind": a.type, "ref": r, "to": a.to, "from": av.at, "second": second})
var text := "%s: %s advances to %s." % [who, State.anomaly_name(s, r), a.to] if a.type == "advance" \
else "%s: %s attacks %s from %s%s." % [who, State.anomaly_name(s, r), a.to, av.at, " (Infinite Loop)" if second else ""]
State.say(s, text, {"tag": "move", "player": p, "loc": a.to, "ref": r})
_respond_to(s, p, s.stack.size())
if a.type == "attack":
Query.emit(s, "onAttackDeclared", {"ref": r, "to": a.to})
"clearFirewall":
var level: int = s.firewalls[a.line]
var cost := State.firewall_cost(s, level)
me.bandwidth -= cost
State.stat(s, "bandwidthOnFirewalls", p, cost)
s.firewalls.erase(a.line)
State.stat(s, "firewallsCleared", p)
State.say(s, "%s clears the Lv %d Firewall on %s (-%d Gb)." % [who, level, a.line, cost], {"tag": "firewall", "player": p})
"firewall":
var before: int = s.firewalls.get(a.line, 0)
var cost := Query.pay(s, {"kind": "firewall", "player": p, "line": a.line, "level": a.level}, "bandwidthOnFirewalls")
s.firewalls[a.line] = a.level
State.stat(s, "firewallsUpgraded" if before else "firewallsPlaced", p)
var text := "%s upgrades the Firewall on %s to Lv %d (-%d Gb)." % [who, a.line, a.level, cost] if before \
else "%s places a Lv %d Firewall on %s (-%d Gb)." % [who, a.level, a.line, cost]
State.say(s, text, {"tag": "firewall", "player": p})
"installHardware":
var r := State.ref(p, a.slot)
var cost := Query.pay(s, {"kind": "hardware", "player": p, "card": a.card, "ref": r, "at": State.anomaly(s, r).at}, "bandwidthOnCards")
State.remove_from(me.hand, a.card)
State.anomaly(s, r).hardware.append(a.card)
s.cards[a.card].installedTurn = s.turn
State.stat(s, "hardwareInstalled", p)
State.played(s, State.name_of(s, a.card), p)
State.say(s, "%s installs %s on %s (-%d Gb)." % [who, State.name_of(s, a.card), State.anomaly_name(s, r), cost], {"tag": "card", "player": p, "ref": r, "loc": State.anomaly(s, r).at})
_respond_to(s, p, s.stack.size())
Query.emit(s, "onInstall", {"card": a.card, "at": State.anomaly(s, r).at, "ref": r})
"installProgram":
var cost := Query.pay(s, {"kind": "program", "player": p, "card": a.card, "at": a.at}, "bandwidthOnCards")
State.remove_from(me.hand, a.card)
s.locations[a.at].programs.append(a.card)
s.cards[a.card].installedTurn = s.turn
State.stat(s, "programsInstalled", p)
State.played(s, State.name_of(s, a.card), p)
State.say(s, "%s installs %s on %s (-%d Gb)." % [who, State.name_of(s, a.card), a.at, cost], {"tag": "card", "player": p, "loc": a.at})
_respond_to(s, p, s.stack.size())
Query.emit(s, "onInstall", {"card": a.card, "at": a.at, "ref": null})
"play":
var card_name := State.name_of(s, a.card)
var hostile := execution_hostiles(s, {"player": p, "target": a.target, "args": a.args, "name": card_name})
var cost := Query.pay(s, {"kind": "execution", "player": p, "card": a.card, "at": a.target, "hostile": hostile}, "bandwidthOnCards")
State.remove_from(me.hand, a.card)
var item := {
"kind": "execution", "player": p, "card": a.card, "name": card_name, "target": a.target, "args": a.args,
"from": a.from, "power": execution_power(s, p, a.from),
}
s.stack.append(item)
if item.power > 0:
State.fired(s, "Dedicated GPU", p)
State.stat(s, "executionsPlayed", p)
State.played(s, card_name, p)
var on := " on %s" % a.target if a.target else ""
var from := " from %s" % a.from if a.from else ""
State.say(s, "%s plays %s%s%s (-%d Gb)." % [who, card_name, on, from, cost], {"tag": "card", "player": p, "loc": a.target})
_respond_to(s, p, s.stack.size() - 1)
if not hostile.is_empty():
State.push_tasks(s, [{"t": "call", "name": "False Positive", "fn": "offer", "data": {"index": s.stack.size() - 1}}])
"activate":
var src: Dictionary = ability_source(s, a.card, a.name)
var cost := ability_cost(s, src) + _extra_cost(s, src, a.args)
me.bandwidth -= cost
State.stat(s, "bandwidthOnAbilities", p, cost)
if src.kind == "hardware":
HardwareCards.use_hardware(s, src.id)
else:
State.mark_used(s, ability_key(src))
var label: String = "%s (%s)" % [State.def_of(s, src.id).ability.name, src.name] if src.kind == "anomaly" else src.name
s.stack.append({"kind": "ability", "player": p, "card": src.id, "name": src.name, "target": null, "args": a.args, "from": null, "power": 0})
State.stat(s, "abilitiesUsed", p)
if src.kind == "anomaly":
State.played(s, src.name, p)
var paid := " (-%d Gb)" % cost if cost else ""
State.say(s, "%s uses %s%s." % [who, label, paid], {"tag": "card", "player": p, "loc": src.at, "ref": src.get("ref")})
_respond_to(s, p, s.stack.size() - 1)
run(s)
return true
static func _end_step(s: Dictionary) -> void:
match s.step:
"deploy":
s.step = "play"
"play":
s.step = "attack"
"attack":
s.step = "resolve"
var tasks := []
for index in s.declarations.size():
tasks.append({"t": "declaration", "index": index})
tasks.append({"t": "afterResolve"})
State.push_tasks(s, tasks)
"playAgain":
State.push_tasks(s, [{"t": "endTurn"}])
# ---------------------------------------------------------------------------------------------
# Running tasks
static func _combat_live(s: Dictionary) -> bool:
return s.combat != null and not s.combat.ended
## Runs queued tasks until a player must decide or the game ends.
static func run(s: Dictionary) -> void:
var guard := 0
while not s.over and s.choice == null:
guard += 1
if guard > 100000:
Util.fail("Engine stuck at turn %d" % s.turn)
return
if s.tasks.is_empty():
return
var task: Dictionary = s.tasks[0]
if task.t == "window":
if _window_waits(s, task):
return
continue
s.tasks.pop_front()
_execute(s, task)
## Advances a response window. Returns true when a player has priority and must decide.
static func _window_waits(s: Dictionary, w: Dictionary) -> bool:
if w.resolving:
if s.stack.size() > w.base:
_resolve_top(s)
return false
w.resolving = false
if w.kind == "response" or not _combat_live(s):
s.tasks.pop_front()
return false
# Something changed the combat: both players may react again.
w.passes = 0
w.priority = s.combat.attacker.player
if w.passes >= 2 or (w.kind != "response" and not _combat_live(s)):
if s.stack.size() > w.base:
w.resolving = true
return false
s.tasks.pop_front()
return false
if not _has_response(s, w.priority):
w.passes += 1
w.priority = State.other(w.priority)
return false
return true
static func _resolve_top(s: Dictionary) -> void:
var item: Dictionary = s.stack.pop_back()
var script := CardScripts.of(item.name)
if item.kind == "execution":
State.to_discard(s, item.card)
for src in Query.sources(s):
var sc := CardScripts.of(src.name)
if sc.has("negates") and sc.negates.call(s, src, item):
return
if item.from:
State.push_tasks(s, [{"t": "call", "name": "Quantum Coprocessor", "fn": "offer", "data": {"item": item}}])
script.execution.resolve.call(s, item)
return
var src = ability_source(s, item.card, item.name)
if src == null:
State.say(s, "%s's ability fizzles: it's no longer in play." % item.name)
return
script.ability.resolve.call(s, item, src)
static func _execute(s: Dictionary, task: Dictionary) -> void:
match task.t:
"declaration":
Flow.resolve_declaration(s, task.index)
"afterResolve":
s.step = "playAgain"
"combat":
Flow.combat_stage(s, task.stage)
"defeat":
Flow.defeat(s, task.ref, task.loc, task.role)
"capture":
if task.stage == "hooks":
Flow.capture_hooks(s, task.ref, task.loc, task.how)
else:
Flow.capture_main(s, task.ref, task.loc, task.how)
"hook":
if not Query.still_active(s, task.src):
return
var sc := CardScripts.of(task.src.name)
if sc.has(task.hook):
sc[task.hook].call(s, task.src, task.data)
"call":
var resume: Dictionary = CardScripts.of(task.name).get("resume", {})
if not resume.has(task.fn):
Util.fail("No script function %s.%s" % [task.name, task.fn])
return
resume[task.fn].call(s, task.data, null)
"draw":
Flow.draw_task(s, task.player)
"endTurn":
_end_turn(s)
# ---------------------------------------------------------------------------------------------
# Player views
## What player `p` can see. Hidden cards become -1: the opponent's hand, both decks and Server piles,
## and face-down Anomalies. The RNG is blanked so bots can't predict dice, the opponent's choices are
## hidden, and only open windows are kept from the task queue. Everything else is shared with the
## real state, so treat a view as read-only.
static func view_for(s: Dictionary, p: int) -> Dictionary:
var hide := func(ids: Array) -> Array:
var out := []
out.resize(ids.size())
out.fill(-1)
return out
var players := []
for i in s.players.size():
var pl: Dictionary = s.players[i]
var v := pl.duplicate()
v.hand = pl.hand.duplicate() if i == p else hide.call(pl.hand)
v.deck = hide.call(pl.deck)
v.serverPile = hide.call(pl.serverPile)
v.discard = pl.discard.duplicate()
v.anomalies = pl.anomalies.map(func(av):
var c: Dictionary = av.duplicate()
c.hardware = av.hardware.duplicate()
c.card = av.card if av.faceUp else -1
return c)
players.append(v)
var choice = s.choice
if choice != null and choice.player != p:
choice = choice.duplicate()
if choice.get("secret", false):
choice.prompt = "%s: %s is choosing." % [choice.kind.split(":")[0], State.player_name(choice.player)]
choice.options = choice.options.map(func(_o): return {"label": "?", "value": null})
var combat = null
if s.combat != null:
combat = s.combat.duplicate()
combat.race = [s.combat.race[0] if p == 0 else null, s.combat.race[1] if p == 1 else null]
var view := s.duplicate()
view.rng = {"s": 0}
view.log = null
view.players = players
view.choice = choice
view.combat = combat
view.tasks = s.tasks.filter(func(t): return t.t == "window")
return view