This commit is contained in:
Forrest 2026-10-01 17:22:18 -04:00
commit 0cba7f5ee0
385 changed files with 17912 additions and 0 deletions

318
engine/bots/eval.gd Normal file
View file

@ -0,0 +1,318 @@
class_name BotEval
## Scoring helpers the greedy bot shares (bots/eval.ts): board values, combat odds and what a combat
## is worth. Everything reads a player's view and changes nothing.
# A location is worth about 10 points, plus 8 more when it's taken from the opponent. Bandwidth counts
# half a point per Bandwidth, a card in hand about 2.
const LOCATION_POINTS := 10.0
const ENEMY_LOCATION_POINTS := 8.0
const BANDWIDTH_POINTS := 0.5
const LOSS_POINTS := 4.0
const CARD_POINTS := 2.0
## Hardware's rough combat Cores, by name.
const HARDWARE_CORES := {"Additional Core": 1, "Overclocked CPU": 2, "Packet Accelerator": 1}
static func location_value(v: Dictionary, p: int, loc: String) -> float:
if GameMap.is_start(loc):
return 0.0 # starting Servers can't be captured
var taken := 0.0 if v.locations[loc].owner == null else ENEMY_LOCATION_POINTS
return LOCATION_POINTS + taken + v.rules.levelBandwidth[GameMap.level_for(p, loc)] * BANDWIDTH_POINTS
## How many Anomalies capturing `loc` would unlock for `p` (level unlocks only).
static func unlocks_at(v: Dictionary, p: int, loc: String) -> int:
if v.rules.recruit.on or v.rules.buyAnomalies.on or GameMap.is_start(loc):
return 0
var level := GameMap.level_for(p, loc)
if level <= v.players[p].unlockedLevel:
return 0
var n := 0
for av in v.players[p].anomalies.slice(0, mini(level, 4)):
if not av.faceUp:
n += 1
return n
## What losing an Anomaly costs: the tempo, plus its Hardware.
static func anomaly_stake(v: Dictionary, r: Dictionary) -> float:
var bw := 0
for h in State.hardware_of(v, r):
bw += 0 if h < 0 else State.def_of(v, h).bandwidth
return LOSS_POINTS + bw * BANDWIDTH_POINTS
# ---------------------------------------------------------------------------------------------
# Dice
## Distributions of the sum of k d6, by k: the probability of each total, as an Array by total.
## A static cache, filled on the main thread's first use; see diceSum in eval.ts.
static var _sum_dist: Array = [[1.0]]
static func dice_sum(k: int) -> Array:
while _sum_dist.size() <= k:
var prev: Array = _sum_dist[_sum_dist.size() - 1]
var next := []
next.resize(prev.size() + 6)
next.fill(0.0)
for s in prev.size():
var p: float = prev[s]
for f in range(1, 7):
next[s + f] += p / 6
_sum_dist.append(next)
return _sum_dist[k]
## P(a > b) where a = fa + ka d6 and b = fb + kb d6, ties rerolled at `tie` odds.
static func _beats(fa: int, ka: int, fb: int, kb: int, tie: float) -> float:
var da := dice_sum(ka)
var db := dice_sum(kb)
var win := 0.0
var draw := 0.0
for a in da.size():
var pa: float = da[a]
if pa == 0:
continue
for b in db.size():
var pb: float = db[b]
if pb == 0:
continue
var x := fa + a
var y := fb + b
if x > y:
win += pa * pb
elif x == y:
draw += pa * pb
return win + draw * tie
## Probability of each margin (a − b) where a = fa + ka d6 and b = fb + kb d6, in TS Map order.
static func margin_dist(fa: int, ka: int, fb: int, kb: int) -> Dictionary:
var da := dice_sum(ka)
var db := dice_sum(kb)
var out := {}
for a in da.size():
var pa: float = da[a]
if pa == 0:
continue
for b in db.size():
var pb: float = db[b]
if pb == 0:
continue
var m := fa + a - fb - b
out[m] = out.get(m, 0.0) + pa * pb
return out
## Averages margin distributions, for a combat whose bonus is decided by a coin flip (Race Condition).
static func _mix_dist(dists: Array) -> Dictionary:
var out := {}
for d in dists:
for m in d:
out[m] = out.get(m, 0.0) + d[m] / dists.size()
return out
## The dice each side of the current combat still has to roll (or has rolled), for the odds.
## `reroll` is null or {ref, k}.
static func _combat_dice(v: Dictionary, reroll: Variant) -> Dictionary:
var c: Dictionary = v.combat
var fa := 0
var ka := 0
var fd := 0
var kd := 0
for r in State.fighters_of(c):
var want := Query.cores_of(v, Query.fighter_of(v, r))
var dice := []
if c.rolled:
dice = c.dice.get(State.ref_key(r), []).duplicate()
dice.sort()
if dice.size() > want:
dice = dice.slice(0, want)
var extra := want - dice.size()
if reroll != null and State.ref_key(reroll.ref) == State.ref_key(r):
extra += dice.filter(func(d): return d <= reroll.k).size()
dice = dice.filter(func(d): return d > reroll.k)
var fixed := Util.sum(dice)
if r == c.attacker:
fa += fixed
ka += extra
else:
fd += fixed
kd += extra
return {"fa": fa, "ka": ka, "fd": fd, "kd": kd}
## Chance the attacker wins the current combat. Before the roll that's the Core odds. After it, the
## dice on the table count: Core changes add dice or drop the highest ones, and `reroll` lets a
## fighter reroll its dice showing k or less (Bit Flip).
static func combat_odds(v: Dictionary, reroll: Variant = null) -> float:
var c: Dictionary = v.combat
var atk := 0
var def := 0
for r in State.fighters_of(c):
var n := Query.cores_of(v, Query.fighter_of(v, r))
if r == c.attacker:
atk += n
else:
def += n
var tie := Odds.win_chance(atk, def)
if not c.rolled:
return tie
var d := _combat_dice(v, reroll)
return _beats(d.fa, d.ka, d.fd, d.kd, tie)
## Health rule: the margin distribution of the current combat, given the dice on the table.
static func combat_dist(v: Dictionary, reroll: Variant = null) -> Dictionary:
var d := _combat_dice(v, reroll)
return margin_dist(d.fa, d.ka, d.fd, d.kd)
## Cores each side would have if `r` attacked `target` from `origin` now, counting what the target's
## Programs do when a combat starts there (Bloatware, Visual Artifact, Memory Parasite), and whether
## Race Condition may add +2 to the defence. Returns {atk, def, race}.
static func _attack_cores(v: Dictionary, r: Dictionary, origin: String, target: String, bonus: int) -> Dictionary:
var atk := Query.cores_of(v, {"ref": r, "role": "attack", "at": origin, "loc": target, "combat": null}) + bonus
var def := 0
for d in State.defenders_at(v, target):
def += Query.cores_of(v, {"ref": d, "role": "defend", "at": target, "loc": target, "combat": null})
var race := false
for x in Query.sources(v):
if x.at != target or x.controller == r.player:
continue
var hw := State.hardware_of(v, r)
if x.name == "Bloatware" and not Query.bug_immune(v, r, x.controller):
atk -= hw.size()
if x.name == "Visual Artifact" and not v.cards[x.id].get("spent", false):
atk -= 1
if x.name == "Race Condition":
race = true
if x.name == "Memory Parasite":
var bonuses := []
for h in hw:
if Query.hardware_active(v, h):
bonuses.append(hardware_cores(v, h))
if not bonuses.is_empty():
atk -= bonuses.min()
return {"atk": maxi(1, atk), "def": maxi(1, def), "race": race}
## Chance an attack would win the roll if declared now.
static func attack_odds(v: Dictionary, r: Dictionary, origin: String, target: String, bonus := 0) -> float:
var c := _attack_cores(v, r, origin, target, bonus)
if c.race:
return (Odds.win_chance(c.atk, c.def) + Odds.win_chance(c.atk, c.def + 2)) / 2
return Odds.win_chance(c.atk, c.def)
## Health rule: margin distribution of an attack declared now.
static func attack_dist(v: Dictionary, r: Dictionary, origin: String, target: String, bonus := 0) -> Dictionary:
var c := _attack_cores(v, r, origin, target, bonus)
var plain := margin_dist(0, c.atk, 0, c.def)
return _mix_dist([plain, margin_dist(0, c.atk, 0, c.def + 2)]) if c.race else plain
## Health rule: expected points for `me` from a combat with the given margin distribution.
## Destroying every defender wins the location and their stakes. Damage short of that is worth a
## share of those stakes plus half the location, since the defender can still recall and heal.
## Damage to the attacker is worth the same share of its own stake.
static func damage_value(v: Dictionary, me: int, attacker: Dictionary, defenders: Array, dist: Dictionary, loc_value: float) -> float:
var left_d := 0
var stake_d := 0.0
for d in defenders:
left_d += Query.health_left(v, d)
stake_d += anomaly_stake(v, d)
var sum_left := maxi(1, left_d)
var stake_a := anomaly_stake(v, attacker)
var left_a := maxi(1, Query.health_left(v, attacker))
var total := 0.0
for m in dist:
var p: float = dist[m]
if m > 0:
total += p * (loc_value + stake_d if m >= sum_left else (m * (stake_d + loc_value / 2)) / sum_left)
elif m < 0:
total -= p * (stake_a if -m >= left_a else (-m * stake_a) / left_a)
return total if attacker.player == me else -total
## Points for the attacking player from declaring an attack now: under the health rule the expected
## damage value, otherwise the odds of taking the location against losing the Anomaly.
static func attack_value(v: Dictionary, r: Dictionary, origin: String, target: String, loc_value: float, bonus := 0) -> float:
if not v.rules.health.on:
var chance := attack_odds(v, r, origin, target, bonus)
return chance * loc_value - (1 - chance) * anomaly_stake(v, r)
return damage_value(v, r.player, r, State.defenders_at(v, target), attack_dist(v, r, origin, target, bonus), loc_value)
## Chance `target` falls to this attack: the win odds, or under the health rule the odds of
## destroying every defender.
static func fall_chance(v: Dictionary, r: Dictionary, origin: String, target: String, bonus := 0) -> float:
if not v.rules.health.on:
return attack_odds(v, r, origin, target, bonus)
var need := 0
for d in State.defenders_at(v, target):
need += Query.health_left(v, d)
var p := 0.0
var dist := attack_dist(v, r, origin, target, bonus)
for m in dist:
if m >= need:
p += dist[m]
return p
## Rough Cores a Hardware card adds in combat.
static func hardware_cores(v: Dictionary, hw: int) -> int:
return HARDWARE_CORES.get(v.cards[hw].name, 0)
## Health a Hardware card adds to its wearer (RAM Expansion), when the health rule is on.
static func hardware_health(v: Dictionary, hw: int) -> int:
return CardScripts.of(v.cards[hw].name).get("health", 0) if v.rules.health.on else 0
# ---------------------------------------------------------------------------------------------
# What the current combat is worth
## Points for `me` if the combat goes each way: {win, lose}.
static func stakes(v: Dictionary, me: int) -> Dictionary:
var c: Dictionary = v.combat
var loc := location_value(v, c.attacker.player, c.loc)
var atk := anomaly_stake(v, c.attacker)
var def := 0.0
for d in c.defenders:
def += anomaly_stake(v, d)
if c.attacker.player == me:
return {"win": loc + def / 2, "lose": -atk}
return {"win": atk / 2, "lose": -(loc + def)}
## Expected points for `me` from the current combat, or from how it ended. `reroll` ({ref, k})
## values a Bit Flip of one fighter's dice showing k or less.
static func combat_value(v: Dictionary, me: int, reroll: Variant = null) -> float:
var c = v.combat
if c == null:
return 0.0
var i_attack: bool = c.attacker.player == me
if c.ended:
# Ended early: the attacker takes the location only if every defender left.
var taken: bool = c.defenders.is_empty() and State.anomaly(v, c.attacker).at != null
if not taken:
return 0.0
return location_value(v, me, c.loc) if i_attack else -location_value(v, c.attacker.player, c.loc)
if v.rules.health.on:
return damage_value(v, me, c.attacker, c.defenders, combat_dist(v, reroll), location_value(v, c.attacker.player, c.loc))
var st := stakes(v, me)
var p_atk := combat_odds(v, reroll)
var p := p_atk if i_attack else 1 - p_atk
return p * st.win + (1 - p) * st.lose
static func card_name(v: Dictionary, id: int) -> String:
return "" if id < 0 else v.cards[id].name
static func printed_bandwidth(v: Dictionary, id: int) -> int:
return 0 if id < 0 else State.def_of(v, id).bandwidth

1
engine/bots/eval.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cldo5g32fpwlm

1245
engine/bots/greedy.gd Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1 @@
uid://c8eurfxxusevb

32
engine/bots/random.gd Normal file
View file

@ -0,0 +1,32 @@
class_name RandomBot
extends RefCounted
## Baseline bot (bots/random.ts): ends the step or passes 30% of the time, otherwise picks any legal
## action. Choices are picked at random too.
##
## A bot has `bot_name` and `choose(view, actions, me) -> action`, picking one of `actions` for
## player `me` while seeing only `view` (see RulesEngine.view_for). Bots are made per game, from a
## seed, so they can keep per-game memory.
var bot_name := "random"
var _rng: Dictionary
func _init(seed: int) -> void:
_rng = Rng.make(seed)
func choose(_view: Dictionary, actions: Array, _me: int) -> Dictionary:
var stop = null
var others := []
for a in actions:
if a.type == "end" or a.type == "pass":
if stop == null:
stop = a
else:
others.append(a)
if others.is_empty():
return stop if stop != null else actions[0]
if stop != null and Rng.next_float(_rng) < 0.3:
return stop
var choices := others.filter(func(a): return a.type == "choose")
return Rng.pick(_rng, choices if not choices.is_empty() and Rng.next_float(_rng) < 0.8 else others)

View file

@ -0,0 +1 @@
uid://dnsq54w8tqkx7

66
engine/cards.gd Normal file
View file

@ -0,0 +1,66 @@
class_name Cards
## Card definitions from the Cider deck CSV (cards.ts).
##
## A CardDef is a Dictionary: {name, kind, bandwidth, cores, health, slots, type, text, set} and,
## when printed, ability: {name, cost, text}. kind is "anomaly", "server", "program", "hardware" or
## "execution". A pool is {all: Array of defs, by_name: Dictionary name -> def}.
const DEFAULT_CSV := "res://data/cards.csv"
const KIND_BY_TEMPLATE := {
"Anomaly Front": "anomaly",
"Server Front": "server",
"Server Front Alt": "server",
"Program Front": "program",
"Hardware Front": "hardware",
"Execution Front": "execution",
}
static func _num(s: String) -> int:
return int(s) if s != "" else 0
## Reads the CSV's text. Reference cards (Turn Sequence) are skipped. By default only set 1 (the base
## game) is loaded; `sets` picks others, or "all". `source` names the file in errors.
static func parse_cards(csv: String, sets: Variant = [1], source := "cards.csv") -> Dictionary:
var all := []
var by_name := {}
for row in Csv.parse_objects(csv):
var kind: String = KIND_BY_TEMPLATE.get(row.get("Front Template", ""), "")
if kind == "":
continue
var set_no := int(row["Set"]) if row.get("Set", "") != "" else 1
if not (sets is String and sets == "all") and not (sets as Array).has(set_no):
continue
var card := {
"name": row["Name"],
"kind": kind,
"bandwidth": _num(row.get("Bandwidth", "")),
"cores": _num(row.get("Cores", "")),
"health": _num(row.get("Health", "")),
"slots": _num(row.get("Expansion Slots", "")),
"type": row.get("Type", ""),
"text": row.get("Description", ""),
"set": set_no,
}
if row.get("Ability Name", "") != "":
card.ability = {
"name": row["Ability Name"],
"cost": _num(row.get("Ability Cost", "")),
"text": row.get("Ability Description", ""),
}
if by_name.has(card.name):
Util.fail("Duplicate card name in %s: %s" % [source, card.name])
continue
all.append(card)
by_name[card.name] = card
return {"all": all, "by_name": by_name}
## Loads the card CSV from disk. See parse_cards for `sets`.
static func load_cards(path := DEFAULT_CSV, sets: Variant = [1]) -> Dictionary:
var text := FileAccess.get_file_as_string(path)
if text == "":
Util.fail("Can't read %s" % path)
return parse_cards(text, sets, path)

1
engine/cards.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://ctcmy378sx1dp

271
engine/cards/anomalies.gd Normal file
View file

@ -0,0 +1,271 @@
class_name AnomalyCards
## Anomaly Abilities (cards/anomalies.ts). Each costs the Bandwidth printed on the card, can be used
## once per turn at Execution timing, and only while the Anomaly is in play. For Abilities, "a combat
## at this Server" means any combat the Anomaly is fighting in, attacking or defending.
## Hardware cost after discounts (Upgraded Hardware), for Abilities that install Hardware.
static func _install_cost(s: Dictionary, card: int, r: Dictionary) -> int:
return Query.cost_of(s, {"kind": "hardware", "player": r.player, "card": card, "ref": r, "at": State.anomaly(s, r).at})
static func scripts() -> Dictionary:
return {
# The copy has the same Cores and uses the original's Hardware bonuses, but no Hardware or
# Ability of its own. It enters play on a location you control with room.
"Carbon NanoBots": {
"text": "Anomaly may create a copy of itself. Only one copy is allowed at a time. If the copy is defeated the original does not lose any hardware upgrades. If the original is defeated the replicate is as well.",
"ability": {"uses": _nanobots_uses, "resolve": _nanobots_resolve},
},
"Corrupt Driver": {
"text": "Choose one Hardware on an enemy Anomaly in combat with this Anomaly. It is disabled until the end of your next command.",
"ability": {"uses": _driver_uses, "resolve": _driver_resolve},
},
"Pixelated Picture": {
"text": "Attacking Anomalies have -1 cores against this Anomaly.",
"ability": {"uses": _pixelated_uses, "resolve": _pixelated_resolve},
},
# Reading: during a combat it's in, install one Hardware from hand on it (paying its cost),
# ignoring Expansion Slots. That Hardware is discarded at the end of your turn.
"Beta Version 1.0": {
"text": "While in combat an additional piece of hardware can be placed on this anomaly until the end of your command. If there are no Expansion Slots available this can still be attached.",
"ability": {
"uses": _beta_uses,
"extraCost": func(s, src, args): return _install_cost(s, args.card, src.ref),
"resolve": _beta_resolve,
},
},
"Code Zero": {
"text": "Place an Infection counter on every enemy Anomaly in combat at this Server. While this Anomaly is in play, an Anomaly with 1+ Infection counters has -1 Core.",
"globalCores": func(s, f): return -1 if State.infection_of(State.anomaly(s, f.ref)) >= 1 else 0,
"ability": {
"uses": func(s, src): return [{}] if not State.opponents_in_combat(s, src.ref).is_empty() else [],
"resolve": _code_zero_resolve,
},
},
# "Breached a Server" = captured an enemy location this turn.
"Data Leaker": {
"text": "Look at your opponent's hand and choose one card in it. They must discard that card without gaining Bandwidth. If this Anomaly breached a Server this command, draw a card.",
"ability": {
"uses": func(s, src): return [{}] if not s.players[State.other(src.controller)].hand.is_empty() else [],
"resolve": _leaker_resolve,
},
"resume": {"discard": _leaker_discard},
},
# Restore Point either heals 3 damage (health rule) or recovers a card from the discard pile.
"Backup Machine": {
"text": "Remove 3 damage from this Anomaly, or return one Hardware or Program from your discard pile to your hand. If it is a Hardware and this Anomaly has an open Expansion Slot, you may install it immediately for 2 less Gb.",
"ability": {"uses": _backup_uses, "resolve": _backup_resolve},
"resume": {"install": _backup_install},
},
# Rerolls this Anomaly's dice showing k or less; that's always the best way to pick dice.
"Broken Bits": {
"text": "During a combat at this Server, reroll any number of this Anomaly's Core dice.",
"ability": {"uses": _bits_uses, "resolve": _bits_resolve},
},
}
# Carbon NanoBots
static func _nanobots_uses(s: Dictionary, src: Dictionary) -> Array:
if State.anomaly(s, State.copy_of(src.ref)).at != null or not Query.can_copy(s, src.controller):
return []
var out := []
for l in GameMap.LOCATIONS:
if Query.has_room(s, src.controller, l):
out.append({"to": l})
return out
static func _nanobots_resolve(s: Dictionary, item: Dictionary, src: Dictionary) -> void:
var to: String = item.args.to
if State.anomaly(s, State.copy_of(src.ref)).at != null or not Query.can_copy(s, src.controller) \
or not Query.has_room(s, src.controller, to):
return
State.fired(s, "Carbon NanoBots", src.controller)
Flow.create_copy(s, src.ref, to)
# Corrupt Driver
static func _driver_uses(s: Dictionary, src: Dictionary) -> Array:
var hws := []
for r in State.opponents_in_combat(s, src.ref):
hws.append_array(State.hardware_of(s, r))
var out := []
for hw in Util.uniq(hws):
if Query.hardware_active(s, hw):
out.append({"card": hw})
return out
static func _driver_resolve(s: Dictionary, item: Dictionary, src: Dictionary) -> void:
var hw: int = item.args.card
s.cards[hw].disabledUntil = maxi(s.cards[hw].disabledUntil, State.end_of(State.next_turn_of(s, src.controller)))
State.fired(s, "Corrupt Driver", src.controller)
State.say(s, "Driver Fault disables %s until the end of %s's next turn." % [State.name_of(s, hw), State.player_name(src.controller)])
# Pixelated Picture
static func _pixelated_uses(s: Dictionary, src: Dictionary) -> Array:
if not State.in_combat(s, src.ref):
return []
for d in s.combat.defenders:
if State.ref_key(d) == State.ref_key(src.ref):
return [{}]
return []
static func _pixelated_resolve(s: Dictionary, _item: Dictionary, src: Dictionary) -> void:
var c = s.combat
if c == null or c.ended:
return
State.add_mod(s, c.attacker, -1, "Low Resolution", src.controller, {"combat": c.id})
State.fired(s, "Pixelated Picture", src.controller)
State.say(s, "Low Resolution: %s gets -1 Core." % State.anomaly_name(s, c.attacker))
# Beta Version 1.0
static func _beta_uses(s: Dictionary, src: Dictionary) -> Array:
if not State.in_combat(s, src.ref):
return []
var hand: Array = s.players[src.controller].hand.filter(func(id): return State.def_of(s, id).kind == "hardware")
return CardUtil.card_options(s, hand).map(func(o): return {"card": o.value})
static func _beta_resolve(s: Dictionary, item: Dictionary, src: Dictionary) -> void:
var card: int = item.args.card
if not s.players[src.controller].hand.has(card) or not State.in_combat(s, src.ref):
return
HardwareCards.attach_hardware(s, card, src.ref)
var turn: int = s.turn if s.active == src.controller else State.next_turn_of(s, src.controller)
s.cards[card].pushedUntil = State.end_of(turn)
State.fired(s, "Beta Version 1.0", src.controller)
State.say(s, "Push Update attaches %s to %s until the end of %s's turn." % [State.name_of(s, card), State.anomaly_name(s, src.ref), State.player_name(src.controller)])
# Code Zero
static func _code_zero_resolve(s: Dictionary, _item: Dictionary, src: Dictionary) -> void:
var foes := State.opponents_in_combat(s, src.ref)
for r in foes:
State.anomaly(s, r).infection += 1
State.fired(s, "Code Zero", src.controller)
var names := ", ".join(foes.map(func(r): return "%s (%d)" % [State.anomaly_name(s, r), State.infection_of(State.anomaly(s, r))]))
State.say(s, "Patient Zero infects %s." % names)
# Data Leaker
static func _leaker_resolve(s: Dictionary, _item: Dictionary, src: Dictionary) -> void:
var hand: Array = s.players[State.other(src.controller)].hand
if hand.is_empty():
return
State.fired(s, "Data Leaker", src.controller)
State.ask(s, {
"player": src.controller,
"kind": "Data Leaker:discard",
"prompt": "Exfiltrate: choose a card from your opponent's hand for them to discard.",
"options": CardUtil.card_options(s, hand),
"resume": {"name": "Data Leaker", "fn": "discard", "data": {"ref": src.ref}},
})
static func _leaker_discard(s: Dictionary, data: Dictionary, card: Variant) -> void:
var p: int = data.ref.player
if State.remove_from(s.players[State.other(p)].hand, card):
State.to_discard(s, card)
State.say(s, "Exfiltrate: %s discards %s." % [State.player_name(State.other(p)), State.name_of(s, card)])
if State.anomaly(s, data.ref).breachedTurn == s.turn:
Flow.draw_cards(s, p, 1)
# Backup Machine
static func _backup_uses(s: Dictionary, src: Dictionary) -> Array:
var out := []
if s.rules.health.on and State.anomaly(s, src.ref).damage > 0:
out.append({"heal": true})
var discard: Array = s.players[src.controller].discard.filter(func(id): return ["hardware", "program"].has(State.def_of(s, id).kind))
for o in CardUtil.card_options(s, discard):
out.append({"card": o.value})
return out
static func _backup_resolve(s: Dictionary, item: Dictionary, src: Dictionary) -> void:
var p: int = src.controller
if item.args.get("heal", false):
var av := State.anomaly(s, src.ref)
if av.at == null or av.damage == 0:
return
var healed := mini(3, av.damage)
av.damage -= healed
State.fired(s, "Backup Machine", p)
State.say(s, "Restore Point heals %d damage on %s." % [healed, State.anomaly_name(s, src.ref)])
return
var card: int = item.args.card
if not State.remove_from(s.players[p].discard, card):
return
State.to_hand(s, card)
State.fired(s, "Backup Machine", p)
State.say(s, "Restore Point returns %s to %s's hand." % [State.name_of(s, card), State.player_name(p)])
if State.def_of(s, card).kind != "hardware" or Query.slots_free(s, src.ref) <= 0:
return
var cost := maxi(0, _install_cost(s, card, src.ref) - 2)
State.ask(s, {
"player": p,
"kind": "Backup Machine:install",
"prompt": "Restore Point: install %s on %s now for %d Gb?" % [State.name_of(s, card), State.anomaly_name(s, src.ref), cost],
"options": [
{"label": "Keep it in hand", "value": false},
{"label": "Install it for %d Gb" % cost, "value": true, "cost": cost},
],
"resume": {"name": "Backup Machine", "fn": "install", "data": {"card": card, "ref": src.ref, "cost": cost}},
})
static func _backup_install(s: Dictionary, data: Dictionary, yes: Variant) -> void:
if not yes or State.anomaly(s, data.ref).at == null or not s.players[data.ref.player].hand.has(data.card):
return
s.players[data.ref.player].bandwidth -= data.cost
s.stats.bandwidthOnCards[data.ref.player] += data.cost
HardwareCards.attach_hardware(s, data.card, data.ref)
State.say(s, "%s is installed on %s." % [State.name_of(s, data.card), State.anomaly_name(s, data.ref)])
# Broken Bits
static func _bits_uses(s: Dictionary, src: Dictionary) -> Array:
var c = s.combat
if c == null or c.ended or not c.rolled or not State.in_combat(s, src.ref):
return []
var dice: Array = c.dice.get(State.ref_key(src.ref), [])
var ks: Array = Util.uniq(dice).filter(func(v): return v < 6)
ks.sort()
return ks.map(func(k): return {"k": k})
static func _bits_resolve(s: Dictionary, item: Dictionary, src: Dictionary) -> void:
var c = s.combat
if c == null or c.ended or not c.rolled:
return
var key := State.ref_key(src.ref)
var before: Array = c.dice.get(key, []).duplicate()
var k: int = item.args.k
var after := []
for v in before:
after.append(State.roll_die(s) if v <= k else v)
c.dice[key] = after
State.fired(s, "Broken Bits", src.controller)
var rerolled := before.filter(func(v): return v <= k).size()
State.say(s, "Bit Flip rerolls %d dice: [%s] → [%s]." % [rerolled, ",".join(before.map(func(v): return str(v))), ",".join(after.map(func(v): return str(v)))])

View file

@ -0,0 +1 @@
uid://ch4bumb8x8y5x

598
engine/cards/executions.gd Normal file
View file

@ -0,0 +1,598 @@
class_name ExecutionCards
## Executions (cards/executions.ts). Each targets a location (the "target Server") and resolves there,
## then goes to the discard pile. Ghost Process lets its controller's Executions reach one adjacent
## location too.
static func _live_combat(s: Dictionary) -> Variant:
return s.combat if s.combat != null and not s.combat.ended else null
## Unique Anomaly refs, first seen first.
static func _uniq_refs(refs: Array) -> Array:
var seen := {}
var out := []
for r in refs:
var k := State.ref_key(r)
if not seen.has(k):
seen[k] = true
out.append(r)
return out
## Plays for every target whose reach includes a location, with the args `args_at(loc)` allows there.
static func _across_scope(s: Dictionary, p: int, args_at: Callable) -> Array:
var out := []
var ghosts := CardUtil.ghosts_of(s, p)
var at := {}
for target in GameMap.LOCATIONS:
for loc in CardUtil.scope_of(s, p, target, ghosts):
if not at.has(loc):
at[loc] = args_at.call(loc)
for args in at[loc]:
out.append({"target": target, "args": args})
return out
static func _wearer_list(s: Dictionary, hw: Variant) -> Array:
var r = State.wearer_of(s, hw) if hw != null else null
return [r] if r != null else []
static func _ref_target(_s: Dictionary, item: Dictionary) -> Array:
return [item.args.ref] if item.args.get("ref") != null else []
static func _draw_n(s: Dictionary, p: int, n: int) -> void:
Flow.draw_cards(s, p, n)
static func _has_negatives(s: Dictionary, r: Dictionary) -> bool:
var av := State.anomaly(s, r)
if av.infection > 0 or av.permanentInfection > 0 or State.running(s, av.rootedUntil) or State.running(s, av.disabledUntil):
return true
for m in State.active_mods(s, av):
if m.cores < 0:
return true
for hw in State.hardware_of(s, r):
if not Query.hardware_active(s, hw):
return true
return false
static func scripts() -> Dictionary:
return {
# Reading: the Anomaly moves to a location you control with room. An attacker "at" the target
# (attacking it) can retreat back to where it stands.
"Execute: Disconnect": {
"text": "Move one Anomaly you control at the target Server to an adjacent Server, removing it from any combat there.",
"execution": {"plays": _disconnect_plays, "targetsAnomalies": _ref_target, "resolve": _disconnect_resolve},
},
# Reading: an unspecified disable lasts until something re-enables it (Execute: Defragment).
"Execute: Sabotage": {
"text": "Destroy or disable one Hardware on an enemy Anomaly in combat at the target Server.",
"execution": {
"plays": _sabotage_plays,
"targetsAnomalies": func(s, item): return _wearer_list(s, item.args.get("card")),
"resolve": _sabotage_resolve,
},
},
"Execute: Kill Process": {
"text": "Disable one Program installed on the target Server until its controller's next command.",
"execution": {"plays": _targetable_program_plays, "resolve": _kill_resolve},
},
# Ruling: Servers perform Executions, so "that Anomaly cannot play another Execution" stops the
# Server it stands on from performing Executions for the rest of the turn.
"Execute: Force Reboot": {
"text": "Remove all temporary bonuses and penalties from one Anomaly you control at the target Server, or one Anomaly attacking it. That Anomaly cannot play another Execution until end of current command.",
"execution": {"plays": _reboot_plays, "targetsAnomalies": _ref_target, "resolve": _reboot_resolve},
},
"Execute: Fork": {
"text": "Copy the localized effect of one Program installed on the target Server until end of current command.",
"execution": {"plays": _targetable_program_plays, "resolve": _fork_resolve},
},
"Execute: Ping Sweep": {
"text": "You may draw 2 cards from the top of your deck.",
"execution": {
"plays": func(_s, _p): return [{"target": null, "args": {}}],
"resolve": _ping_resolve,
},
},
# Reading: resolves right away, only while no combat is going on. Into your own location it's a
# move; into an unowned or undefended one it's a capture; into a defended one it's an attack.
"Execute: Trace Route": {
"text": "Move one Anomaly you control from an adjacent Server to the target Server. If the target Server is enemy-controlled, your Anomaly attacks it with +1 Core for the resulting combat.",
"execution": {"plays": _trace_plays, "targetsAnomalies": _ref_target, "resolve": _trace_resolve},
},
"Execute: Override": {
"text": "Choose one enemy Program installed on the target Server. Ignore its text until end of current command.",
"execution": {"plays": _override_plays, "resolve": _override_resolve},
},
"Execute: Memory Dump": {
"text": "Draw 2 cards, then discard 1. If you control the target Server, draw 1 extra card instead of discarding.",
"execution": {"plays": _every_location, "resolve": _dump_resolve},
"resume": {"discard": _dump_discard, "drop": _dump_drop},
},
"Execute: Rollback": {
"text": "Return one Program or Hardware installed at the target Server this command to its owner's hand.",
"execution": {
"plays": _rollback_plays,
"targetsAnomalies": func(s, item): return _wearer_list(s, item.args.get("card")),
"resolve": _rollback_resolve,
},
},
# Protected = Hardware Sandbox's Program. No card protects Hardware yet.
"Execute: Root Access": {
"text": "Until end of current command, your Programs and Executions at the target Server may target protected Programs and Hardware as though they were unprotected.",
"execution": {"plays": _every_location, "resolve": _root_resolve},
},
# Rooted Anomalies can't advance, attack, reposition, or be moved; their declared moves fail.
"Execute: Packet Flood": {
"text": "Anomalies based at the target Server cannot move or retreat until the start of their controller's next command.",
"execution": {"plays": _flood_plays, "resolve": _flood_resolve},
},
# Reading: Disabled Anomalies still defend, but can't advance, attack, move or use Abilities.
"Execute: Emergency Shutdown": {
"text": "End any combat at the target Server immediately. All Anomalies there remain and become Disabled until end of current command.",
"execution": {"plays": _shutdown_plays, "resolve": _shutdown_resolve},
},
"Execute: Process Clone": {
"text": "Choose one Program installed on the target Server you control. Treat it as though a second copy were installed there until end of current command.",
"execution": {"plays": _clone_plays, "resolve": _clone_resolve},
},
"Execute: Defragment": {
"text": "Re-enable one Disabled Program on the target Server, or one Disabled Hardware on an Anomaly there.",
"execution": {"plays": _defrag_plays, "resolve": _defrag_resolve},
},
# Reading: the Program keeps its owner, and runs at both locations until end of turn.
"Execute: Remote Access": {
"text": "Activate one Program installed on a Server adjacent to the target Server as though it were installed on the target Server, until end of current command.",
"execution": {"plays": _remote_plays, "resolve": _remote_resolve},
},
"Execute: Purge": {
"text": "Remove all Virus/Infection counters and hostile persistent effects from every Anomaly you control at the target Server.",
"execution": {"plays": _purge_plays, "resolve": _purge_resolve},
},
"Execute: Hard Reset": {
"text": "Uninstall any number of Programs from the target Server you control. For each card returned to your hand this way, recover 1 Gb.",
"execution": {"plays": _reset_plays, "resolve": _reset_resolve},
},
}
static func _every_location(_s: Dictionary, _p: int) -> Array:
return GameMap.LOCATIONS.map(func(target): return {"target": target, "args": {}})
## Plays on each active Program `p` may target, in the scope of each target (Kill Process, Fork).
static func _targetable_program_plays(s: Dictionary, p: int) -> Array:
return _across_scope(s, p, func(loc):
return CardUtil.programs_on(s, loc).filter(func(id): return Query.can_target_program(s, id, p)).map(func(card): return {"card": card}))
# Disconnect
static func _disconnect_plays(s: Dictionary, p: int) -> Array:
return _across_scope(s, p, func(loc):
var out := []
for r in CardUtil.mine(s, p, loc):
if not State.can_act(s, r):
continue
var at: String = State.anomaly(s, r).at
var dests: Array = State.neighbors(s, loc).filter(func(d): return d != at and Query.has_room(s, p, d))
if State.in_combat(s, r) and at != loc:
dests.append(at)
for to in dests:
out.append({"ref": r, "to": to})
return out)
static func _disconnect_resolve(s: Dictionary, item: Dictionary) -> void:
var r: Dictionary = item.args.ref
var to: String = item.args.to
var av := State.anomaly(s, r)
if av.at == null or not State.can_act(s, r) or (to != av.at and not Query.has_room(s, r.player, to)):
return
State.fired(s, item.name, item.player)
if State.in_combat(s, r):
Flow.drop_from_combat(s, r)
if to != av.at:
Flow.move_anomaly(s, r, to)
# Sabotage
static func _sabotage_plays(s: Dictionary, p: int) -> Array:
var c = _live_combat(s)
if c == null:
return []
var hws := []
for r in State.fighters_of(c):
if r.player != p:
hws.append_array(State.hardware_of(s, r))
hws = Util.uniq(hws)
var out := []
for target in GameMap.LOCATIONS:
if not CardUtil.scope_of(s, p, target).has(c.loc):
continue
for card in hws:
out.append({"target": target, "args": {"card": card, "mode": "destroy"}})
if Query.hardware_active(s, card):
out.append({"target": target, "args": {"card": card, "mode": "disable"}})
return out
static func _sabotage_resolve(s: Dictionary, item: Dictionary) -> void:
var hw: int = item.args.card
var owner = State.wearer_of(s, hw)
if owner == null:
return
State.fired(s, item.name, item.player)
if item.args.mode == "destroy":
State.uninstall_hardware(s, hw)
State.to_discard(s, hw)
State.stat(s, "hardwareLost", owner.player)
State.say(s, "Sabotage destroys %s." % State.name_of(s, hw))
HardwareCards.shed_hardware(s, owner)
else:
s.cards[hw].disabledUntil = Types.FOREVER
State.say(s, "Sabotage disables %s." % State.name_of(s, hw))
# Kill Process
static func _kill_resolve(s: Dictionary, item: Dictionary) -> void:
var card: int = item.args.card
if State.program_location(s, card) == null:
return
var until := State.start_of(State.next_turn_of(s, State.owner_of(s, card)))
s.cards[card].disabledUntil = maxi(s.cards[card].disabledUntil, until)
State.fired(s, item.name, item.player)
State.say(s, "Kill Process disables %s until %s's next turn." % [State.name_of(s, card), State.player_name(State.owner_of(s, card))])
# Force Reboot
static func _reboot_plays(s: Dictionary, p: int) -> Array:
return _across_scope(s, p, func(loc):
var c = _live_combat(s)
var attacker := [c.attacker] if c != null and c.loc == loc else []
return _uniq_refs(CardUtil.mine(s, p, loc) + attacker).map(func(r): return {"ref": r}))
static func _reboot_resolve(s: Dictionary, item: Dictionary) -> void:
var r: Dictionary = item.args.ref
var av := State.anomaly(s, r)
if av.at == null:
return
var live := State.active_mods(s, av)
av.mods = av.mods.filter(func(m): return not live.has(m))
# Servers perform Executions: the Server this Anomaly stands on can't for the rest of the turn.
State.mark_used(s, "noExec:%s" % av.at)
State.fired(s, item.name, item.player)
State.say(s, "Force Reboot clears %d temporary effect(s) from %s." % [live.size(), State.anomaly_name(s, r)])
# Fork
static func _fork_resolve(s: Dictionary, item: Dictionary) -> void:
var card: int = item.args.card
if State.program_location(s, card) == null or not Query.program_active(s, card):
return
s.seq += 1
s.virtuals.append({
"id": s.seq, "name": State.name_of(s, card), "controller": item.player, "at": item.target,
"until": State.end_of_turn(s), "installed": false, "from": card,
})
State.fired(s, item.name, item.player)
State.say(s, "Fork copies %s on %s for %s until end of turn." % [State.name_of(s, card), item.target, State.player_name(item.player)])
# Ping Sweep
static func _ping_resolve(s: Dictionary, item: Dictionary) -> void:
State.fired(s, item.name, item.player)
_draw_n(s, item.player, 2 + item.power)
# Trace Route
static func _trace_plays(s: Dictionary, p: int) -> Array:
if _live_combat(s) != null:
return []
var out := []
for target in GameMap.LOCATIONS:
if GameMap.is_start(target) and not State.controls(s, p, target):
continue
var mine_there := State.controls(s, p, target)
if mine_there and not Query.has_room(s, p, target):
continue
for r in State.refs_in_play(s, p):
var at: String = State.anomaly(s, r).at
if at != target and State.can_act(s, r) and State.adjacent(s, at, target):
out.append({"target": target, "args": {"ref": r}})
return out
static func _trace_resolve(s: Dictionary, item: Dictionary) -> void:
var r: Dictionary = item.args.ref
var t: String = item.target
var av := State.anomaly(s, r)
if av.at == null or not State.can_act(s, r) or not State.adjacent(s, av.at, t) or _live_combat(s) != null:
return
var owner = s.locations[t].owner
State.fired(s, item.name, item.player)
if owner == item.player:
if Query.has_room(s, item.player, t):
Flow.move_anomaly(s, r, t)
elif owner == null:
State.push_capture(s, r, t, "capturesUnowned")
elif State.defenders_at(s, t).is_empty():
State.push_capture(s, r, t, "capturesUndefended")
else:
var c := State.start_combat(s, r, av.at, t, "traceRoute")
State.add_mod(s, r, 1 + item.power, "Trace Route", item.player, {"combat": c.id})
Query.emit(s, "onAttackDeclared", {"ref": r, "to": t})
# Override
static func _override_plays(s: Dictionary, p: int) -> Array:
return _across_scope(s, p, func(loc):
return CardUtil.programs_on(s, loc) \
.filter(func(id): return State.owner_of(s, id) != p and Query.can_target_program(s, id, p)) \
.map(func(card): return {"card": card}))
static func _override_resolve(s: Dictionary, item: Dictionary) -> void:
var card: int = item.args.card
if State.program_location(s, card) == null:
return
s.cards[card].ignoredUntil = State.end_of_turn(s)
State.fired(s, item.name, item.player)
State.say(s, "Override: %s's text is ignored until end of turn." % State.name_of(s, card))
# Memory Dump
static func _dump_resolve(s: Dictionary, item: Dictionary) -> void:
var p: int = item.player
State.fired(s, item.name, p)
if State.controls(s, p, item.target):
_draw_n(s, p, 3 + item.power)
return
var tasks := []
for i in 2 + item.power:
tasks.append({"t": "draw", "player": p})
tasks.append(State.later("Execute: Memory Dump", "discard", {"player": p}))
State.push_tasks(s, tasks)
static func _dump_discard(s: Dictionary, data: Dictionary, _value: Variant) -> void:
var hand: Array = s.players[data.player].hand
if hand.is_empty():
return
State.ask(s, {
"player": data.player,
"kind": "Execute: Memory Dump:discard",
"prompt": "Memory Dump: discard a card.",
"options": CardUtil.card_options(s, hand),
"resume": {"name": "Execute: Memory Dump", "fn": "drop", "data": {"player": data.player}},
})
static func _dump_drop(s: Dictionary, data: Dictionary, card: Variant) -> void:
if State.remove_from(s.players[data.player].hand, card):
State.to_discard(s, card)
# Rollback
static func _rollback_plays(s: Dictionary, p: int) -> Array:
return _across_scope(s, p, func(loc):
var progs: Array = s.locations[loc].programs.filter(func(id):
return s.cards[id].installedTurn == s.turn and Query.can_target_program(s, id, p))
var worn := []
for r in State.anomalies_at(s, loc):
worn.append_array(State.anomaly(s, r).hardware)
var hws: Array = Util.uniq(worn).filter(func(id): return s.cards[id].installedTurn == s.turn)
return (progs + hws).map(func(card): return {"card": card}))
static func _rollback_resolve(s: Dictionary, item: Dictionary) -> void:
var card: int = item.args.card
var wearer = State.wearer_of(s, card)
if State.uninstall_program(s, card) == null and State.uninstall_hardware(s, card) == null:
return
State.to_hand(s, card)
State.fired(s, item.name, item.player)
State.say(s, "Rollback returns %s to %s's hand." % [State.name_of(s, card), State.player_name(State.owner_of(s, card))])
if wearer != null:
HardwareCards.shed_hardware(s, wearer)
# Root Access
static func _root_resolve(s: Dictionary, item: Dictionary) -> void:
s.locations[item.target].rootAccess[item.player] = State.end_of_turn(s)
State.fired(s, item.name, item.player)
# Packet Flood
static func _flood_plays(s: Dictionary, p: int) -> Array:
return _across_scope(s, p, func(loc): return [{"to": loc}] if not State.anomalies_at(s, loc).is_empty() else [])
static func _flood_resolve(s: Dictionary, item: Dictionary) -> void:
var loc: String = item.args.get("to") if item.args.get("to") != null else item.target
var here := State.anomalies_at(s, loc)
if here.is_empty():
return
for r in here:
var av := State.anomaly(s, r)
av.rootedUntil = maxi(av.rootedUntil, State.start_of(State.next_turn_of(s, r.player)))
State.fired(s, item.name, item.player)
State.say(s, "Packet Flood: %s can't move." % ", ".join(here.map(func(r): return State.anomaly_name(s, r))))
# Emergency Shutdown
static func _shutdown_plays(s: Dictionary, p: int) -> Array:
var c = _live_combat(s)
if c == null:
return []
var out := []
for target in GameMap.LOCATIONS:
if CardUtil.scope_of(s, p, target).has(c.loc):
out.append({"target": target, "args": {}})
return out
static func _shutdown_resolve(s: Dictionary, item: Dictionary) -> void:
var c = _live_combat(s)
if c == null or not CardUtil.scope_of(s, item.player, item.target).has(c.loc):
return
var everyone := _uniq_refs(State.fighters_of(c) + State.anomalies_at(s, c.loc))
Flow.end_combat(s, "Emergency Shutdown")
for r in everyone:
State.anomaly(s, r).disabledUntil = maxi(State.anomaly(s, r).disabledUntil, State.end_of_turn(s))
State.fired(s, item.name, item.player)
# Process Clone
static func _clone_plays(s: Dictionary, p: int) -> Array:
var out := []
for target in GameMap.LOCATIONS:
if not State.controls(s, p, target):
continue
for loc in CardUtil.scope_of(s, p, target):
if State.controls(s, p, loc):
for card in CardUtil.programs_on(s, loc):
out.append({"target": target, "args": {"card": card}})
return out
static func _clone_resolve(s: Dictionary, item: Dictionary) -> void:
var card: int = item.args.card
if State.program_location(s, card) == null or not State.controls(s, item.player, item.target):
return
s.seq += 1
s.virtuals.append({
"id": s.seq, "name": State.name_of(s, card), "controller": item.player, "at": item.target,
"until": State.end_of_turn(s), "installed": true, "from": card,
})
State.fired(s, item.name, item.player)
State.say(s, "Process Clone: a second %s runs on %s until end of turn." % [State.name_of(s, card), item.target])
# Defragment
static func _defrag_plays(s: Dictionary, p: int) -> Array:
return _across_scope(s, p, func(loc):
var progs: Array = s.locations[loc].programs.filter(func(id): return State.running(s, s.cards[id].disabledUntil))
var worn := []
for r in State.anomalies_at(s, loc):
worn.append_array(State.hardware_of(s, r))
var hws: Array = Util.uniq(worn).filter(func(id): return not Query.hardware_active(s, id))
return (progs + hws).map(func(card): return {"card": card}))
static func _defrag_resolve(s: Dictionary, item: Dictionary) -> void:
var card: int = item.args.card
if not State.running(s, s.cards[card].disabledUntil):
return
s.cards[card].disabledUntil = 0
State.fired(s, item.name, item.player)
State.say(s, "Defragment re-enables %s." % State.name_of(s, card))
# Remote Access
static func _remote_plays(s: Dictionary, p: int) -> Array:
var out := []
for target in GameMap.LOCATIONS:
for n in State.neighbors(s, target):
for id in CardUtil.programs_on(s, n):
if Query.can_target_program(s, id, p):
out.append({"target": target, "args": {"card": id}})
return out
static func _remote_resolve(s: Dictionary, item: Dictionary) -> void:
var card: int = item.args.card
if State.program_location(s, card) == null:
return
s.seq += 1
s.virtuals.append({
"id": s.seq, "name": State.name_of(s, card), "controller": State.owner_of(s, card), "at": item.target,
"until": State.end_of_turn(s), "installed": true, "from": card,
})
State.fired(s, item.name, item.player)
State.say(s, "Remote Access: %s also runs on %s until end of turn." % [State.name_of(s, card), item.target])
# Purge
static func _purge_plays(s: Dictionary, p: int) -> Array:
return _across_scope(s, p, func(loc):
for r in CardUtil.mine(s, p, loc):
if _has_negatives(s, r):
return [{"to": loc}]
return [])
static func _purge_resolve(s: Dictionary, item: Dictionary) -> void:
var loc: String = item.args.get("to") if item.args.get("to") != null else item.target
var here := CardUtil.mine(s, item.player, loc)
for r in here:
var av := State.anomaly(s, r)
av.infection = 0
av.permanentInfection = 0
av.mods = av.mods.filter(func(m): return m.cores >= 0 or m.by == item.player)
av.rootedUntil = 0
av.disabledUntil = 0
for hw in State.hardware_of(s, r):
s.cards[hw].disabledUntil = 0
State.fired(s, item.name, item.player)
State.say(s, "Purge cleans %s." % ", ".join(here.map(func(r): return State.anomaly_name(s, r))))
# Hard Reset
static func _reset_plays(s: Dictionary, p: int) -> Array:
var out := []
for target in GameMap.LOCATIONS:
if State.controls(s, p, target) and not s.locations[target].programs.is_empty():
for cards in CardUtil.subsets(s.locations[target].programs):
out.append({"target": target, "args": {"cards": cards}})
return out
static func _reset_resolve(s: Dictionary, item: Dictionary) -> void:
var back: Array = item.args.cards.filter(func(id): return State.program_location(s, id) == item.target)
for id in back:
State.uninstall_program(s, id)
State.to_hand(s, id)
var gain: int = back.size() * (1 + item.power)
State.gain_bandwidth(s, item.player, gain)
State.fired(s, item.name, item.player)
State.say(s, "Hard Reset returns %s to hand (+%d Gb)." % [", ".join(back.map(func(id): return State.name_of(s, id))), gain])

View file

@ -0,0 +1 @@
uid://b3a807yeclr0l

422
engine/cards/hardware.gd Normal file
View file

@ -0,0 +1,422 @@
class_name HardwareCards
## Hardware (cards/hardware.ts). It works while its wearer is in play. "The occupied Server" is the
## location the wearer stands on.
## Uses a Hardware card has left this turn. Its "once per turn" or "first ... each turn" effect gets
## one use, or two when Cooling System on the same Anomaly picks it (Cooling helps one Hardware a turn).
static func hardware_uses_left(s: Dictionary, hw: int) -> int:
var used := State.used_this_turn(s, "hw:%d" % hw)
var cooler = _cooler_for(s, hw)
return (1 if cooler == null else 2) - used
static func _cooler_for(s: Dictionary, hw: int) -> Variant:
var r = State.wearer_of(s, hw)
if r == null:
return null
for id in State.anomaly(s, r).hardware:
if id == hw or s.cards[id].name != "Cooling System" or not Query.hardware_active(s, id):
continue
var picked_for = s.used.get("cool:%d" % id)
if picked_for == null or picked_for == hw:
return id
return null
## Reading: an Anomaly that loses an Expansion Slot (Network Interface Upgrade removed) discards
## Hardware until it fits, the most recently installed first.
static func shed_hardware(s: Dictionary, r: Dictionary) -> void:
while not Query.slots_fit(s, r):
var hw = null
var list: Array = State.anomaly(s, r).hardware
for i in range(list.size() - 1, -1, -1):
if Query.takes_slot(s, list[i]):
hw = list[i]
break
State.uninstall_hardware(s, hw)
State.to_discard(s, hw)
State.stat(s, "hardwareLost", r.player)
State.say(s, "%s is out of Expansion Slots and discards %s." % [State.anomaly_name(s, r), State.name_of(s, hw)])
static func use_hardware(s: Dictionary, hw: int) -> void:
var cooler = _cooler_for(s, hw)
State.mark_used(s, "hw:%d" % hw)
if State.used_this_turn(s, "hw:%d" % hw) >= 2 and cooler != null:
s.used["cool:%d" % cooler] = hw
State.fired(s, "Cooling System", State.owner_of(s, hw))
## Whether `r` is the Anomaly (or a copy of the Anomaly) wearing Hardware at `wearer`.
static func _wearing(wearer: Variant, r: Dictionary) -> bool:
return wearer != null and wearer.player == r.player and (wearer.slot == r.slot or wearer.slot + 4 == r.slot)
## Installs a Hardware card from its owner's hand onto an Anomaly, without paying.
static func attach_hardware(s: Dictionary, card: int, r: Dictionary) -> void:
State.remove_from(s.players[r.player].hand, card)
State.anomaly(s, r).hardware.append(card)
s.cards[card].installedTurn = s.turn
State.stat(s, "hardwareInstalled", r.player)
State.played(s, State.name_of(s, card), r.player)
static func scripts() -> Dictionary:
return {
# Health rule: the wearer's Health goes up by 2 (Query.health_of). Without the rule it does nothing.
"RAM Expansion": {"text": "Anomaly gains +2 Health.", "health": 2},
"Additional Core": {"text": "Anomaly gains +1 Core.", "cores": func(_s, _src, _f): return 1},
# Reading: the Program is one on the location the wearer fought from, the owner picks it, and it
# stays disabled through the end of the next turn.
"Overclocked CPU": {
"text": "Anomaly gains +2 Cores during combat, but one installed Program at the current server becomes disabled afterward for 2 commands.",
"cores": func(_s, _src, f): return 2 if f.role != null else 0,
"onCombatEnd": _overclocked_combat_end,
"resume": {"disable": func(s, _data, id): _disable_for_two_turns(s, id)},
},
"Solid-State Cache": {
"text": "The first Program installed on the occupied Server each round costs 3 less Gb.",
"costMod": _cache_cost,
"onPaid": _use_and_fire.bind("Solid-State Cache"),
},
# Reading: the first time the wearer is defeated with this installed, all its Hardware stays on
# it (in its slot) instead of being discarded.
"Redundant Power Supply": {
"text": "The first time this Anomaly would be destroyed, do not destroy the Hardware.",
"savePriority": 0,
"onWearerDefeated": _rps_defeated,
},
# Ruling: it takes no Expansion Slot and adds one, so the wearer nets +1 Expansion Slot.
"Network Interface Upgrade": {
"text": "This Hardware can be played without taking an Expansion Slot on the Anomaly.",
"noSlot": true,
"extraSlots": 1,
},
# Ruling: Servers perform Executions, so this works for Executions performed by the Server the
# wearer stands on. +1 to the number the Execution uses (cards drawn, Cores, Bandwidth recovered).
"Dedicated GPU": {
"text": "Executions performed by this Anomaly receive +1 effectiveness or combat strength.",
"executionPower": 1,
},
# Blocks opponents' Bug counters (see CardUtil.add_bugs; no card places them yet) and their
# Bug Program effects on the wearer (Bloatware, Stock Rice).
"ECC Memory": {
"text": "Opponents cannot place Bug counters or Bug status effects on this Anomaly.",
"bugImmunity": true,
},
# Works through hardware_uses_left() above.
"Cooling System": {"text": "Allow one Hardware to activate twice per round."},
# Reading: half the combined printed Bandwidth of its Hardware, rounded up.
"RAID Array": {
"text": "When this Anomaly is destroyed, all hardware can be kept by paying half the Bandwidth cost.",
"savePriority": 1,
"onWearerDefeated": _raid_defeated,
"resume": {"keep": _raid_keep},
},
"Packet Accelerator": {
"text": "This Anomaly gains +1 Core hen attacking.",
"cores": func(_s, _src, f): return 1 if f.role == "attack" else 0,
},
# Programs never target Anomalies, so this taxes Executions (and Hardware they hit).
"Firewall Appliance": {
"text": "The first hostile Program or Execution targeting this Anomaly each round costs the opponent +3 Gb.",
"costMod": _appliance_cost,
"onPaid": _use_and_fire.bind("Firewall Appliance"),
},
# Reading: pick the Program on install, and again at the start of your turn if the wearer has
# moved. Protection only holds while the wearer stands on that Program's location.
"Hardware Sandbox": {
"text": "Choose one Program installed on the occupied Server. It cannot be targeted by opponents.",
"onInstall": _sandbox_install,
"onTurnStart": _sandbox_turn_start,
"resume": {"protect": _sandbox_protect},
},
# Reading: at the start of your turn, look at the top card and you may put it on the bottom.
"Diagnostic Module": {
"text": "Look at one face down card in your draw pile. You may place it at the bottom and draw another to start your first command each round.",
"onTurnStart": _diagnostic_turn_start,
"resume": {"bottom": _diagnostic_bottom},
},
# Reading: swap Hardware on this Anomaly, paying the difference in printed Bandwidth (no refund).
"Hot-Swap Bay": {
"text": "Once per round, return one Hardware to your hand and install another Hardware from your hand, paying the difference in cost.",
"ability": {
"hardwareOncePerTurn": true,
"uses": _hot_swap_uses,
"extraCost": _hot_swap_extra,
"resolve": _hot_swap_resolve,
},
},
# Ruling: Servers perform Executions, so "this Anomaly uses an Execution" means one performed by
# the Server the wearer stands on. "Disable this Hardware" lasts until your next turn.
"Quantum Coprocessor": {
"text": "Once per round when this Anomaly uses an Execution, you may copy that Execution's effect with a different legal target, then disable this Hardware.",
"copiesExecutions": true,
"resume": {"offer": _quantum_offer, "copy": _quantum_copy},
},
}
static func _use_and_fire(s: Dictionary, src: Dictionary, _pay: Dictionary, card_name: String) -> void:
use_hardware(s, src.id)
State.fired(s, card_name, src.controller)
# Overclocked CPU
static func _overclocked_combat_end(s: Dictionary, src: Dictionary, _ev: Variant) -> void:
var c: Dictionary = s.combat
var role := ""
if _wearing(src.get("ref"), c.attacker):
role = "attack"
else:
for d in c.defenders:
if _wearing(src.get("ref"), d):
role = "defend"
break
if role == "":
return
var loc: String = c.origin if role == "attack" else c.loc
if s.locations[loc].owner != src.controller:
return
var progs := CardUtil.programs_on(s, loc)
if progs.is_empty():
return
State.fired(s, "Overclocked CPU", src.controller)
if progs.size() == 1:
_disable_for_two_turns(s, progs[0])
return
State.ask(s, {
"player": src.controller,
"kind": "Overclocked CPU:disable",
"prompt": "Overclocked CPU: which Program on %s is disabled for 2 turns?" % loc,
"options": progs.map(func(id): return {"label": State.name_of(s, id), "value": id}),
"resume": {"name": "Overclocked CPU", "fn": "disable", "data": null},
})
static func _disable_for_two_turns(s: Dictionary, id: int) -> void:
s.cards[id].disabledUntil = maxi(s.cards[id].disabledUntil, State.end_of(s.turn + 1))
State.say(s, "Overclocked CPU: %s is disabled for 2 turns." % State.name_of(s, id))
# Solid-State Cache, Firewall Appliance
static func _cache_cost(s: Dictionary, src: Dictionary, pay: Dictionary) -> int:
return -3 if pay.kind == "program" and pay.player == src.controller and pay.get("at") == src.at \
and hardware_uses_left(s, src.id) > 0 else 0
static func _appliance_cost(s: Dictionary, src: Dictionary, pay: Dictionary) -> int:
if pay.kind != "execution" or pay.player == src.controller or hardware_uses_left(s, src.id) <= 0:
return 0
for r in pay.get("hostile", []):
if _wearing(src.get("ref"), r):
return 3
return 0
# Redundant Power Supply, RAID Array
static func _rps_defeated(s: Dictionary, hw: int, ev: Dictionary) -> bool:
if s.cards[hw].get("spent", false):
return false
s.cards[hw].spent = true
State.fired(s, "Redundant Power Supply", ev.ref.player)
State.say(s, "Redundant Power Supply: %s keeps its Hardware." % State.anomaly_name(s, ev.ref))
Flow.knock_out(s, ev.ref, ev.loc, ev.role, true)
return true
static func _raid_defeated(s: Dictionary, _hw: int, ev: Dictionary) -> bool:
var av := State.anomaly(s, ev.ref)
var total := 0
for h in av.hardware:
total += State.def_of(s, h).bandwidth
var cost := ceili(total / 2.0)
State.ask(s, {
"player": ev.ref.player,
"kind": "RAID Array:keep",
"prompt": "RAID Array: pay %d Gb to keep %s?" % [cost, ", ".join(av.hardware.map(func(h): return State.name_of(s, h)))],
"options": [
{"label": "Keep all Hardware for %d Gb" % cost, "value": true, "cost": cost},
{"label": "Lose the Hardware", "value": false},
],
"resume": {"name": "RAID Array", "fn": "keep", "data": {"ref": ev.ref, "loc": ev.loc, "role": ev.role, "cost": cost}},
})
return true
static func _raid_keep(s: Dictionary, data: Dictionary, keep: Variant) -> void:
if keep:
s.players[data.ref.player].bandwidth -= data.cost
State.stat(s, "bandwidthOnCards", data.ref.player, data.cost)
State.fired(s, "RAID Array", data.ref.player)
Flow.knock_out(s, data.ref, data.loc, data.role, keep)
# Hardware Sandbox
static func _sandbox_install(s: Dictionary, src: Dictionary, ev: Dictionary) -> void:
if ev.card == src.id:
_ask_sandbox(s, src.id)
static func _sandbox_turn_start(s: Dictionary, src: Dictionary, _ev: Variant) -> void:
if s.active != src.controller:
return
var p = s.cards[src.id].get("protects")
if p == null or State.program_location(s, p) != src.at:
_ask_sandbox(s, src.id)
static func _sandbox_protect(s: Dictionary, data: Dictionary, program: Variant) -> void:
s.cards[data.card].protects = program
State.fired(s, "Hardware Sandbox", State.owner_of(s, data.card))
static func _ask_sandbox(s: Dictionary, card: int) -> void:
var r = State.wearer_of(s, card)
var at = State.anomaly(s, r).at if r != null else null
if r == null or not at:
return
var progs: Array = s.locations[at].programs.filter(func(id): return State.owner_of(s, id) == r.player)
if progs.is_empty():
return
if progs.size() == 1:
s.cards[card].protects = progs[0]
return
State.ask(s, {
"player": r.player,
"kind": "Hardware Sandbox:protect",
"prompt": "Hardware Sandbox: protect which Program on %s?" % at,
"options": progs.map(func(id): return {"label": State.name_of(s, id), "value": id}),
"resume": {"name": "Hardware Sandbox", "fn": "protect", "data": {"card": card}},
})
# Diagnostic Module
static func _diagnostic_turn_start(s: Dictionary, src: Dictionary, _ev: Variant) -> void:
if s.active != src.controller or hardware_uses_left(s, src.id) <= 0:
return
var deck: Array = s.players[src.controller].deck
if deck.size() < 2:
return
use_hardware(s, src.id)
State.fired(s, "Diagnostic Module", src.controller)
var top := State.name_of(s, deck[0])
State.ask(s, {
"player": src.controller,
"kind": "Diagnostic Module:bottom",
"secret": true,
"prompt": "Diagnostic Module: the top card of your deck is %s. Put it on the bottom?" % top,
"options": [
{"label": "Keep %s on top" % top, "value": false},
{"label": "Put %s on the bottom" % top, "value": true},
],
"resume": {"name": "Diagnostic Module", "fn": "bottom", "data": {"player": src.controller}},
})
static func _diagnostic_bottom(s: Dictionary, data: Dictionary, bottom: Variant) -> void:
var deck: Array = s.players[data.player].deck
if bottom and not deck.is_empty():
deck.append(deck.pop_front())
# Hot-Swap Bay
static func _hot_swap_uses(s: Dictionary, src: Dictionary) -> Array:
var av := State.anomaly(s, src.ref)
var hand: Array = s.players[src.controller].hand.filter(func(id): return State.def_of(s, id).kind == "hardware")
var out := []
for out_card in av.hardware:
for o in CardUtil.card_options(s, hand):
if Query.slots_fit(s, src.ref, out_card, o.value):
out.append({"card": out_card, "cards": [o.value]})
return out
static func _hot_swap_extra(s: Dictionary, _src: Dictionary, args: Dictionary) -> int:
return maxi(0, State.def_of(s, args.cards[0]).bandwidth - State.def_of(s, args.card).bandwidth)
static func _hot_swap_resolve(s: Dictionary, item: Dictionary, src: Dictionary) -> void:
var out_card: int = item.args.card
var into: int = item.args.cards[0]
var r: Dictionary = src.ref
if not State.anomaly(s, r).hardware.has(out_card) or not s.players[src.controller].hand.has(into):
return
if not Query.slots_fit(s, r, out_card, into):
return
State.uninstall_hardware(s, out_card)
State.to_hand(s, out_card)
attach_hardware(s, into, r)
State.fired(s, "Hot-Swap Bay", src.controller)
State.say(s, "Hot-Swap Bay swaps %s for %s on %s." % [State.name_of(s, out_card), State.name_of(s, into), State.anomaly_name(s, r)])
# Quantum Coprocessor
static func _quantum_offer(s: Dictionary, data: Dictionary, _value: Variant) -> void:
var item: Dictionary = data.item
var qc = null
for r in State.refs_in_play(s, item.player):
if State.is_copy(r) or State.anomaly(s, r).at != item.from or Query.desynced(s, r):
continue
for hw in State.anomaly(s, r).hardware:
if s.cards[hw].name == "Quantum Coprocessor" and Query.hardware_active(s, hw) and hardware_uses_left(s, hw) > 0:
qc = hw
break
if qc != null:
break
if qc == null:
return
var ex: Dictionary = CardScripts.of(item.name).get("execution", {})
if ex.is_empty():
return
var same := {"t": item.target, "a": item.args}
var plays: Array = ex.plays.call(s, item.player).filter(func(p): return {"t": p.target, "a": p.args} != same)
if plays.is_empty():
return
var options := [{"label": "Don't copy", "value": null}]
for p in plays:
var label := "%s %s" % [p.target if p.target != null else "no target", Describe.describe_args(s, p.args, item.player)]
options.append({"label": label, "value": {"target": p.target, "args": p.args}})
State.ask(s, {
"player": item.player,
"kind": "Quantum Coprocessor:copy",
"prompt": "Quantum Coprocessor: copy %s with a different target?" % item.name,
"options": options,
"resume": {"name": "Quantum Coprocessor", "fn": "copy", "data": {"item": item, "qc": qc}},
})
static func _quantum_copy(s: Dictionary, data: Dictionary, v: Variant) -> void:
if not v:
return
use_hardware(s, data.qc)
s.cards[data.qc].disabledUntil = State.start_of(State.next_turn_of(s, data.item.player))
State.fired(s, "Quantum Coprocessor", data.item.player)
State.say(s, "Quantum Coprocessor copies %s onto %s." % [data.item.name, v.target if v.target != null else "a new target"])
var copy: Dictionary = data.item.duplicate()
copy.target = v.target
copy.args = v.args
copy.from = null
CardScripts.of(data.item.name).execution.resolve.call(s, copy)

View file

@ -0,0 +1 @@
uid://b4f3qutsfuf6y

734
engine/cards/programs.gd Normal file
View file

@ -0,0 +1,734 @@
class_name ProgramCards
## Programs (cards/programs.ts). A Program sits on a location its owner controls and its effect is
## local: "this Server" is the location it's on (or where Worm Protocol spreads it). Enemy Anomalies
## are only ever "at" your location while attacking or capturing it.
static func _enemy_of(src: Dictionary, r: Dictionary) -> bool:
return r.player != src.controller
## The first active source with this name at the location, so duplicates don't double up.
static func _first_here(s: Dictionary, src: Dictionary, loc: String) -> bool:
var named := Query.sources_named(s, src.name, loc)
return not named.is_empty() and Query.same_source(named[0], src)
## Destroys an installed Program. Hotfix (first each turn) disables it instead; otherwise Version
## Control returns it to its owner's hand.
static func destroy_program(s: Dictionary, id: int) -> void:
var loc = State.program_location(s, id)
if loc == null:
return
var owner := State.owner_of(s, id)
var here: Array = Query.sources(s).filter(func(x): return x.at == loc and x.controller == owner and x.get("virtual") == null)
var hotfix = null
for x in here:
if x.name == "Hotfix" and State.used_this_turn(s, "hotfix:%d" % x.id) == 0:
hotfix = x
break
if hotfix != null:
State.mark_used(s, "hotfix:%d" % hotfix.id)
s.cards[id].disabledUntil = maxi(s.cards[id].disabledUntil, State.start_of(State.next_turn_of(s, owner)))
State.fired(s, "Hotfix", owner)
State.say(s, "Hotfix: %s is disabled instead of destroyed." % State.name_of(s, id))
return
State.uninstall_program(s, id)
State.stat(s, "programsLost", owner)
for x in here:
if x.name == "Version Control":
State.fired(s, "Version Control", owner)
State.to_hand(s, id)
State.say(s, "Version Control: %s returns to %s's hand." % [State.name_of(s, id), State.player_name(owner)])
return
State.to_discard(s, id)
State.say(s, "%s is destroyed." % State.name_of(s, id))
## Installs a Program for free (Replication Routine).
static func _install_free(s: Dictionary, card: int, at: String) -> void:
var p := State.owner_of(s, card)
State.remove_from(s.players[p].hand, card)
s.locations[at].programs.append(card)
s.cards[card].installedTurn = s.turn
State.stat(s, "programsInstalled", p)
State.played(s, State.name_of(s, card), p)
State.say(s, "%s installs %s on %s for free." % [State.player_name(p), State.name_of(s, card), at])
Query.emit(s, "onInstall", {"card": card, "at": at, "ref": null})
## Negative things on an Anomaly that Error Correction can remove, one at a time, as options.
static func _negatives(s: Dictionary, r: Dictionary) -> Array:
var av := State.anomaly(s, r)
var out := []
if av.infection > 0:
out.append({"label": "an Infection counter", "value": "infection"})
if av.bugs > 0:
out.append({"label": "a Bug counter", "value": "bug"})
if av.permanentInfection > 0:
out.append({"label": "a permanent Infection counter", "value": "permanent"})
for hw in State.hardware_of(s, r):
if not Query.hardware_active(s, hw):
out.append({"label": "disabled %s" % State.name_of(s, hw), "value": "hw:%d" % hw})
var worst = _latest_penalty(s, av)
if worst != null:
out.append({"label": "%d Cores from %s" % [worst.cores, worst.source], "value": "mod:%d" % worst.seq})
if State.running(s, av.rootedUntil):
out.append({"label": "Packet Flood", "value": "rooted"})
if State.running(s, av.disabledUntil):
out.append({"label": "Disabled", "value": "disabled"})
return out
## The most recent active modifier that lowers an Anomaly's Cores, or null.
static func _latest_penalty(s: Dictionary, av: Dictionary) -> Variant:
var worst = null
for m in State.active_mods(s, av):
if m.cores < 0 and (worst == null or m.seq > worst.seq):
worst = m
return worst
static func _remove_negative(s: Dictionary, r: Dictionary, what: String) -> void:
var av := State.anomaly(s, r)
if what == "infection":
av.infection -= 1
elif what == "bug":
av.bugs -= 1
elif what == "permanent":
av.permanentInfection -= 1
elif what == "rooted":
av.rootedUntil = 0
elif what == "disabled":
av.disabledUntil = 0
elif what.begins_with("hw:"):
s.cards[what.substr(3).to_int()].disabledUntil = 0
elif what.begins_with("mod:"):
var seq := what.substr(4).to_int()
av.mods = av.mods.filter(func(m): return m.seq != seq)
static func scripts() -> Dictionary:
return {
# Reading: one counter per attack declared on this Server, or per capture of it that wasn't an
# attack. The -2 applies anywhere while this Program is in play, and doesn't stack with copies.
"Recursive Infection": {
"text": "Whenever an enemy Anomaly attacks or breaches this Server, place an Infection counter on it. An Anomaly with 3+ Infection counters has -2 Core.",
"onAttackDeclared": _recursive_attack,
"onBreach": _recursive_breach,
"globalCores": func(s, f): return -2 if State.infection_of(State.anomaly(s, f.ref)) >= 3 else 0,
},
# Reading: "owner" is the attacking Anomaly's owner, who picks which of its Hardware is disabled
# for that combat.
"Memory Parasite": {
"text": "Enemy Anomalies attacking this Server have 1 hardware component disabled of the owners choosing.",
"onCombatStart": _parasite_combat_start,
"resume": {"disable": _parasite_disable},
},
# Reading: installing this card counts, so it can bring a second Virus with it.
"Replication Routine": {
"text": "When you install a Virus Program on this Server, you may install a second Virus Program from your hand here for no Bandwidth cost.",
"onInstall": _replication_install,
"resume": {"install": _replication_resume},
},
# Fires on every roll the attacker loses here (with the health rule off, that's every defeat).
"Resource Leech": {
"text": "Whenever an enemy Anomaly takes damage while attacking this Server, gain 3 Gb.",
"onDamage": _leech_damage,
},
"Worm Protocol": {
"text": "The localized effects of your other Programs on this Server also apply at one adjacent Server you choose when this is installed.",
"onInstall": _worm_install,
"resume": {"spread": _worm_spread},
},
"Payload Injector": {
"text": "The first Execution you play targeting this Server each round costs 2 less Gb.",
"costMod": _payload_cost,
"onPaid": _payload_paid,
},
# Enemy Anomalies are only ever at this location while attacking it. The counter survives defeat.
"Persistent Infection": {
"text": "Whenever an enemy Anomaly takes damage at this Server, place an Infection counter on it permanently.",
"onDamage": _persistent_damage,
},
# Reading: your Anomaly attacking from this Server may declare a second attack on another
# adjacent location. Both come from this Server, even if the first one moved it.
"Infinite Loop": {
"text": "If the attacking Anomaly is controlled by the owner of this Program, it may attack a second adjacent Server in the same command.",
"extraAttacks": 1,
},
"Stack Overflow": {
"text": "Anomalies you control defending this Server gain +1 Core for each Program installed on this Server (including this one).",
"cores": _stack_overflow_cores,
},
# Both players pick at the same time; the attacker's pick stays hidden from the defender.
"Race Condition": {
"text": "During any combat at this Server, both players secretly choose Attack or Defend. If the choices differ, the defender gains a combat bonus of +2 Cores.",
"onCombatStart": _race_combat_start,
"resume": {"pick": _race_pick},
},
"Bloatware": {
"text": "At the start of any combat at this Server, the attacking Anomaly loses 1 Core for each Hardware installed on it.",
"onCombatStart": _bloatware_combat_start,
},
"Null Pointer": {
"text": "Once per round, when an enemy Execution would resolve at this Server, it's effect does not occur.",
"negates": _null_pointer_negates,
},
# Reading: "Hardware bonuses" are the Cores Hardware adds.
"Stock Rice": {
"text": "Neither Anomaly in a combat that takes place at this Server may use any Hardware bonuses.",
"blocksHardwareInCombat": true,
"onCombatStart": _stock_rice_combat_start,
},
# Every lost roll disables a Program until its controller's next command; a destroyed attacker
# lets the owner destroy it instead.
"Overflow Error": {
"text": "When an enemy Anomaly takes damage while attacking this Server, disable one Program its controller has in play until their next command. If the Anomaly was destroyed, you may destroy that Program instead.",
"onDamage": _overflow_damage,
"resume": {"hit": _overflow_hit},
},
# Reading: the copy lasts until your next turn, while this Program is disabled.
"Undefined Behavior": {
"text": "Once per round, copy the localized effect of another Program on another Server. Then disable this Program until your next command.",
"ability": {"uses": _undefined_uses, "resolve": _undefined_resolve},
},
"Packet Loss": {
"text": "When an enemy successfully breaches this Server, its controller discards a card at random.",
"onBreach": _packet_loss_breach,
},
# The once-per-turn Hardware abilities are Hot-Swap Bay's and Quantum Coprocessor's.
"Desynchronization": {
"text": "Enemy Anomalies attacking this Server cannot use their Hardware's \"once per round\" abilities during that combat.",
"blocksHardwareAbilities": true,
},
# Reading: "each turn" was removed from the card, so this works once per installation.
"Visual Artifact": {
"text": "The first attack made against an Anomaly you control at this Server suffers -1 Core.",
"onCombatStart": _artifact_combat_start,
},
# Executions check for this through CardUtil.scope_of().
"Ghost Process": {
"text": "Your Executions played targeting this Server may also affect Anomalies, Programs, and Hardware at one adjacent Server.",
},
# Runs from the engine right after an enemy Execution that targets an Anomaly is played.
"False Positive": {
"text": "When an enemy Execution targets an Anomaly you control at this Server, you may redirect it to another legal Anomaly at another Server.",
"resume": {"offer": _false_positive_offer, "redirect": _false_positive_redirect},
},
"Fragmentation": {
"text": "Executions your opponents play targeting this Server cost +2 Gb.",
"costMod": func(_s, src, pay): return 2 if pay.kind == "execution" and pay.player != src.controller and pay.get("at") == src.at else 0,
"onPaid": func(s, src, _pay): State.fired(s, "Fragmentation", src.controller),
},
"Latency Spike": {
"text": "The attacking player cannot play Executions during the first step of any combat at this Server.",
"blocksAttackerExecutions": true,
},
# Destroyed means destroyed by an effect (Overflow Error). A captured location's Programs aren't
# destroyed; they're discarded (see Version Control).
"Hotfix": {
"text": "The first Program on this Server that would be destroyed each round is instead disabled until your next command.",
},
"Error Correction": {
"text": "At the beginning of your first command each round, remove one negative counter or status from each Anomaly you control at this Server.",
"onTurnStart": _error_correction_turn_start,
"resume": {"fix": _error_correction_fix, "remove": func(s, data, what): _remove_negative(s, data.ref, what)},
},
# Reading: it can sacrifice itself.
"Garbage Collection": {
"text": "Once per round, sacrifice one Program installed on this Server to recover its printed Bandwidth value.",
"ability": {"uses": _garbage_uses, "resolve": _garbage_resolve},
},
"Version Control": {
"text": "When a Program on this Server would be destroyed, or when this Server is captured, return one Program from this Server to your hand instead of discarding it.",
"onCaptured": _version_captured,
"resume": {"save": _version_save},
},
"Rollback Routine": {
"text": "Once per round, undo the most recent temporary stat reduction applied to an Anomaly you control at this Server.",
"ability": {"uses": _rollback_uses, "resolve": _rollback_resolve},
},
"Compatibility Layer": {
"text": "This Server may hold one additional Program beyond the normal limit, and Patch Programs installed here cost 2 less Gb.",
"programSlots": 1,
"costMod": func(s, src, pay): return -2 if pay.kind == "program" and pay.player == src.controller and pay.get("at") == src.at and CardUtil.is_patch(s, pay.card) else 0,
"onPaid": func(s, src, _pay): State.fired(s, "Compatibility Layer", src.controller),
},
}
# Recursive Infection
static func _recursive_attack(s: Dictionary, src: Dictionary, ev: Dictionary) -> void:
if ev.to == src.at and _enemy_of(src, ev.ref):
CardUtil.infect(s, ev.ref, 1, "Recursive Infection", src.controller)
static func _recursive_breach(s: Dictionary, src: Dictionary, ev: Dictionary) -> void:
if ev.loc != src.at or not _enemy_of(src, ev.ref):
return
for d in s.declarations:
if d.kind == "attack" and State.same_ref(d.ref, ev.ref) and d.to == ev.loc:
return
CardUtil.infect(s, ev.ref, 1, "Recursive Infection", src.controller)
# Memory Parasite
static func _parasite_combat_start(s: Dictionary, src: Dictionary, _ev: Variant) -> void:
var c: Dictionary = s.combat
if c.loc != src.at or not _enemy_of(src, c.attacker):
return
var hw: Array = State.hardware_of(s, c.attacker).filter(func(h): return Query.hardware_active(s, h) and not c.suppressed.has(h))
if hw.is_empty():
return
State.fired(s, "Memory Parasite", src.controller)
if hw.size() == 1:
c.suppressed.append(hw[0])
State.say(s, "Memory Parasite disables %s for this combat." % State.name_of(s, hw[0]))
return
State.ask(s, {
"player": c.attacker.player,
"kind": "Memory Parasite:disable",
"prompt": "Memory Parasite: which of your Hardware is disabled for this combat?",
"options": hw.map(func(h): return {"label": State.name_of(s, h), "value": h}),
"resume": {"name": "Memory Parasite", "fn": "disable", "data": null},
})
static func _parasite_disable(s: Dictionary, _data: Variant, hw: Variant) -> void:
if s.combat != null:
s.combat.suppressed.append(hw)
# Replication Routine
static func _replication_install(s: Dictionary, src: Dictionary, ev: Dictionary) -> void:
if not src.at or ev.at != src.at or src.get("virtual") != null or not CardUtil.is_virus(s, ev.card):
return
if s.locations[src.at].programs.size() >= Query.program_slots(s, src.at):
return
var hand: Array = s.players[src.controller].hand.filter(func(id): return CardUtil.is_virus(s, id))
if hand.is_empty():
return
State.ask(s, {
"player": src.controller,
"kind": "Replication Routine:install",
"prompt": "Replication Routine: install a second Virus Program on %s for free?" % src.at,
"options": [{"label": "No", "value": null}] + CardUtil.card_options(s, hand),
"resume": {"name": "Replication Routine", "fn": "install", "data": {"at": src.at}},
})
static func _replication_resume(s: Dictionary, data: Dictionary, card: Variant) -> void:
if card == null or not State.controls(s, State.owner_of(s, card), data.at):
return
if s.locations[data.at].programs.size() >= Query.program_slots(s, data.at):
return
State.fired(s, "Replication Routine", State.owner_of(s, card))
_install_free(s, card, data.at)
# Resource Leech, Persistent Infection
static func _leech_damage(s: Dictionary, src: Dictionary, ev: Dictionary) -> void:
if ev.loc != src.at or ev.role != "attack" or not _enemy_of(src, ev.ref):
return
State.gain_bandwidth(s, src.controller, 3)
State.fired(s, "Resource Leech", src.controller)
State.say(s, "Resource Leech: %s gains 3 Gb." % State.player_name(src.controller))
static func _persistent_damage(s: Dictionary, src: Dictionary, ev: Dictionary) -> void:
if ev.loc != src.at or not _enemy_of(src, ev.ref) or State.is_copy(ev.ref):
return
CardUtil.infect(s, ev.ref, 1, "Persistent Infection", src.controller, true)
# Worm Protocol
static func _worm_install(s: Dictionary, src: Dictionary, ev: Dictionary) -> void:
if ev.card != src.id or src.get("virtual") != null:
return
var near := State.neighbors(s, src.at)
if near.is_empty():
return
State.ask(s, {
"player": src.controller,
"kind": "Worm Protocol:spread",
"prompt": "Worm Protocol on %s: spread your other Programs' effects to which adjacent location?" % src.at,
"options": near.map(func(l): return {"label": l, "value": l}),
"resume": {"name": "Worm Protocol", "fn": "spread", "data": {"card": src.id}},
})
static func _worm_spread(s: Dictionary, data: Dictionary, to: Variant) -> void:
s.cards[data.card].wormTo = to
State.fired(s, "Worm Protocol", State.owner_of(s, data.card))
# Payload Injector
static func _payload_cost(s: Dictionary, src: Dictionary, pay: Dictionary) -> int:
return -2 if pay.kind == "execution" and pay.player == src.controller and pay.get("at") == src.at \
and State.used_this_turn(s, "payload:%d" % src.id) == 0 else 0
static func _payload_paid(s: Dictionary, src: Dictionary, _pay: Dictionary) -> void:
State.mark_used(s, "payload:%d" % src.id)
State.fired(s, "Payload Injector", src.controller)
# Stack Overflow
static func _stack_overflow_cores(s: Dictionary, src: Dictionary, f: Dictionary) -> int:
if f.role == "defend" and f.at == src.at and f.ref.player == src.controller:
return Query.installed_count(s, src.at)
return 0
# Race Condition
static func _race_combat_start(s: Dictionary, src: Dictionary, _ev: Variant) -> void:
var c: Dictionary = s.combat
if c.loc != src.at or not _first_here(s, src, c.loc):
return
State.fired(s, "Race Condition", src.controller)
_ask_race(s, c.attacker.player)
static func _race_pick(s: Dictionary, data: Dictionary, pick: Variant) -> void:
var c = s.combat
if c == null or c.ended:
return
c.race[data.player] = pick
var defender: int = c.defenders[0].player if not c.defenders.is_empty() else State.other(c.attacker.player)
if data.player == c.attacker.player:
_ask_race(s, defender)
return
var a = c.race[c.attacker.player]
var d = c.race[defender]
State.say(s, "Race Condition: attacker chose %s, defender chose %s." % [Util.js(a), Util.js(d)])
if a != d and not c.defenders.is_empty():
State.add_mod(s, c.defenders[0], 2, "Race Condition", defender, {"combat": c.id})
State.say(s, "The choices differ: the defender gets +2 Cores.")
static func _ask_race(s: Dictionary, player: int) -> void:
State.ask(s, {
"player": player,
"kind": "Race Condition:pick",
"secret": true,
"prompt": "Race Condition: secretly choose Attack or Defend.",
"options": [{"label": "Attack", "value": "attack"}, {"label": "Defend", "value": "defend"}],
"resume": {"name": "Race Condition", "fn": "pick", "data": {"player": player}},
})
# Bloatware, Stock Rice, Visual Artifact
static func _bloatware_combat_start(s: Dictionary, src: Dictionary, _ev: Variant) -> void:
var c: Dictionary = s.combat
if c.loc != src.at or not _enemy_of(src, c.attacker) or Query.bug_immune(s, c.attacker, src.controller):
return
var n: int = State.hardware_of(s, c.attacker).size()
if n == 0:
return
State.add_mod(s, c.attacker, -n, "Bloatware", src.controller, {"combat": c.id})
State.fired(s, "Bloatware", src.controller)
State.say(s, "Bloatware: %s loses %d Core%s." % [State.anomaly_name(s, c.attacker), n, "" if n == 1 else "s"])
static func _stock_rice_combat_start(s: Dictionary, src: Dictionary, _ev: Variant) -> void:
if s.combat.loc == src.at:
State.fired(s, "Stock Rice", src.controller)
static func _artifact_combat_start(s: Dictionary, src: Dictionary, _ev: Variant) -> void:
var c: Dictionary = s.combat
if c.loc != src.at or s.cards[src.id].get("spent", false):
return
var guarding := false
for d in c.defenders:
if d.player == src.controller:
guarding = true
if not guarding:
return
s.cards[src.id].spent = true
State.add_mod(s, c.attacker, -1, "Visual Artifact", src.controller, {"combat": c.id})
State.fired(s, "Visual Artifact", src.controller)
State.say(s, "Visual Artifact: %s gets -1 Core." % State.anomaly_name(s, c.attacker))
# Null Pointer
static func _null_pointer_negates(s: Dictionary, src: Dictionary, item: Dictionary) -> bool:
if item.player == src.controller or item.target != src.at or State.used_this_turn(s, "null:%d" % src.id) > 0:
return false
State.mark_used(s, "null:%d" % src.id)
State.fired(s, "Null Pointer", src.controller)
State.say(s, "Null Pointer: %s has no effect." % item.name)
return true
# Overflow Error
static func _overflow_damage(s: Dictionary, src: Dictionary, ev: Dictionary) -> void:
if ev.loc != src.at or ev.role != "attack" or not _enemy_of(src, ev.ref):
return
var theirs := []
for l in GameMap.LOCATIONS:
if State.controls(s, ev.ref.player, l):
for id in CardUtil.programs_on(s, l):
if Query.can_target_program(s, id, src.controller):
theirs.append(id)
if theirs.is_empty():
return
State.fired(s, "Overflow Error", src.controller)
var options := []
for id in theirs:
var where := "%s on %s" % [State.name_of(s, id), State.program_location(s, id)]
if ev.destroyed:
options.append({"label": "Destroy %s" % where, "value": {"card": id, "mode": "destroy"}})
options.append({"label": "Disable %s" % where, "value": {"card": id, "mode": "disable"}})
State.ask(s, {
"player": src.controller,
"kind": "Overflow Error:hit",
"prompt": "Overflow Error: destroy or disable one of their Programs." if ev.destroyed else "Overflow Error: disable one of their Programs.",
"options": options,
"resume": {"name": "Overflow Error", "fn": "hit", "data": null},
})
static func _overflow_hit(s: Dictionary, _data: Variant, v: Variant) -> void:
if State.program_location(s, v.card) == null:
return
if v.mode == "destroy":
destroy_program(s, v.card)
else:
var until := State.start_of(State.next_turn_of(s, State.owner_of(s, v.card)))
s.cards[v.card].disabledUntil = maxi(s.cards[v.card].disabledUntil, until)
# Undefined Behavior
static func _undefined_uses(s: Dictionary, src: Dictionary) -> Array:
if src.kind != "program" or src.get("virtual") != null:
return []
var out := []
for l in GameMap.LOCATIONS:
if l == src.at:
continue
for id in CardUtil.programs_on(s, l):
if State.name_of(s, id) != "Undefined Behavior" and Query.can_target_program(s, id, src.controller):
out.append({"card": id})
return out
static func _undefined_resolve(s: Dictionary, item: Dictionary, src: Dictionary) -> void:
var card: int = item.args.card
if State.program_location(s, card) == null:
return
var until := State.start_of(State.next_turn_of(s, src.controller))
s.seq += 1
s.virtuals.append({"id": s.seq, "name": State.name_of(s, card), "controller": src.controller, "at": src.at, "until": until, "installed": false, "from": card})
s.cards[src.id].disabledUntil = maxi(s.cards[src.id].disabledUntil, until)
State.fired(s, "Undefined Behavior", src.controller)
State.say(s, "Undefined Behavior on %s copies %s and shuts itself off until %s's next turn." % [src.at, State.name_of(s, card), State.player_name(src.controller)])
# Packet Loss
static func _packet_loss_breach(s: Dictionary, src: Dictionary, ev: Dictionary) -> void:
if ev.loc != src.at or not _enemy_of(src, ev.ref):
return
var hand: Array = s.players[ev.ref.player].hand
if hand.is_empty():
return
var card: int = hand[Rng.rand_int(s.rng, hand.size())]
State.remove_from(hand, card)
State.to_discard(s, card)
State.fired(s, "Packet Loss", src.controller)
State.say(s, "Packet Loss: %s discards %s at random." % [State.player_name(ev.ref.player), State.name_of(s, card)])
# False Positive
static func _false_positive_offer(s: Dictionary, data: Dictionary, _value: Variant) -> void:
if data.index >= s.stack.size():
return
var item: Dictionary = s.stack[data.index]
var ex: Dictionary = CardScripts.of(item.name).get("execution", {})
var hit: Array = ex.targetsAnomalies.call(s, item) if ex.has("targetsAnomalies") else []
var guarded = null
for r in hit:
if r.player == item.player:
continue
var at = State.anomaly(s, r).at
for x in Query.sources(s):
if x.name == "False Positive" and x.at == at and x.controller == r.player:
guarded = r
break
if guarded != null:
break
if ex.is_empty() or guarded == null:
return
var from = State.anomaly(s, guarded).at
var options := [{"label": "Leave it", "value": null}]
for play in ex.plays.call(s, item.player):
var refs: Array = ex.targetsAnomalies.call(s, {"player": item.player, "target": play.target, "args": play.args}) if ex.has("targetsAnomalies") else []
if refs.is_empty():
continue
var away := true
for r in refs:
if State.anomaly(s, r).at == from or State.same_ref(r, guarded):
away = false
if not away:
continue
var whom := State.anomaly_name(s, play.args.ref) if play.args.get("ref") != null else State.name_of(s, play.args.get("card", -1))
options.append({"label": "Redirect to %s on %s" % [whom, Util.js(play.target)], "value": {"index": data.index, "target": play.target, "args": play.args}})
if options.size() == 1:
return
State.ask(s, {
"player": guarded.player,
"kind": "False Positive:redirect",
"prompt": "False Positive: redirect %s away from %s?" % [item.name, State.anomaly_name(s, guarded)],
"options": options,
"resume": {"name": "False Positive", "fn": "redirect", "data": null},
})
static func _false_positive_redirect(s: Dictionary, _data: Variant, v: Variant) -> void:
if v == null or v.index >= s.stack.size():
return
var item: Dictionary = s.stack[v.index]
item.target = v.target
item.args = v.args
State.fired(s, "False Positive", State.other(item.player))
# Error Correction
static func _error_correction_turn_start(s: Dictionary, src: Dictionary, _ev: Variant) -> void:
if s.active != src.controller:
return
var tasks := []
for r in State.refs_in_play(s, src.controller):
if State.anomaly(s, r).at == src.at:
tasks.append(State.later("Error Correction", "fix", {"ref": r}))
State.push_tasks(s, tasks)
static func _error_correction_fix(s: Dictionary, data: Dictionary, _value: Variant) -> void:
var list := _negatives(s, data.ref)
if list.is_empty():
return
State.fired(s, "Error Correction", data.ref.player)
if list.size() == 1:
_remove_negative(s, data.ref, list[0].value)
State.say(s, "Error Correction removes %s from %s." % [list[0].label, State.anomaly_name(s, data.ref)])
return
State.ask(s, {
"player": data.ref.player,
"kind": "Error Correction:remove",
"prompt": "Error Correction: remove what from %s?" % State.anomaly_name(s, data.ref),
"options": list,
"resume": {"name": "Error Correction", "fn": "remove", "data": {"ref": data.ref}},
})
# Garbage Collection
static func _garbage_uses(s: Dictionary, src: Dictionary) -> Array:
if src.kind != "program":
return []
return s.locations[src.at].programs.map(func(card): return {"card": card})
static func _garbage_resolve(s: Dictionary, item: Dictionary, src: Dictionary) -> void:
var card: int = item.args.card
if State.program_location(s, card) != src.at:
return
State.uninstall_program(s, card)
State.to_discard(s, card)
State.stat(s, "programsLost", src.controller)
State.gain_bandwidth(s, src.controller, State.def_of(s, card).bandwidth)
State.fired(s, "Garbage Collection", src.controller)
State.say(s, "Garbage Collection sacrifices %s for %d Gb." % [State.name_of(s, card), State.def_of(s, card).bandwidth])
# Version Control
static func _version_captured(s: Dictionary, src: Dictionary, ev: Dictionary) -> void:
if ev.loc != src.at or src.get("virtual") != null:
return
var here: Array = s.locations[ev.loc].programs
if here.is_empty():
return
State.ask(s, {
"player": src.controller,
"kind": "Version Control:save",
"prompt": "Version Control: %s is being captured. Return which Program to your hand?" % ev.loc,
"options": here.map(func(id): return {"label": State.name_of(s, id), "value": id}),
"resume": {"name": "Version Control", "fn": "save", "data": null},
})
static func _version_save(s: Dictionary, _data: Variant, card: Variant) -> void:
if State.uninstall_program(s, card) == null:
return
State.to_hand(s, card)
State.fired(s, "Version Control", State.owner_of(s, card))
State.say(s, "Version Control returns %s to %s's hand." % [State.name_of(s, card), State.player_name(State.owner_of(s, card))])
# Rollback Routine
static func _rollback_uses(s: Dictionary, src: Dictionary) -> Array:
if src.kind != "program":
return []
var out := []
for r in State.refs_in_play(s, src.controller):
if State.anomaly(s, r).at == src.at and _latest_penalty(s, State.anomaly(s, r)) != null:
out.append({"ref": r})
return out
static func _rollback_resolve(s: Dictionary, item: Dictionary, src: Dictionary) -> void:
var av := State.anomaly(s, item.args.ref)
if av.at != src.at:
return
var last = _latest_penalty(s, av)
if last == null:
return
av.mods = av.mods.filter(func(m): return m.seq != last.seq)
State.fired(s, "Rollback Routine", src.controller)
State.say(s, "Rollback Routine undoes %d Cores from %s on %s." % [last.cores, last.source, State.anomaly_name(s, item.args.ref)])

View file

@ -0,0 +1 @@
uid://q4cltmsskkvf

195
engine/cards/servers.gd Normal file
View file

@ -0,0 +1,195 @@
class_name ServerCards
## Servers (cards/servers.ts). A Server's ability belongs to the player who controls its location and
## applies at that location, unless the text says otherwise.
static func scripts() -> Dictionary:
return {
"High Bandwidth Server": {"text": "Add additional 4 Gb to resource total", "bandwidthOnPlace": 4},
"Power Server": {"text": "Add additional 4 Gb to resource total", "bandwidthOnPlace": 4},
"Server Farm": {
"text": "Add 4 Gb to resource total and 2 Cores to any Anomaly",
"bandwidthOnPlace": 4,
"cores": _core_bonus.bind(2),
},
"MultiCore Server": {"text": "Add 2 Cores to any Anomalies", "cores": _core_bonus.bind(2)},
"Cloud Compute": {"text": "Add 4 Cores to any Anomalies", "cores": _core_bonus.bind(4)},
"Cluster Server": {"text": "Up to 2 Anomalies can defend this Server", "capacity": 2},
"Pingable Server": {"text": "Up to 2 Anomalies can defend this Server", "capacity": 2},
# Reading: once per turn, at any time, make a copy of your Anomaly based here (Carbon NanoBots'
# copy rules). The copy enters play on any location you control with room.
"Backup Server": {
"text": "Duplicate Anomaly based at this Server",
"ability": {"uses": _backup_uses, "resolve": _backup_resolve},
},
"Upgraded Hardware": {
"text": "Hardware upgrades cost 2 less Gb to install",
"costMod": _upgraded_cost,
"onPaid": _fired_by_controller.bind("Upgraded Hardware"),
},
"Network Throttle": {
"text": "Firewalls cost 1 less Gb to install",
"costMod": _throttle_cost,
"onPaid": _fired_by_controller.bind("Network Throttle"),
},
# Reading: when placed, pick one adjacent Server (either player's) and gain its ability for as
# long as this card stays. A copied Bandwidth bonus is paid right away.
"Duplicate Server": {
"text": "Copy one adjacent Server ability",
"onPlaced": _duplicate_placed,
"resume": {"copy": _duplicate_copy},
},
"Protected Server": {
"text": "Add 2 Gb if defending this Server",
"onCombatStart": _protected_combat_start,
},
# Reading: applies to every draw after the opening hand, once per card drawn.
"Callable Server": {
"text": "When drawing a card, you may choose to place it on the bottom of the deck and draw another",
"onDraw": _callable_draw,
"resume": {"redraw": _callable_redraw},
},
}
## Core bonus for the controller's Anomaly standing on this Server (attacking from it or defending it).
static func _core_bonus(_s: Dictionary, src: Dictionary, f: Dictionary, n: int) -> int:
return n if f.at == src.at and f.ref.player == src.controller else 0
static func _fired_by_controller(s: Dictionary, src: Dictionary, _pay: Dictionary, card_name: String) -> void:
State.fired(s, card_name, src.controller)
# Backup Server
static func _backup_uses(s: Dictionary, src: Dictionary) -> Array:
var p: int = src.controller
if not Query.can_copy(s, p):
return []
var spots: Array = GameMap.LOCATIONS.filter(func(l): return Query.has_room(s, p, l))
var out := []
for r in State.refs_in_play(s, p):
if not State.is_copy(r) and State.anomaly(s, r).at == src.at and State.anomaly(s, State.copy_of(r)).at == null:
for to in spots:
out.append({"ref": r, "to": to})
return out
static func _backup_resolve(s: Dictionary, item: Dictionary, _src: Dictionary) -> void:
var r: Dictionary = item.args.ref
var to: String = item.args.to
if State.anomaly(s, r).at == null or State.anomaly(s, State.copy_of(r)).at != null or not Query.can_copy(s, r.player) \
or not Query.has_room(s, r.player, to):
return
State.fired(s, "Backup Server", r.player)
Flow.create_copy(s, r, to)
# Upgraded Hardware, Network Throttle
static func _upgraded_cost(_s: Dictionary, src: Dictionary, pay: Dictionary) -> int:
return -2 if pay.kind == "hardware" and pay.player == src.controller and pay.get("at") == src.at else 0
static func _throttle_cost(_s: Dictionary, src: Dictionary, pay: Dictionary) -> int:
if pay.kind != "firewall" or pay.player != src.controller:
return 0
var line: Dictionary = GameMap.LINE_BY_ID[pay.line]
return -1 if line.a == src.at or line.b == src.at else 0
# Duplicate Server
static func _duplicate_placed(s: Dictionary, src: Dictionary, ev: Dictionary) -> void:
if ev.card != src.id or src.get("virtual") != null:
return
var names := []
for n in State.neighbors(s, src.at):
var sv = s.locations[n].server
if sv != null and State.name_of(s, sv) != "Duplicate Server" and not names.has(State.name_of(s, sv)):
names.append(State.name_of(s, sv))
if names.is_empty():
return
State.ask(s, {
"player": src.controller,
"kind": "Duplicate Server:copy",
"prompt": "Duplicate Server on %s: copy which adjacent Server?" % src.at,
"options": names.map(func(n): return {"label": n, "value": n}),
"resume": {"name": "Duplicate Server", "fn": "copy", "data": {"card": src.id, "player": src.controller}},
})
static func _duplicate_copy(s: Dictionary, data: Dictionary, server_name: String) -> void:
s.cards[data.card].copies = server_name
var p: int = data.player
State.fired(s, "Duplicate Server", p)
State.say(s, "Duplicate Server copies %s." % server_name)
var bonus: int = scripts().get(server_name, {}).get("bandwidthOnPlace", 0)
if bonus:
State.gain_bandwidth(s, p, bonus, "bandwidthFromCaptures")
State.say(s, "%s gains %d Gb from the copied ability." % [State.player_name(p), bonus])
# Protected Server
static func _protected_combat_start(s: Dictionary, src: Dictionary, _ev: Variant) -> void:
var c: Dictionary = s.combat
if c.loc != src.at:
return
var defending := false
for d in State.defenders_at(s, c.loc):
if d.player == src.controller:
defending = true
if not defending:
return
State.gain_bandwidth(s, src.controller, 2)
State.fired(s, "Protected Server", src.controller)
State.say(s, "Protected Server: %s gains 2 Gb for defending." % State.player_name(src.controller))
# Callable Server
static func _callable_draw(s: Dictionary, src: Dictionary, ev: Dictionary) -> void:
if ev.player != src.controller or s.players[ev.player].deck.is_empty():
return
var first = null
for x in Query.sources_named(s, "Callable Server"):
if x.controller == ev.player:
first = x
break
if first == null or not Query.same_source(first, src):
return
if not s.players[ev.player].hand.has(ev.card):
return
var nm := State.name_of(s, ev.card)
State.ask(s, {
"player": ev.player,
"kind": "Callable Server:redraw",
"secret": true,
"prompt": "Callable Server: keep %s, or put it on the bottom and draw another?" % nm,
"options": [
{"label": "Keep %s" % nm, "value": false},
{"label": "Bottom %s and draw again" % nm, "value": true},
],
"resume": {"name": "Callable Server", "fn": "redraw", "data": {"player": ev.player, "card": ev.card}},
})
static func _callable_redraw(s: Dictionary, data: Dictionary, again: Variant) -> void:
if not again:
return
var pl: Dictionary = s.players[data.player]
if not State.remove_from(pl.hand, data.card):
return
pl.deck.append(data.card)
State.fired(s, "Callable Server", data.player)
Flow.draw_now(s, data.player)
s.stats.cardsDrawn[data.player] -= 1
State.say(s, "%s bottoms a card and draws again." % State.player_name(data.player))

View file

@ -0,0 +1 @@
uid://cs1kmjh8ijwvv

106
engine/cards/util.gd Normal file
View file

@ -0,0 +1,106 @@
class_name CardUtil
## Helpers shared by card scripts (cards/util.ts).
## Locations where `p` has Ghost Process working, as a Dictionary used as a set.
static func ghosts_of(s: Dictionary, p: int) -> Dictionary:
var out := {}
for x in Query.sources(s):
if x.name == "Ghost Process" and x.controller == p:
out[x.at] = true
return out
## Locations an Execution played on `target` can reach: Ghost Process adds one adjacent location.
## Pass `ghosts` (from ghosts_of) when calling it for many targets.
static func scope_of(s: Dictionary, p: int, target: String, ghosts: Variant = null) -> Array:
if ghosts == null:
ghosts = ghosts_of(s, p)
return [target] + State.neighbors(s, target) if ghosts.has(target) else [target]
static func mine(s: Dictionary, p: int, loc: String) -> Array:
return State.at_server(s, loc).filter(func(r): return r.player == p)
## Active, installed Programs on a location.
static func programs_on(s: Dictionary, loc: String) -> Array:
return s.locations[loc].programs.filter(func(id): return Query.program_active(s, id))
static func active_hardware(s: Dictionary, ids: Array) -> Array:
return ids.filter(func(id): return Query.hardware_active(s, id))
## Places Bug counters: like Infection counters, for Bug cards. No card places them yet. ECC Memory
## stops opponents from placing them.
static func add_bugs(s: Dictionary, r: Dictionary, n: int, source: String, by: int) -> bool:
if Query.bug_immune(s, r, by):
State.say(s, "ECC Memory blocks %s's Bug counters on %s." % [source, State.anomaly_name(s, r)])
State.fired(s, "ECC Memory", r.player)
return false
State.anomaly(s, r).bugs += n
State.fired(s, source, by)
State.say(s, "%s: %s gets %d Bug counter%s (%d total)." % [source, State.anomaly_name(s, r), n, "" if n == 1 else "s", State.anomaly(s, r).bugs])
return true
static func infect(s: Dictionary, r: Dictionary, n: int, source: String, by: int, permanent := false) -> void:
var av := State.anomaly(s, r)
if permanent:
av.permanentInfection += n
else:
av.infection += n
State.fired(s, source, by)
State.say(s, "%s: %s gets %s %sInfection counter%s (%d total)." % [source, State.anomaly_name(s, r), "an" if n == 1 else str(n), "permanent " if permanent else "", "" if n == 1 else "s", av.infection + av.permanentInfection])
## One option per distinct card name.
static func card_options(s: Dictionary, ids: Array) -> Array:
var seen := {}
var out := []
for id in ids:
var nm := State.name_of(s, id)
if seen.has(nm):
continue
seen[nm] = true
out.append({"label": nm, "value": id})
return out
static func is_virus(s: Dictionary, id: int) -> bool:
var d := State.def_of(s, id)
return d.kind == "program" and d.type == "V"
static func is_patch(s: Dictionary, id: int) -> bool:
var d := State.def_of(s, id)
return d.kind == "program" and d.type == "P"
static func whose(p: int) -> String:
return State.player_name(p)
## Distinct non-empty subsets of up to 3 items.
static func subsets(items: Array) -> Array:
var out := []
var n := mini(items.size(), 3)
for mask in range(1, 1 << n):
var sub := []
for i in n:
if mask & (1 << i):
sub.append(items[i])
out.append(sub)
return out
static func src_label(s: Dictionary, src: Dictionary) -> String:
if src.kind == "anomaly":
var d := State.def_of(s, src.id)
return "%s (%s)" % [Util.js(d.ability.name if d.has("ability") else null), src.name]
return src.name
static func every_anomaly_in_play(s: Dictionary) -> Array:
return State.refs_in_play(s, 0) + State.refs_in_play(s, 1)

1
engine/cards/util.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dgxib28v7i72s

62
engine/csv.gd Normal file
View file

@ -0,0 +1,62 @@
class_name Csv
## Minimal RFC 4180 parser (csv.ts): quoted fields, "" escapes, and commas or newlines inside quotes.
static func parse(text: String) -> Array:
var rows := []
var row := []
var field := ""
var quoted := false
var n := text.length()
var i := 0
while i < n:
var ch := text[i]
if quoted:
if ch != "\"":
field += ch
elif i + 1 < n and text[i + 1] == "\"":
field += "\""
i += 1
else:
quoted = false
elif ch == "\"":
quoted = true
elif ch == ",":
row.append(field)
field = ""
elif ch == "\n" or ch == "\r":
if ch == "\r" and i + 1 < n and text[i + 1] == "\n":
i += 1
row.append(field)
rows.append(row)
row = []
field = ""
else:
field += ch
i += 1
if field != "" or row.size() > 0:
row.append(field)
rows.append(row)
return rows
## Rows keyed by header name, skipping blank lines.
static func parse_objects(text: String) -> Array:
var rows := parse(text)
if rows.is_empty():
return []
var header: Array = rows[0]
var out := []
for r in rows.slice(1):
var blank := true
for f in r:
if f != "":
blank = false
break
if blank:
continue
var obj := {}
for i in header.size():
obj[header[i]] = r[i] if i < r.size() else ""
out.append(obj)
return out

1
engine/csv.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dopecc2vmjwva

55
engine/deck.gd Normal file
View file

@ -0,0 +1,55 @@
class_name Deck
## Deck lists (deck.ts). A deck list is {anomalies, servers, main}: lists of card names. `main` holds
## the Executions, Hardware and Programs (and Anomalies, when recruiting).
const MAIN_KINDS := ["program", "hardware", "execution"]
## Problems with a deck list; empty when it's legal.
static func validate_deck(pool: Dictionary, deck: Dictionary, rules: Dictionary) -> Array:
var errors := []
var part := func(label: String, names: Array, kinds: Array, size: int) -> void:
if names.size() != size:
errors.append("%s: %d cards, needs %d" % [label, names.size(), size])
for n in names:
var card = pool.by_name.get(n)
if card == null:
errors.append("%s: unknown card \"%s\"" % [label, n])
elif not kinds.has(card.kind):
errors.append("%s: \"%s\" is a %s" % [label, n, card.kind])
part.call("Anomalies", deck.anomalies, ["anomaly"], Rules.anomalies_outside(rules))
part.call("Servers", deck.servers, ["server"], rules.deck.servers)
var main_kinds: Array = MAIN_KINDS + ["anomaly"] if rules.recruit.on else MAIN_KINDS
part.call("Deck", deck.main, main_kinds, rules.deck.main)
var copies := {}
for n in deck.anomalies + deck.servers + deck.main:
copies[n] = copies.get(n, 0) + 1
for n in copies:
if copies[n] > rules.deck.maxCopies:
errors.append("%d copies of \"%s\", max %d" % [copies[n], n, rules.deck.maxCopies])
return errors
## A random legal deck: every card in the pool is equally likely, up to the copy limit. `include`
## (a Callable taking a card def) limits the pool.
static func random_deck(pool: Dictionary, rng: Dictionary, rules: Dictionary, include := Callable()) -> Variant:
var sample := func(kinds: Array, size: int) -> Array:
var names := []
for c in pool.all:
if kinds.has(c.kind) and (not include.is_valid() or include.call(c)):
for i in rules.deck.maxCopies:
names.append(c.name)
if names.size() < size:
Util.fail("Not enough %s cards for a deck" % "/".join(kinds))
return []
return Rng.shuffle(rng, names).slice(0, size)
if rules.recruit.on:
var k: int = rules.recruit.anomaliesInDeck
var anomalies: Array = sample.call(["anomaly"], 1 + k)
var servers: Array = sample.call(["server"], rules.deck.servers)
var rest: Array = sample.call(MAIN_KINDS, rules.deck.main - k)
return {"anomalies": anomalies.slice(0, 1), "servers": servers, "main": Rng.shuffle(rng, anomalies.slice(1) + rest)}
var anomalies: Array = sample.call(["anomaly"], rules.deck.anomalies)
var servers: Array = sample.call(["server"], rules.deck.servers)
var main: Array = sample.call(MAIN_KINDS, rules.deck.main)
return {"anomalies": anomalies, "servers": servers, "main": main}

1
engine/deck.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dcqsdsw3lbfaw

176
engine/describe.gd Normal file
View file

@ -0,0 +1,176 @@
class_name Describe
## Readable labels for actions, for people choosing them (describe.ts): the move list and prompts.
## Labels are written for the deciding player: "your" things are unmarked, the opponent's say whose
## they are. Nothing here names a card the decider can't see.
## Default for the `me` arguments: label for whoever decides now. Pass null for no viewer.
const DECIDER := -1
const STEP_NAMES := {"deploy": "Deploy", "play": "Play", "attack": "Attack", "resolve": "Resolve", "playAgain": "Play again"}
static var _paren_re := RegEx.create_from_string(" \\((.*)\\)$")
## "A2–B1" for a line id like "A2-B1".
static func line_name(line: String) -> String:
var l = GameMap.LINE_BY_ID.get(line)
return "%s–%s" % [l.a, l.b] if l != null else line
static func _me(s: Dictionary, me: Variant) -> Variant:
return RulesEngine.decider(s) if me is int and me == DECIDER else me
## "Anomaly 2 (Glitch)", or "the copy of Anomaly 2 (Glitch)"; the opponent's say "North's".
static func ref_name(s: Dictionary, r: Dictionary, me: Variant = DECIDER) -> String:
me = _me(s, me)
var n: int = State.original_of(r).slot
var card: int = State.anomaly(s, r).card
var nm := "face down" if card < 0 or not State.anomaly(s, State.original_of(r)).faceUp else State.name_of(s, card)
var whose := "%s's " % State.player_name(r.player) if me != null and r.player != me else ""
return ("%scopy of Anomaly %d (%s)" if r.slot > 4 else "%sAnomaly %d (%s)") % [whose, n, nm]
## Where a card is, for telling two same-named cards apart: " on C2", " on Anomaly 1 (Glitch)",
## " from hand".
static func _card_where(s: Dictionary, id: int, me: Variant) -> String:
var loc = State.program_location(s, id)
if loc != null:
return " on %s" % loc
var r = State.wearer_of(s, id)
if r != null:
return " on %s" % ref_name(s, r, me)
var pl: Dictionary = s.players[s.cards[id].owner]
if pl.hand.has(id):
return " from hand"
if pl.discard.has(id):
return " from the discard pile"
return ""
static func _card_name(s: Dictionary, id: int, me: Variant) -> String:
if id < 0:
return State.name_of(s, id)
var owner: int = s.cards[id].owner
var whose := "%s's " % State.player_name(owner) if me != null and owner != me else ""
return "%s%s%s" % [whose, State.name_of(s, id), _card_where(s, id, me)]
## Execution and Ability arguments: "Anomaly 2 (Glitch) → C1", "destroy Overclocked CPU on …".
static func describe_args(s: Dictionary, a: Dictionary, me: Variant = DECIDER, to_word := "at") -> String:
me = _me(s, me)
var parts := []
if a.get("heal", false):
parts.append("heal this Anomaly")
if a.get("ref") != null:
parts.append(ref_name(s, a.ref, me))
if a.get("card") != null:
var nm := _card_name(s, a.card, me)
if a.get("mode"):
parts.append("%s %s" % [a.mode, nm])
elif a.get("cards") != null:
parts.append("swap out %s" % nm)
else:
parts.append(nm)
if a.get("cards") != null and not a.cards.is_empty():
var names := ", ".join(a.cards.map(func(id): return _card_name(s, id, me)))
parts.append("%s%s" % ["for " if a.get("card") != null else "", names])
if a.get("to"):
parts.append("→ %s" % a.to if a.get("ref") != null else "%s %s" % [to_word, a.to])
if a.get("k") != null:
parts.append("reroll dice showing %d or less" % a.k)
return " ".join(parts)
static func _gb(n: int) -> String:
return " (%d Gb)" % n
## A label for one of the current legal actions, e.g. "Play Execute: Force Reboot on D2 (5 Gb)".
static func describe_action(s: Dictionary, a: Dictionary) -> String:
var me = RulesEngine.decider(s)
if me == null:
me = s.active
var cost := RulesEngine.action_cost(s, a)
match a.type:
"end":
if s.step == "playAgain":
return "End command" if s.rules.commands.on else "End turn"
if s.step == "attack":
return "End Attack step and resolve"
return "End %s step" % STEP_NAMES[s.step]
"pass":
return "Pass"
"choose":
var o = s.choice.options[a.index] if s.choice != null and a.index < s.choice.options.size() else null
var label: String = o.label if o != null else "Option %d" % (a.index + 1)
return label + (_gb(o.cost) if o != null and o.get("cost", 0) else "")
"place":
var r := State.ref(me, a.slot)
var av := State.anomaly(s, r)
if av.at == null:
return "Place %s on %s" % [ref_name(s, r, me), a.to]
return "Move %s %s → %s" % [ref_name(s, r, me), av.at, a.to]
"recall":
var r := State.ref(me, a.slot)
var hurt := Query.health_of(s, r) - Query.health_left(s, r) if s.rules.health.on else 0
return "Recall %s from %s%s" % [ref_name(s, r, me), State.anomaly(s, r).at, ", healing %d" % hurt if hurt else ""]
"advance":
var r := State.ref(me, a.slot)
return "Advance %s %s → %s" % [ref_name(s, r, me), State.anomaly(s, r).at, a.to]
"attack":
var r := State.ref(me, a.slot)
return "Attack %s with %s from %s" % [a.to, ref_name(s, r, me), State.anomaly(s, r).at]
"clearFirewall":
return "Clear the Lv %d Firewall on %s%s" % [s.firewalls[a.line], line_name(a.line), _gb(cost)]
"firewall":
if s.firewalls.get(a.line, 0):
return "Upgrade the Firewall on %s to Lv %d%s" % [line_name(a.line), a.level, _gb(cost)]
return "Place a Lv %d Firewall on %s%s" % [a.level, line_name(a.line), _gb(cost)]
"salvage":
return "Salvage %s (+%d Gb)" % [State.name_of(s, a.card), State.def_of(s, a.card).bandwidth]
"installHardware":
return "Install %s on %s%s" % [State.name_of(s, a.card), ref_name(s, State.ref(me, a.slot), me), _gb(cost)]
"recruit":
var old := State.anomaly(s, State.ref(me, a.slot))
var retiring := ", retiring %s" % State.name_of(s, old.card) if old.card >= 0 else ""
return "Recruit %s as Anomaly %d%s%s" % [State.name_of(s, a.card), a.slot, retiring, _gb(cost)]
"buyAnomaly":
var sale = RulesEngine.anomaly_for_sale(s, me)
return "Buy Anomaly %d (face down)%s" % [a.slot, _gb(sale.price if sale != null else cost)]
"installProgram":
return "Install %s on %s%s" % [State.name_of(s, a.card), a.at, _gb(cost)]
"play":
# Packet Flood and Purge name the location they hit; it's the target unless Ghost Process widens it.
var args_text := ""
if a.args.get("to") == a.target and a.args.get("ref") == null:
var shown: Dictionary = a.args.duplicate()
shown.erase("to")
args_text = describe_args(s, shown, me)
else:
args_text = describe_args(s, a.args, me)
var on := " on %s" % a.target if a.target else ""
var from := ", performed by %s" % a.from if a.from else ""
return "Play %s%s%s%s%s" % [State.name_of(s, a.card), on, ": %s" % args_text if args_text else "", from, _gb(cost)]
"activate":
var src = RulesEngine.ability_source(s, a.card, a.name)
var d := State.def_of(s, a.card)
var label := ""
if src != null and src.kind == "anomaly" and src.get("ref") != null:
var ability_name: String = d.ability.name if d.has("ability") else a.name
label = "%s (%s)" % [ability_name, _paren_re.sub(ref_name(s, src.ref, me), ", $1")]
elif a.name != d.name:
label = "%s (copied by %s)" % [a.name, d.name]
else:
label = a.name
var where := ""
if src != null and src.kind == "hardware" and src.get("ref") != null:
where = " on %s" % ref_name(s, src.ref, me)
elif src != null and src.kind != "anomaly" and src.at:
where = " on %s" % src.at
var args_text := describe_args(s, a.args, me, "→")
var joined := ""
if args_text:
joined = (" " if args_text.begins_with("→") else ": ") + args_text
return "Use %s%s%s%s" % [label, where, joined, _gb(cost) if cost else ""]
return Util.fail("Unknown action type %s" % a.type)

1
engine/describe.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dlfmtcv7a0urk

1050
engine/engine.gd Normal file

File diff suppressed because it is too large Load diff

1
engine/engine.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cfxcxi5k1le8x

540
engine/flow.gd Normal file
View file

@ -0,0 +1,540 @@
class_name Flow
## The parts of a turn that run on their own once started (flow.ts): resolving declarations,
## combat, defeat, capture and drawing. Card scripts call into these too (Trace Route starts a
## combat, Disconnect pulls an Anomaly out of one).
## Lets an app see each combat as it happens, since a whole combat can run inside one
## apply_action. Called with (s, stage) after a combat starts ("start"), after the roll ("roll"),
## before the result is applied, with the final dice ("result"), and when it ends ("end"). Unset in
## the sim and tests.
static var combat_watch := Callable()
# ---------------------------------------------------------------------------------------------
# Drawing
static func draw_cards(s: Dictionary, p: int, n: int) -> void:
var tasks := []
for i in n:
tasks.append({"t": "draw", "player": p})
State.push_tasks(s, tasks)
## Draws one card without "when drawing" effects. Returns it, or null for an empty deck.
static func draw_now(s: Dictionary, p: int) -> Variant:
var pl: Dictionary = s.players[p]
if pl.deck.is_empty():
return null
var card: int = pl.deck.pop_front()
pl.hand.append(card)
State.stat(s, "cardsDrawn", p)
return card
static func draw_task(s: Dictionary, p: int) -> void:
var card = draw_now(s, p)
if card != null:
Query.emit(s, "onDraw", {"player": p, "card": card})
# ---------------------------------------------------------------------------------------------
# Anomalies leaving and entering play
static func _clear_status(av: Dictionary) -> void:
av.infection = 0
av.bugs = 0
av.mods = []
av.disabledUntil = 0
av.rootedUntil = 0
av.damage = 0
## A copy leaves play. It has no Hardware of its own.
static func remove_copy(s: Dictionary, r: Dictionary) -> void:
var cp := State.anomaly(s, r)
if cp.at == null:
return
State.say(s, "%s is removed." % State.anomaly_name(s, r), {"tag": "move", "player": r.player, "ref": r})
_clear_status(cp)
cp.permanentInfection = 0
cp.at = null
cp.faceUp = false
drop_from_combat(s, r)
## Recruit rule: an Anomaly recruited over leaves for the discard pile with its Hardware, and its
## copy leaves play.
static func retire_anomaly(s: Dictionary, r: Dictionary) -> void:
var av := State.anomaly(s, r)
remove_copy(s, State.copy_of(r))
if not av.hardware.is_empty():
State.stat(s, "hardwareLost", r.player, av.hardware.size())
for hw in av.hardware:
State.to_discard(s, hw)
var from := " from %s" % av.at if av.at else ""
State.say(s, "%s retires %s%s." % [State.player_name(r.player), State.anomaly_name(s, r), from], {"tag": "card", "player": r.player, "ref": r})
drop_from_combat(s, r)
State.to_discard(s, av.card)
State.stat(s, "anomaliesRetired", r.player)
## The loser of a combat goes back to its slot. Its Hardware is discarded unless `keep_hardware`,
## and its counters and effects are removed (Persistent Infection's counters stay).
static func knock_out(s: Dictionary, r: Dictionary, loc: String, role: String, keep_hardware: bool) -> void:
var av := State.anomaly(s, r)
if av.at == null:
return
if State.is_copy(r):
remove_copy(s, r)
else:
if not keep_hardware and not av.hardware.is_empty():
var names := ", ".join(av.hardware.map(func(h): return State.name_of(s, h)))
State.say(s, "%s loses %s." % [State.player_name(r.player), names], {"tag": "combat", "player": r.player, "ref": r, "loc": loc})
State.stat(s, "hardwareLost", r.player, av.hardware.size())
for hw in av.hardware:
State.to_discard(s, hw)
av.hardware = []
_clear_status(av)
av.at = null
State.say(s, "%s returns to its slot." % State.anomaly_name(s, r), {"tag": "combat", "player": r.player, "ref": r, "loc": loc})
remove_copy(s, State.copy_of(r))
State.stat(s, "anomaliesDestroyed", r.player)
Query.emit(s, "onDefeat", {"ref": r, "loc": loc, "role": role})
## Health rule: an Anomaly returns to its slot by its owner's choice, as its placement for the
## round. It heals fully and keeps its Hardware; like a defeat, its counters and effects come off
## (Persistent Infection's stay) and its copy leaves play.
static func recall_anomaly(s: Dictionary, r: Dictionary) -> void:
var av := State.anomaly(s, r)
if av.at == null:
return
var healed: int = av.damage
var healing := ", healing %d damage" % healed if healed else ""
State.say(s, "%s recalls %s from %s to its slot%s." % [State.player_name(r.player), State.anomaly_name(s, r), av.at, healing], {"tag": "move", "player": r.player, "ref": r, "loc": av.at})
_clear_status(av)
av.at = null
av.placed = true
remove_copy(s, State.copy_of(r))
State.stat(s, "recalls", r.player)
## Places a copy of `original` on `to`.
static func create_copy(s: Dictionary, original: Dictionary, to: String) -> void:
var r := State.copy_of(original)
var cp := State.anomaly(s, r)
cp.merge({
"card": State.anomaly(s, original).card,
"faceUp": true,
"at": to,
"hardware": [],
"damage": 0,
"placed": false,
"advanced": false,
"attacks": 0,
"infection": 0,
"bugs": 0,
"permanentInfection": 0,
"mods": [],
"disabledUntil": 0,
"rootedUntil": 0,
"breachedTurn": 0,
"createdTurn": s.turn,
}, true)
State.say(s, "%s creates %s on %s." % [State.player_name(r.player), State.anomaly_name(s, r), to], {"tag": "card", "player": r.player, "ref": r, "loc": to})
## Moves an Anomaly by a card effect. Callers check the move is legal.
static func move_anomaly(s: Dictionary, r: Dictionary, to: String) -> void:
var av := State.anomaly(s, r)
State.say(s, "%s moves %s → %s." % [State.anomaly_name(s, r), av.at, to], {"tag": "move", "player": r.player, "ref": r, "loc": to})
av.at = to
# ---------------------------------------------------------------------------------------------
# Step 5: declarations
static func resolve_declaration(s: Dictionary, index: int) -> void:
var d: Dictionary = s.declarations[index]
var p: int = d.ref.player
var av := State.anomaly(s, d.ref)
var who := State.anomaly_name(s, d.ref)
if av.at == null:
return
if State.is_rooted(s, d.ref) or State.is_disabled_anomaly(s, d.ref):
State.say(s, "%s can't move, so its %s on %s fails." % [who, d.kind, d.to], {"tag": "move", "player": p, "ref": d.ref, "loc": d.to})
return
if State.controls(s, p, d.to):
return
var defended := not State.defenders_at(s, d.to).is_empty()
var how := "capturesUnowned" if s.locations[d.to].owner == null else "capturesUndefended"
if d.kind == "advance":
var reachable := false
for n in State.neighbors(s, d.to):
if State.controls(s, p, n):
reachable = true
if not reachable:
State.say(s, "%s can no longer reach %s." % [who, d.to], {"tag": "move", "player": p, "ref": d.ref, "loc": d.to})
return
if defended:
State.start_combat(s, d.ref, av.at, d.to, "advance")
else:
State.push_capture(s, d.ref, d.to, how)
return
if (not d.second and av.at != d.from) or not State.controls(s, p, d.from) or not State.adjacent(s, d.from, d.to):
State.say(s, "%s's attack on %s fails: it's no longer in position." % [who, d.to], {"tag": "move", "player": p, "ref": d.ref, "loc": d.to})
return
if defended:
State.start_combat(s, d.ref, d.from, d.to, "attack")
else:
State.push_capture(s, d.ref, d.to, how)
# ---------------------------------------------------------------------------------------------
# Combat
static func _roll(s: Dictionary, n: int) -> Array:
var out := []
for i in n:
out.append(State.roll_die(s))
return out
static func _side_totals(c: Dictionary) -> Dictionary:
var def_total := 0
for d in c.defenders:
def_total += Util.sum(c.dice.get(State.ref_key(d), []))
return {"atk": Util.sum(c.dice.get(State.ref_key(c.attacker), [])), "def": def_total}
static func _dice_text(s: Dictionary, c: Dictionary) -> String:
var one := func(r):
var dice: Array = c.dice.get(State.ref_key(r), [])
return "%s [%s]" % [State.name_of(s, State.anomaly(s, r).card), ",".join(dice.map(func(v): return str(v)))]
var t := _side_totals(c)
return "%s=%d vs %s=%d" % [one.call(c.attacker), t.atk, " + ".join(c.defenders.map(one)), t.def]
## Rolls every fighter's dice, rerolling all of them on a tie (under the health rule a tie stands).
static func _roll_all(s: Dictionary, c: Dictionary) -> void:
while true:
for r in State.fighters_of(c):
c.dice[State.ref_key(r)] = _roll(s, Query.cores_of(s, Query.fighter_of(s, r)))
var t := _side_totals(c)
if t.atk != t.def or s.rules.health.on:
break
c.ties += 1
c.rolled = true
# ---------------------------------------------------------------------------------------------
# Damage (health rule)
## Health text for the combat log, e.g. "7/10 Health".
static func health_text(s: Dictionary, r: Dictionary) -> String:
return "%d/%d Health" % [Query.health_left(s, r), Query.health_of(s, r)]
## Deals `n` damage to an Anomaly. Returns true if that destroys it (its damage reaches its Health).
static func damage_anomaly(s: Dictionary, r: Dictionary, n: int) -> bool:
var av := State.anomaly(s, r)
if av.at == null or n <= 0:
return false
av.damage += n
var dead: bool = av.damage >= Query.health_of(s, r)
var how := " and is destroyed" if dead else " (%s)" % health_text(s, r)
State.say(s, "%s takes %d damage%s." % [State.anomaly_name(s, r), n, how], {"tag": "combat", "player": r.player, "ref": r, "amount": n, "loc": av.at})
return dead
## The attacker splits `n` damage among the defenders. The engine picks the split that destroys the
## most defenders, weakest first, and puts what's left on the weakest survivor. Returns the hits as
## {ref, amount, destroyed}.
static func _allocate_damage(s: Dictionary, defenders: Array, n: int) -> Array:
var order := Util.sorted_by(defenders, func(r): return Query.health_left(s, r))
var hits := []
for i in order.size():
if n <= 0:
break
var d: Dictionary = order[i]
var left := Query.health_left(s, d)
var hit := left if n >= left else (n if i == order.size() - 1 else 0)
if hit == 0:
# Can't destroy this one: dump the rest on the weakest.
var first = null
for h in hits:
if State.ref_key(h.ref) == State.ref_key(order[0]):
first = h
break
damage_anomaly(s, order[0], n)
if first != null:
first.amount += n
else:
hits.append({"ref": order[0], "amount": n, "destroyed": false})
break
n -= hit
hits.append({"ref": d, "amount": hit, "destroyed": damage_anomaly(s, d, hit)})
return hits
## Tells the cards that an Anomaly lost a roll (Resource Leech, Overflow Error, Persistent Infection).
static func _emit_damage(s: Dictionary, r: Dictionary, loc: String, role: String, amount: int, destroyed: bool) -> void:
Query.emit(s, "onDamage", {"ref": r, "loc": loc, "role": role, "amount": amount, "destroyed": destroyed})
## Health rule: the loser of the roll takes the difference as damage; destroyed Anomalies are defeated.
static func _resolve_damage(s: Dictionary, c: Dictionary, t: Dictionary) -> void:
if t.atk == t.def:
c.ties += 1
State.stat(s, "combatsTied", c.attacker.player)
State.say(s, "Tie, %d to %d: a stalemate. Nobody takes damage." % [t.atk, t.def], {"tag": "combat", "loc": c.loc})
return
var margin: int = absi(t.atk - t.def)
var attacker_wins: bool = t.atk > t.def
var defender: int = s.locations[c.loc].owner
var winner: int = c.attacker.player if attacker_wins else defender
State.say(s, "%s wins the roll, %d to %d: %d damage." % [State.player_name(winner), t.atk, t.def, margin], {"tag": "combat", "player": winner, "loc": c.loc})
State.stat(s, "damageDealt", winner, margin)
if attacker_wins:
State.stat(s, "attacksWon", c.attacker.player)
var hits := _allocate_damage(s, c.defenders, margin)
var tasks := []
var destroyed := 0
for h in hits:
if h.destroyed:
destroyed += 1
tasks.append({"t": "defeat", "ref": h.ref, "loc": c.loc, "role": "defend"})
if destroyed == c.defenders.size():
tasks.append({"t": "capture", "ref": c.attacker, "loc": c.loc, "stage": "hooks", "how": "capturesInCombat"})
else:
State.say(s, "%s holds." % c.loc, {"tag": "combat", "player": defender, "loc": c.loc})
State.push_tasks(s, tasks)
# Pushed last, so the damage hooks run before the defeats.
for h in hits:
_emit_damage(s, h.ref, c.loc, "defend", h.amount, h.destroyed)
else:
var dead := damage_anomaly(s, c.attacker, margin)
if dead:
State.push_tasks(s, [{"t": "defeat", "ref": c.attacker, "loc": c.loc, "role": "attack"}])
_emit_damage(s, c.attacker, c.loc, "attack", margin, dead)
## Cores that change after the roll change the dice: each Core gained rolls one more die, and each
## Core lost removes that Anomaly's highest die.
static func sync_dice(s: Dictionary, c: Dictionary) -> void:
if not c.rolled:
return
for r in State.fighters_of(c):
var key := State.ref_key(r)
var dice: Array = c.dice.get(key, [])
var want := Query.cores_of(s, Query.fighter_of(s, r))
while dice.size() < want:
dice.append(State.roll_die(s))
if dice.size() > want:
dice.sort()
dice.resize(want)
c.dice[key] = dice
## Current dice totals {atk, def}, after syncing to Core changes.
static func combat_totals(s: Dictionary) -> Dictionary:
var c: Dictionary = s.combat
sync_dice(s, c)
return _side_totals(c)
## Stops the current combat with no winner.
static func end_combat(s: Dictionary, why: String) -> void:
var c = s.combat
if c == null or c.ended:
return
c.ended = true
State.stat(s, "combatsEnded", c.attacker.player)
State.say(s, "The combat at %s ends: %s." % [c.loc, why], {"tag": "combat", "loc": c.loc})
## Takes an Anomaly out of the current combat. If the attacker leaves, the combat ends. If the last
## defender leaves, the attacker takes the location as undefended.
static func drop_from_combat(s: Dictionary, r: Dictionary) -> void:
var c = s.combat
if c == null or c.ended:
return
if State.same_ref(c.attacker, r):
end_combat(s, "%s left it" % State.anomaly_name(s, r))
return
var i := -1
for k in c.defenders.size():
if State.same_ref(c.defenders[k], r):
i = k
break
if i < 0:
return
c.defenders.remove_at(i)
c.dice.erase(State.ref_key(r))
if c.defenders.is_empty():
end_combat(s, "no defender is left")
if State.anomaly(s, c.attacker).at != null:
State.push_capture(s, c.attacker, c.loc, "capturesUndefended")
static func combat_stage(s: Dictionary, stage: String) -> void:
var c = s.combat
if c == null:
return
_run_stage(s, c, stage)
# "result" is watched inside _run_stage, before the damage.
if (stage == "start" or stage == "roll" or stage == "end") and combat_watch.is_valid():
combat_watch.call(s, stage)
static func _run_stage(s: Dictionary, c: Dictionary, stage: String) -> void:
if stage == "cleanup":
for r in State.fighters_of(c):
var av := State.anomaly(s, r)
av.mods = av.mods.filter(func(m): return m.get("combat") != c.id)
s.combat = null
return
if stage == "end":
State.push_tasks(s, [{"t": "combat", "stage": "cleanup"}])
if c.rolled or c.ended:
Query.emit(s, "onCombatEnd", null)
return
if c.ended:
return
if stage == "start":
State.stat(s, "attacks", c.attacker.player)
var sides := Query.side_cores(s)
var hp := func(r): return ", %s" % health_text(s, r) if s.rules.health.on else ""
var defs := " and ".join(c.defenders.map(func(d): return "%s%s" % [State.anomaly_name(s, d), hp.call(d)]))
State.say(s, "Combat at %s: %s (%d Cores, from %s%s) vs %s (%d Cores)." % [c.loc, State.anomaly_name(s, c.attacker), sides.atk, c.origin, hp.call(c.attacker), defs, sides.def], {"tag": "combat", "player": c.attacker.player, "loc": c.loc, "ref": c.attacker})
Query.emit(s, "onCombatStart", null)
return
if stage == "roll":
# Static Core effects count as firing once per combat.
var credited := {}
var credit := func(card_name, p):
var k := "%s:%d" % [card_name, p]
if not credited.has(k):
credited[k] = true
State.fired(s, card_name, p)
for r in State.fighters_of(c):
Query.cores_of(s, Query.fighter_of(s, r), credit)
_roll_all(s, c)
var ties := " after %d tie reroll(s)" % c.ties if c.ties else ""
State.say(s, "Roll: %s%s." % [_dice_text(s, c), ties], {"tag": "combat", "loc": c.loc})
return
# result
var t := combat_totals(s)
if combat_watch.is_valid():
combat_watch.call(s, "result")
if s.rules.health.on:
_resolve_damage(s, c, t)
return
if t.atk == t.def:
c.ties += 1
_roll_all(s, c)
State.say(s, "Tie, so both sides reroll: %s." % _dice_text(s, c), {"tag": "combat", "loc": c.loc})
State.push_tasks(s, [
State._window("postRoll", c.attacker.player, s.stack.size()),
{"t": "combat", "stage": "result"},
])
return
var attacker_wins: bool = t.atk > t.def
var winner: int = c.attacker.player if attacker_wins else s.locations[c.loc].owner
State.say(s, "%s wins the combat, %d to %d." % [State.player_name(winner), t.atk, t.def], {"tag": "combat", "player": winner, "loc": c.loc})
if attacker_wins:
State.stat(s, "attacksWon", c.attacker.player)
var tasks := []
for r in c.defenders:
tasks.append({"t": "defeat", "ref": r, "loc": c.loc, "role": "defend"})
tasks.append({"t": "capture", "ref": c.attacker, "loc": c.loc, "stage": "hooks", "how": "capturesInCombat"})
State.push_tasks(s, tasks)
# Without the health rule a lost roll destroys, so the damage hooks fire with the full Health.
for r in c.defenders:
_emit_damage(s, r, c.loc, "defend", Query.health_left(s, r), true)
else:
State.push_tasks(s, [{"t": "defeat", "ref": c.attacker, "loc": c.loc, "role": "attack"}])
_emit_damage(s, c.attacker, c.loc, "attack", Query.health_left(s, c.attacker), true)
# ---------------------------------------------------------------------------------------------
# Defeat
static func defeat(s: Dictionary, r: Dictionary, loc: String, role: String) -> void:
var av := State.anomaly(s, r)
if av.at == null:
return
if not State.is_copy(r):
# Redundant Power Supply, then RAID Array, may save the Hardware.
var savers: Array = av.hardware.filter(func(hw):
return Query.hardware_active(s, hw) and CardScripts.of(s.cards[hw].name).has("onWearerDefeated"))
savers = Util.sorted_by(savers, func(hw): return CardScripts.of(s.cards[hw].name).get("savePriority", 0))
for hw in savers:
if CardScripts.of(s.cards[hw].name).onWearerDefeated.call(s, hw, {"ref": r, "loc": loc, "role": role}):
return
knock_out(s, r, loc, role, false)
# ---------------------------------------------------------------------------------------------
# Capture
static func capture_hooks(s: Dictionary, r: Dictionary, loc: String, how: String) -> void:
var p: int = r.player
if State.anomaly(s, r).at == null or State.controls(s, p, loc) or GameMap.is_start(loc):
return
State.push_tasks(s, [{"t": "capture", "ref": r, "loc": loc, "stage": "main", "how": how}])
var prev = s.locations[loc].owner
if prev != null and prev != p:
State.anomaly(s, r).breachedTurn = s.turn
Query.emit(s, "onCaptured", {"ref": r, "loc": loc})
Query.emit(s, "onBreach", {"ref": r, "loc": loc})
static func capture_main(s: Dictionary, r: Dictionary, loc: String, how: String) -> void:
var p: int = r.player
var me: Dictionary = s.players[p]
var L: Dictionary = s.locations[loc]
if State.anomaly(s, r).at == null or State.controls(s, p, loc):
return
var previous = L.owner
if L.server != null:
State.reset_card(s, L.server)
s.players[s.cards[L.server].owner].serverPile.append(L.server)
if previous != null and not L.programs.is_empty():
State.stat(s, "programsLost", previous, L.programs.size())
for prog in L.programs:
State.to_discard(s, prog)
L.programs = []
L.owner = p
L.server = me.serverPile.pop_front() if not me.serverPile.is_empty() else null
State.anomaly(s, r).at = loc
var level := GameMap.level_for(p, loc)
var turn1 = s.rules.firstTurn if s.turn == 1 else null
var bonus: int = 0 if L.server == null else CardScripts.of(s.cards[L.server].name).get("bandwidthOnPlace", 0)
var no_capture_bandwidth: bool = turn1 != null and turn1.captureBandwidth == false
var bandwidth: int = (0 if no_capture_bandwidth else s.rules.levelBandwidth[level]) + bonus
State.gain_bandwidth(s, p, bandwidth, "bandwidthFromCaptures")
State.stat(s, how, p)
var from := "" if previous == null else " from %s" % State.player_name(previous)
var server := "no Server" if L.server == null else State.name_of(s, L.server)
State.say(s, "%s captures %s%s (Lv %d) with %s: +%d Gb (now %d)." % [State.player_name(p), loc, from, level, server, bandwidth, me.bandwidth], {"tag": "capture", "player": p, "loc": loc})
var unlocks: bool = not s.rules.recruit.on and not s.rules.buyAnomalies.on
if unlocks and level > me.unlockedLevel and not (turn1 != null and turn1.unlock == false):
me.unlockedLevel = level
for i in 4:
var av: Dictionary = me.anomalies[i]
if i < level and not av.faceUp:
av.faceUp = true
av.unlockedTurn = s.turn
State.say(s, "%s unlocks Anomaly %d: %s." % [State.player_name(p), i + 1, State.name_of(s, av.card)], {"tag": "capture", "player": p, "loc": loc})
if State.grid_count(s, p) >= s.rules.winLocations:
s.over = true
s.winner = p
s.endReason = "win"
State.say(s, "%s wins with %d locations." % [State.player_name(p), State.grid_count(s, p)], {"tag": "game", "player": p})
return
if L.server != null:
State.played(s, State.name_of(s, L.server), p)
Query.emit(s, "onPlaced", {"card": L.server})

1
engine/flow.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://bgu4e1y4tm1rn

97
engine/invariants.gd Normal file
View file

@ -0,0 +1,97 @@
class_name Invariants
## Rule invariants (invariants.ts): checks a state is consistent. Used by tests and the
## conformance runner's --check.
## Rule violations in a state; empty when it's consistent.
static func check(s: Dictionary) -> Array:
var errors := []
var zone := {}
var put := func(id: int, where: String) -> void:
if zone.has(id):
var nm = s.cards[id].name if id >= 0 and id < s.cards.size() else null
errors.append("card %d (%s) is in both %s and %s" % [id, Util.js(nm), zone[id], where])
zone[id] = where
for p in s.players.size():
var pl: Dictionary = s.players[p]
var own := func(ids: Array, where: String) -> void:
for id in ids:
put.call(id, "p%d.%s" % [p, where])
if s.cards[id].owner != p:
errors.append("p%d.%s holds the opponent's card %d" % [p, where, id])
own.call(pl.hand, "hand")
own.call(pl.deck, "deck")
own.call(pl.discard, "discard")
own.call(pl.serverPile, "serverPile")
if pl.bandwidth < 0:
errors.append("p%d has %d Gb" % [p, pl.bandwidth])
var count := {}
for i in pl.anomalies.size():
var av: Dictionary = pl.anomalies[i]
var slot: int = i + 1
var r := State.ref(p, slot)
if slot <= 4:
if av.card >= 0 or not s.rules.recruit.on:
own.call([av.card], "anomaly%d" % slot)
elif av.at != null or not av.hardware.is_empty():
errors.append("p%d empty slot %d is in use" % [p, slot])
own.call(av.hardware, "anomaly%d.hardware" % slot)
var ported: Array = av.hardware.filter(func(h):
return not CardScripts.of(s.cards[h].name).get("noSlot", false) and not s.cards[h].has("pushedUntil"))
if av.card >= 0 and ported.size() > Query.slots_total(s, r):
errors.append("p%d Anomaly %d is over its slots" % [p, slot])
else:
if not av.hardware.is_empty():
errors.append("p%d copy %d has Hardware of its own" % [p, slot - 4])
if av.at != null and pl.anomalies[i - 4].at == null:
errors.append("p%d copy %d is in play without its original" % [p, slot - 4])
if av.card != pl.anomalies[i - 4].card:
errors.append("p%d copy %d doesn't match its original" % [p, slot - 4])
if av.damage < 0:
errors.append("p%d Anomaly %d has negative damage" % [p, slot])
if av.at == null:
if av.damage != 0:
errors.append("p%d Anomaly %d is in its slot with %d damage" % [p, slot, av.damage])
continue
if not av.faceUp:
errors.append("p%d Anomaly %d is in play face down" % [p, slot])
# A destroyed Anomaly may still stand there while its defeat is being resolved (RAID Array's choice).
var dying: bool = s.choice != null
for t in s.tasks:
if t.t == "defeat" and t.ref.player == p and t.ref.slot == slot:
dying = true
if s.rules.health.on and not dying and av.damage >= Query.health_of(s, r):
errors.append("p%d Anomaly %d is in play with no Health left" % [p, slot])
if not State.controls(s, p, av.at):
errors.append("p%d Anomaly %d is on %s, which it doesn't control" % [p, slot, av.at])
count[av.at] = count.get(av.at, 0) + 1
for loc in count:
if count[loc] > Query.capacity(s, loc):
errors.append("p%d has %d Anomalies on %s" % [p, count[loc], loc])
var total := 0
for i in pl.anomalies.size():
if (i < 4 and pl.anomalies[i].card >= 0) or (i >= 4 and pl.anomalies[i].at != null):
total += 1
if s.rules.recruit.on and total > 4:
errors.append("p%d has %d Anomalies, counting copies" % [p, total])
for loc in GameMap.LOCATIONS:
var L: Dictionary = s.locations[loc]
if L.server != null:
put.call(L.server, "%s.server" % loc)
for id in L.programs:
put.call(id, "%s.programs" % loc)
if L.owner == null and (L.server != null or not L.programs.is_empty()):
errors.append("%s is unowned but has cards" % loc)
var layers: int = L.programs.filter(func(id): return s.cards[id].name == "Compatibility Layer").size()
if L.programs.size() > s.rules.maxProgramsPerLocation + layers:
errors.append("%s has too many Programs" % loc)
for item in s.stack:
if item.kind == "execution":
put.call(item.card, "stack")
if zone.size() != s.cards.size():
errors.append("%d cards are missing from every zone" % (s.cards.size() - zone.size()))
if s.choice != null and s.choice.options.is_empty():
errors.append("choice %s has no options" % s.choice.kind)
return errors

1
engine/invariants.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://beajrwd7n855u

142
engine/map.gd Normal file
View file

@ -0,0 +1,142 @@
class_name GameMap
## The playmats (map.ts). Location ids follow the diagram in rules.md: S1 is South's start, S2 is
## North's. A line is {id, a, b, gateway}; lines with a gateway can hold a Firewall.
##
## The current board lives in static vars. RulesEngine.create_game switches it with use_board, so a
## process plays one board at a time, as in TS.
const START_LOC: Array[String] = ["S1", "S2"]
## Boards by name: {grid, lines: [[a, b, gateway], ...], win}. The grid is row by row from South's
## side; the row is the letter (A is South's first row). `win` is the grid locations needed to win.
static var BOARDS: Dictionary = {}
static var GRID: Array = []
static var LOCATIONS: Array = []
static var LINES: Array = []
static var LINE_BY_ID: Dictionary = {}
static var LINES_AT: Dictionary = {}
static var _row_count := 0
static func _static_init() -> void:
BOARDS = {
"classic": _classic(),
# 4×4, each start joins the middle two squares of its first row.
"grid4": _squares([2, 3]),
# 4×4, each start joins all four squares of its first row.
"grid4-wide": _squares([1, 2, 3, 4]),
# 4×4, each start joins one square: A2 for South, D3 for North.
"grid4-one": _squares([2]),
# Three lanes, linked only across the middle row; every line between locations has a gateway.
"lanes": _lanes(true),
# Three lanes, but only the two middle cross-links can be firewalled.
"lanes-open": _lanes(false),
}
use_board("classic")
## The playmat in rules.md: rows of 3, 2, 3, 2, 3, entered from the middle of each end row.
static func _classic() -> Dictionary:
return {
"grid": ["A1", "A2", "A3", "B1", "B2", "C1", "C2", "C3", "D1", "D2", "E1", "E2", "E3"],
"lines": [
["S1", "A2", false],
["A1", "A2", true], ["A2", "A3", true],
["A1", "B1", true], ["A2", "B1", true], ["A2", "B2", true], ["A3", "B2", true],
["B1", "C1", true], ["B1", "C2", true], ["B2", "C2", true], ["B2", "C3", true],
["C1", "D1", true], ["C2", "D1", true], ["C2", "D2", true], ["C3", "D2", true],
["D1", "E1", true], ["D1", "E2", true], ["D2", "E2", true], ["D2", "E3", true],
["E1", "E2", true], ["E2", "E3", true],
["S2", "E2", false],
],
"win": 10,
}
## A 4×4 grid of squares, rows A–D, columns 1–4, joined side to side (not diagonally), with a
## gateway on every line between squares. Each start joins the listed squares of its first row;
## North's are South's rotated 180°. Win with 12 of the 16.
static func _squares(south_entries: Array) -> Dictionary:
var rows := ["A", "B", "C", "D"]
var grid := []
for r in rows:
for c in [1, 2, 3, 4]:
grid.append("%s%d" % [r, c])
var lines := []
for c in south_entries:
lines.append(["S1", "A%d" % c, false])
for i in rows.size():
var r: String = rows[i]
for c in range(1, 5):
if c < 4:
lines.append(["%s%d" % [r, c], "%s%d" % [r, c + 1], true])
if i < 3:
lines.append(["%s%d" % [r, c], "%s%d" % [rows[i + 1], c], true])
for c in south_entries:
lines.append(["S2", "D%d" % (5 - c), false])
return {"grid": grid, "lines": lines, "win": 12}
## Three lanes of five rows, A–E, joined to each other only across the middle row (C1–C2–C3). Each
## start joins the first location of every lane. With `lane_gateways` false the lane lines can't be
## firewalled, so only the two middle cross-links can. Win with 11 of the 15.
static func _lanes(lane_gateways: bool) -> Dictionary:
var rows := ["A", "B", "C", "D", "E"]
var grid := []
for r in rows:
for c in [1, 2, 3]:
grid.append("%s%d" % [r, c])
var lines := []
for c in [1, 2, 3]:
lines.append(["S1", "A%d" % c, false])
for i in rows.size() - 1:
for c in range(1, 4):
lines.append(["%s%d" % [rows[i], c], "%s%d" % [rows[i + 1], c], lane_gateways])
lines.append(["C1", "C2", true])
lines.append(["C2", "C3", true])
for c in range(1, 4):
lines.append(["S2", "E%d" % c, false])
return {"grid": grid, "lines": lines, "win": 11}
static func use_board(board_name: String) -> void:
if not BOARDS.has(board_name):
Util.fail("Unknown board \"%s\". Boards: %s" % [board_name, ", ".join(BOARDS.keys())])
return
var board: Dictionary = BOARDS[board_name]
GRID = board.grid
LOCATIONS = [START_LOC[0]] + GRID + [START_LOC[1]]
LINES = []
for l in board.lines:
LINES.append({"id": "%s-%s" % [l[0], l[1]], "a": l[0], "b": l[1], "gateway": l[2]})
LINE_BY_ID = {}
for l in LINES:
LINE_BY_ID[l.id] = l
LINES_AT = {}
for loc in LOCATIONS:
LINES_AT[loc] = LINES.filter(func(l): return l.a == loc or l.b == loc)
var rows := {}
for loc in GRID:
rows[loc[0]] = true
_row_count = rows.size()
static func other_end(line: Dictionary, loc: String) -> String:
return line.b if line.a == loc else line.a
static func is_start(loc: String) -> bool:
return loc == START_LOC[0] or loc == START_LOC[1]
## A location's level for the player capturing it: your first row is Lv 1, counting up to the far
## row (Lv 5 on the classic board, Lv 4 on the 4×4 ones). Your own start is Lv 1.
static func level_for(p: int, loc: String) -> int:
if loc == START_LOC[p]:
return 1
var row := "ABCDE".find(loc[0])
if row < 0 or row >= _row_count:
Util.fail("No level for %s from player %d" % [loc, p])
return 1
return row + 1 if p == 0 else _row_count - row

1
engine/map.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://bo6yu1gb8qako

62
engine/odds.gd Normal file
View file

@ -0,0 +1,62 @@
class_name Odds
## Dice odds (odds.ts): the exact distribution of a sum of d6, and combat chances from it.
static var _cache := {}
static var _roll_cache := {}
## Distribution of the sum of n d6, as probability by total.
static func _sum_distribution(n: int) -> Dictionary:
var dist := {0: 1.0}
for i in n:
var next := {}
for total in dist:
for face in range(1, 7):
next[total + face] = next.get(total + face, 0.0) + dist[total] / 6.0
dist = next
return dist
## Exact chance that `atk` Cores beat `def` Cores, with ties rerolled.
static func win_chance(atk: int, def: int) -> float:
var key := "%d:%d" % [atk, def]
if _cache.has(key):
return _cache[key]
var win := 0.0
var lose := 0.0
var a := _sum_distribution(maxi(1, atk))
var d := _sum_distribution(maxi(1, def))
for sa in a:
for sd in d:
if sa > sd:
win += a[sa] * d[sd]
elif sa < sd:
lose += a[sa] * d[sd]
var chance := win / (win + lose)
_cache[key] = chance
return chance
## One roll of `atk` Cores against `def` Cores: {win, tie, lose} chances (no rerolls), and the
## expected damage to the defenders (damageDealt) and to the attacker (damageTaken) under the health
## rule, where the margin is the damage.
static func roll_odds(atk: int, def: int) -> Dictionary:
var key := "%d:%d" % [atk, def]
if _roll_cache.has(key):
return _roll_cache[key]
var out := {"win": 0.0, "tie": 0.0, "lose": 0.0, "damageDealt": 0.0, "damageTaken": 0.0}
var a := _sum_distribution(maxi(1, atk))
var d := _sum_distribution(maxi(1, def))
for sa in a:
for sd in d:
var p: float = a[sa] * d[sd]
if sa > sd:
out.win += p
out.damageDealt += p * (sa - sd)
elif sa < sd:
out.lose += p
out.damageTaken += p * (sd - sa)
else:
out.tie += p
_roll_cache[key] = out
return out

1
engine/odds.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dag5epbussjc

46
engine/play.gd Normal file
View file

@ -0,0 +1,46 @@
class_name Play
## Plays whole games between bots (play.ts), for batch runs and tests.
const MAX_ACTIONS := 200000
## Bot makers by name. Each takes a seed and returns a bot (see RandomBot). The greedy bots ignore it.
static func bots() -> Dictionary:
return {
"random": func(seed: int): return RandomBot.new(seed),
"greedy": func(_seed: int): return GreedyBot.new(),
"nocards": func(_seed: int): return GreedyBot.new({"useCards": false}),
}
## The decks a game with this seed is dealt when none are given, from the cards `include` allows.
static func deal(pool: Dictionary, seed: int, rules: Dictionary, include := Callable()) -> Array:
var deck_rng := Rng.make(seed ^ 0x9e3779b9)
return [Deck.random_deck(pool, deck_rng, rules, include), Deck.random_deck(pool, deck_rng, rules, include)]
## Plays one game to the end from {pool, bots: [maker, maker], seed, decks?, rules?, log?, check?}.
## The same options and seed always produce the same game. Returns the final state, or null if the
## engine failed (see Util.errors).
static func play_game(o: Dictionary) -> Variant:
var rules: Dictionary = o.get("rules", Rules.defaults())
var decks: Array = o.get("decks", deal(o.pool, o.seed, rules))
var s = RulesEngine.create_game({"pool": o.pool, "decks": decks, "seed": o.seed, "rules": rules, "log": o.get("log", false)})
if s == null:
return null
var players := [o.bots[0].call(o.seed * 2 + 1), o.bots[1].call(o.seed * 2 + 2)]
var n := 0
while not s.over:
n += 1
if n > MAX_ACTIONS:
return Util.fail("Game with seed %d didn't finish in %d actions" % [o.seed, MAX_ACTIONS])
var p: int = RulesEngine.decider(s)
var legal := RulesEngine.legal_actions(s)
var action: Dictionary = players[p].choose(RulesEngine.view_for(s, p), legal, p)
if not RulesEngine.apply_action(s, action, legal):
return null
if o.get("check", false):
var errors := Invariants.check(s)
if not errors.is_empty():
return Util.fail("Seed %d, turn %d:\n %s" % [o.seed, s.turn, "\n ".join(errors)])
return s

1
engine/play.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://ds2hvnuq3xelq

402
engine/query.gd Normal file
View file

@ -0,0 +1,402 @@
class_name Query
## Questions about the current state that depend on card effects (query.ts): what's in play, Cores,
## costs, capacity and protection.
##
## A Source (something with an effect in play) is {kind, id, name, controller, at} plus `ref` for
## Anomalies and Hardware and `virtual` for copied effects; see types.ts. A Fighter (an Anomaly as
## it fights, or would fight) is {ref, role, at, loc, combat}.
## Health when no value is printed and no override is set.
const FALLBACK_HEALTH := 10
static func program_active(s: Dictionary, id: int) -> bool:
var c: Dictionary = s.cards[id]
return not State.running(s, c.disabledUntil) and not State.running(s, c.ignoredUntil)
static func hardware_active(s: Dictionary, id: int) -> bool:
return not State.running(s, s.cards[id].disabledUntil)
## Recruit rule: `p` has fewer than 4 Anomalies, counting copies. Always true without the rule.
static func anomaly_room(s: Dictionary, p: int) -> bool:
if not s.rules.recruit.on:
return true
var avs: Array = s.players[p].anomalies
var n := 0
for i in avs.size():
if (i < 4 and avs[i].card >= 0) or (i >= 4 and avs[i].at != null):
n += 1
return n < 4
## Whether `p` may make a copy now: the copy-rule switches, and room under the recruit rule.
static func can_copy(s: Dictionary, p: int) -> bool:
var c: Dictionary = s.rules.copies
return c.allowed and (not c.needAnomaly2 or s.players[p].anomalies[1].faceUp) and anomaly_room(s, p)
## Everything with an effect in play right now.
static func sources(s: Dictionary) -> Array:
var out := []
for loc in GameMap.LOCATIONS:
var L: Dictionary = s.locations[loc]
if L.owner == null:
continue
if L.server != null:
var c: Dictionary = s.cards[L.server]
out.append({"kind": "server", "id": L.server, "name": c.name, "controller": L.owner, "at": loc})
if c.get("copies"):
out.append({"kind": "server", "id": L.server, "name": c.copies, "controller": L.owner, "at": loc, "virtual": -2})
var live: Array = L.programs.filter(func(id): return program_active(s, id))
for id in live:
out.append({"kind": "program", "id": id, "name": s.cards[id].name, "controller": L.owner, "at": loc})
for w in live:
var to = s.cards[w].get("wormTo") if s.cards[w].name == "Worm Protocol" else null
if not to:
continue
for id in live:
if id != w:
out.append({"kind": "program", "id": id, "name": s.cards[id].name, "controller": L.owner, "at": to, "virtual": -1})
for v in s.virtuals:
if State.running(s, v.until):
out.append({"kind": "program", "id": v.from, "name": v.name, "controller": v.controller, "at": v.at, "virtual": v.id})
for p in [0, 1]:
for r in State.refs_in_play(s, p):
if State.is_copy(r):
continue
var av := State.anomaly(s, r)
out.append({"kind": "anomaly", "id": av.card, "name": s.cards[av.card].name, "controller": p, "at": av.at, "ref": r})
for hw in av.hardware:
if hardware_active(s, hw):
out.append({"kind": "hardware", "id": hw, "name": s.cards[hw].name, "controller": p, "at": av.at, "ref": r})
return out
static func same_source(a: Dictionary, b: Dictionary) -> bool:
if a.id != b.id or a.name != b.name or a.at != b.at or a.get("virtual") != b.get("virtual"):
return false
var ra = a.get("ref")
var rb = b.get("ref")
return (ra == null and rb == null) or State.same_ref(ra, rb)
static func still_active(s: Dictionary, src: Dictionary) -> bool:
for x in sources(s):
if same_source(x, src):
return true
return false
## Active sources with this card name (including copies) applying at `loc`, or anywhere for null.
static func sources_named(s: Dictionary, card_name: String, loc: Variant = null) -> Array:
return sources(s).filter(func(x): return x.name == card_name and (loc == null or x.at == loc))
## Queues `hook` for every source whose script has it.
static func emit(s: Dictionary, hook: String, data: Variant) -> void:
var tasks := []
for src in sources(s):
if CardScripts.of(src.name).has(hook):
tasks.append({"t": "hook", "hook": hook, "src": src, "data": data})
State.push_tasks(s, tasks)
# ---------------------------------------------------------------------------------------------
# Capacity
## How many of its owner's Anomalies a location holds (Cluster Server, Pingable Server: 2).
static func capacity(s: Dictionary, loc: String) -> int:
var sv = s.locations[loc].server
if sv == null or s.locations[loc].owner == null:
return 1
var c: Dictionary = s.cards[sv]
var copied: int = CardScripts.of(c.copies).get("capacity", 1) if c.get("copies") else 1
return maxi(1, maxi(CardScripts.of(c.name).get("capacity", 1), copied))
## Whether `p` can put another Anomaly on `loc`.
static func has_room(s: Dictionary, p: int, loc: String) -> bool:
if not State.controls(s, p, loc):
return false
# Nothing enters a location mid-combat (a copy, or an Anomaly moved by Disconnect).
if s.combat != null and not s.combat.ended and s.combat.loc == loc:
return false
var n := 0
for r in State.refs_in_play(s, p):
if State.anomaly(s, r).at == loc:
n += 1
return n < capacity(s, loc)
## Program slots on a location: 2, plus active Programs that add slots (Compatibility Layer).
static func program_slots(s: Dictionary, loc: String) -> int:
var n: int = s.rules.maxProgramsPerLocation
for id in s.locations[loc].programs:
if program_active(s, id):
n += CardScripts.of(s.cards[id].name).get("programSlots", 0)
return n
## Programs installed on a location, counting copies that count as installed (Process Clone).
static func installed_count(s: Dictionary, loc: String) -> int:
var n: int = s.locations[loc].programs.size()
for v in s.virtuals:
if v.installed and v.at == loc and State.running(s, v.until):
n += 1
return n
static func slots_used(s: Dictionary, r: Dictionary) -> int:
var n := 0
for id in State.anomaly(s, r).hardware:
if not CardScripts.of(s.cards[id].name).get("noSlot", false):
n += 1
return n
## Expansion Slots an Anomaly has: printed, plus Hardware that adds some (Network Interface Upgrade).
static func slots_total(s: Dictionary, r: Dictionary) -> int:
var av := State.anomaly(s, r)
var n: int = State.def_of(s, av.card).slots
for id in av.hardware:
n += CardScripts.of(s.cards[id].name).get("extraSlots", 0)
return n
static func slots_free(s: Dictionary, r: Dictionary) -> int:
return slots_total(s, r) - slots_used(s, r)
## Whether a Hardware takes an Expansion Slot: Network Interface Upgrade and Hardware pushed on over
## the limit don't.
static func takes_slot(s: Dictionary, id: int) -> bool:
return not CardScripts.of(s.cards[id].name).get("noSlot", false) and not s.cards[id].has("pushedUntil")
## Whether an Anomaly's Hardware fits its Expansion Slots, with `out` taken off and `into` put on.
static func slots_fit(s: Dictionary, r: Dictionary, out: Variant = null, into: Variant = null) -> bool:
var av := State.anomaly(s, r)
var hw: Array = av.hardware.filter(func(id): return id != out)
if into != null:
hw.append(into)
var total: int = State.def_of(s, av.card).slots
var taken := 0
for id in hw:
total += CardScripts.of(s.cards[id].name).get("extraSlots", 0)
if takes_slot(s, id):
taken += 1
return taken <= total
# ---------------------------------------------------------------------------------------------
# Cores
## Where an Anomaly would fight from, as a fighter, with the current combat if it's in it.
static func fighter_of(s: Dictionary, r: Dictionary) -> Dictionary:
var c = s.combat
var av := State.anomaly(s, r)
if c != null and not c.ended:
if State.same_ref(c.attacker, r):
return {"ref": r, "role": "attack", "at": c.origin, "loc": c.loc, "combat": c}
for d in c.defenders:
if State.same_ref(d, r):
return {"ref": r, "role": "defend", "at": c.loc, "loc": c.loc, "combat": c}
return {"ref": r, "role": null, "at": av.at, "loc": null, "combat": null}
## Hardware on an Anomaly (a copy uses its original's) whose script passes `flag`, if active.
static func wears(s: Dictionary, r: Dictionary, flag: Callable) -> Array:
return State.hardware_of(s, r).filter(func(hw):
return hardware_active(s, hw) and flag.call(CardScripts.of(s.cards[hw].name)))
## Opponents' Bug effects can't touch an Anomaly wearing ECC Memory.
static func bug_immune(s: Dictionary, r: Dictionary, by: int) -> bool:
return by != r.player and not wears(s, r, func(sc): return sc.get("bugImmunity", false)).is_empty()
## Active sources with a script flag at a location, from a player other than `p`.
static func enemy_flag_at(s: Dictionary, loc: String, p: int, flag: Callable) -> Array:
return sources(s).filter(func(x): return x.at == loc and x.controller != p and flag.call(CardScripts.of(x.name)))
## Stock Rice: no Hardware bonuses in a combat at its location.
static func _hardware_blocked(s: Dictionary, f: Dictionary, all: Array) -> bool:
if not f.loc or f.role == null:
return false
for x in all:
if x.at == f.loc and CardScripts.of(x.name).get("blocksHardwareInCombat", false) and not bug_immune(s, f.ref, x.controller):
return true
return false
## Desynchronization: an attacker can't use once-per-turn Hardware abilities in a combat there.
static func desynced(s: Dictionary, r: Dictionary) -> bool:
var c = s.combat
if c == null or c.ended or not State.same_ref(c.attacker, r):
return false
return not enemy_flag_at(s, c.loc, r.player, func(sc): return sc.get("blocksHardwareAbilities", false)).is_empty()
# ---------------------------------------------------------------------------------------------
# Health (health rule)
## Health rule: the damage that destroys an Anomaly. Printed Health (or the rules' override), plus
## active Hardware that adds Health. A copy has its original's Health.
static func health_of(s: Dictionary, r: Dictionary) -> int:
var av := State.anomaly(s, r)
var n: int = s.rules.health.override
if n == 0:
n = 0 if av.card < 0 else State.def_of(s, av.card).health
if n == 0:
n = FALLBACK_HEALTH
for hw in State.hardware_of(s, r):
if hardware_active(s, hw):
n += CardScripts.of(s.cards[hw].name).get("health", 0)
return maxi(1, n)
## Health rule: Health an Anomaly has left.
static func health_left(s: Dictionary, r: Dictionary) -> int:
return health_of(s, r) - State.anomaly(s, r).damage
## Combat Cores for a fighter. `credit` is called with (name, player) for every card that changed the
## total, so the card report can count static effects (Stack Overflow, Server bonuses) as firing.
## `detail`, when given, collects every part of the total as {source, kind, controller, cores}, the
## printed Cores first. The total is at least 1.
static func cores_of(s: Dictionary, f: Dictionary, credit := Callable(), detail: Variant = null) -> int:
var av := State.anomaly(s, f.ref)
var d: Dictionary = State.def_of(s, av.card)
var n: int = d.cores
if detail != null:
detail.append({"source": d.name, "kind": "anomaly", "controller": f.ref.player, "cores": n})
var all := sources(s)
if not _hardware_blocked(s, f, all):
for hw in State.hardware_of(s, f.ref):
if not hardware_active(s, hw) or (f.combat != null and f.combat.suppressed.has(hw)):
continue
var hw_name: String = s.cards[hw].name
var sc := CardScripts.of(hw_name)
if sc.has("cores"):
var src := {"kind": "hardware", "id": hw, "name": hw_name, "controller": f.ref.player, "at": f.at, "ref": f.ref}
n += _part(sc.cores.call(s, src, f), hw_name, f.ref.player, "hardware", credit, detail)
var counted := {}
for src in all:
if src.kind == "hardware":
continue
var sc := CardScripts.of(src.name)
if sc.has("cores"):
n += _part(sc.cores.call(s, src, f), src.name, src.controller, src.kind, credit, detail)
if sc.has("globalCores") and not counted.has(src.name):
counted[src.name] = true
n += _part(sc.globalCores.call(s, f), src.name, src.controller, src.kind, credit, detail)
for m in State.active_mods(s, av):
n += m.cores
if m.cores != 0 and detail != null:
detail.append({"source": m.source, "kind": "modifier", "controller": m.by, "cores": m.cores})
return maxi(1, n)
## One part of a Core total: reports it to `credit` and `detail`, and returns it.
static func _part(delta: int, src_name: String, p: int, kind: String, credit: Callable, detail: Variant) -> int:
if delta != 0:
if credit.is_valid():
credit.call(src_name, p)
if detail != null:
detail.append({"source": src_name, "kind": kind, "controller": p, "cores": delta})
return delta
## Cores for each side of the current combat: {atk, def}.
static func side_cores(s: Dictionary) -> Dictionary:
var c: Dictionary = s.combat
var def_total := 0
for d in c.defenders:
def_total += cores_of(s, fighter_of(s, d))
return {"atk": cores_of(s, fighter_of(s, c.attacker)), "def": def_total}
# ---------------------------------------------------------------------------------------------
# Costs
#
# A Payment is {kind, player} plus what it's for: card, at (a Program's location or an Execution's
# target), ref (a Hardware's wearer), line and level (a Firewall), hostile (enemy Anomalies an
# Execution targets). kind is "program", "hardware", "execution", "firewall" or "ability".
static func _base_cost(s: Dictionary, payment: Dictionary) -> int:
if payment.kind == "firewall":
return State.firewall_cost(s, payment.get("level", 0))
return 0 if payment.get("card") == null else State.def_of(s, payment.card).bandwidth
## Bandwidth a payment costs after every discount and surcharge in play. Pass `all` (the current
## sources) when pricing many payments against the same state.
static func cost_of(s: Dictionary, payment: Dictionary, all: Variant = null) -> int:
var n := _base_cost(s, payment)
for src in (all if all != null else sources(s)):
var sc := CardScripts.of(src.name)
if sc.has("costMod"):
n += sc.costMod.call(s, src, payment)
return maxi(0, n)
## Pays for something, using up once-per-turn discounts. Returns the amount paid.
static func pay(s: Dictionary, payment: Dictionary, stat_key: String) -> int:
var n := _base_cost(s, payment)
var touched := []
for src in sources(s):
var sc := CardScripts.of(src.name)
var d: int = sc.costMod.call(s, src, payment) if sc.has("costMod") else 0
if d != 0:
n += d
touched.append(src)
var cost := maxi(0, n)
if cost > s.players[payment.player].bandwidth:
Util.fail("Can't afford %d Gb" % cost)
s.players[payment.player].bandwidth -= cost
State.stat(s, stat_key, payment.player, cost)
for src in touched:
var sc := CardScripts.of(src.name)
if sc.has("onPaid"):
sc.onPaid.call(s, src, payment)
return cost
## Bandwidth a player could have for a payment: current Bandwidth plus the Salvage value of the rest
## of the hand.
static func reachable_bandwidth(s: Dictionary, p: int, except: Variant = null) -> int:
var pl: Dictionary = s.players[p]
var n: int = pl.bandwidth
for id in pl.hand:
if id != except and id >= 0:
n += State.def_of(s, id).bandwidth
return n
# ---------------------------------------------------------------------------------------------
# Protection
## Hardware Sandbox: opponents can't target the Program it protects (Execute: Root Access lifts it).
static func is_protected(s: Dictionary, program: int, by: int) -> bool:
var owner: int = s.cards[program].owner
if by == owner:
return false
var loc = null
for l in GameMap.LOCATIONS:
if s.locations[l].programs.has(program):
loc = l
break
if loc != null and State.running(s, s.locations[loc].rootAccess[by]):
return false
for x in sources(s):
if x.kind == "hardware" and x.name == "Hardware Sandbox" and s.cards[x.id].get("protects") == program \
and loc != null and x.at == loc and x.controller == owner:
return true
return false
static func can_target_program(s: Dictionary, program: int, by: int) -> bool:
return not is_protected(s, program, by)

1
engine/query.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dgi5af1g3vslf

48
engine/rng.gd Normal file
View file

@ -0,0 +1,48 @@
class_name Rng
## Seeded Mulberry32 (rng.ts). The state is a Dictionary `{s}` kept in the GameState, so a cloned
## state carries its RNG along, which keeps every game reproducible from its seed.
##
## GDScript ints are 64-bit, so every step is masked to 32 bits to match JS's Math.imul and `>>> 0`.
const M := 0xFFFFFFFF
static func make(seed: int) -> Dictionary:
return {"s": seed & M}
## The low 32 bits of a * b, for a and b in 0..2^32 - 1, without overflowing 64 bits.
static func _imul(a: int, b: int) -> int:
return ((a & 0xFFFF) * b + ((((a >> 16) * b) & 0xFFFF) << 16)) & M
static func next_float(r: Dictionary) -> float:
r.s = (r.s + 0x6d2b79f5) & M
var t: int = r.s
t = _imul(t ^ (t >> 15), t | 1)
t = t ^ ((t + _imul(t ^ (t >> 7), t | 61)) & M)
return float((t ^ (t >> 14)) & M) / 4294967296.0
static func rand_int(r: Dictionary, n: int) -> int:
return floori(next_float(r) * n)
static func d6(r: Dictionary) -> int:
return 1 + rand_int(r, 6)
static func pick(r: Dictionary, items: Array) -> Variant:
return items[rand_int(r, items.size())]
## Shuffles `items` in place (Fisher–Yates, as in TS) and returns it.
static func shuffle(r: Dictionary, items: Array) -> Array:
var i := items.size() - 1
while i > 0:
var j := rand_int(r, i + 1)
var tmp = items[i]
items[i] = items[j]
items[j] = tmp
i -= 1
return items

1
engine/rng.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dg4kiual5kl37

109
engine/rules.gd Normal file
View file

@ -0,0 +1,109 @@
class_name Rules
## Every number from rules.md that a rule variant might change (rules.ts). A rules Dictionary is
## shaped like the TS RulesConfig; the field docs are there. Pass a modified copy to
## RulesEngine.create_game to A/B test a rule.
## The current rules, as a fresh Dictionary.
static func defaults() -> Dictionary:
return {
"board": "classic",
"startingBandwidth": 4,
"openingHand": 7,
"drawPerTurn": 1,
"winLocations": 10,
"maxTurns": 200,
"levelBandwidth": {1: 4, 2: 4, 3: 4, 4: 4, 5: 4},
"firewallCost": [2, 4, 8],
"maxProgramsPerLocation": 2,
"deck": {"anomalies": 4, "servers": 20, "main": 45, "maxCopies": 2},
"startingAnomalies": 1,
"firstTurn": {"draw": true, "advance": true, "captureBandwidth": true, "unlock": true, "cards": true},
"secondPlayer": {"bandwidth": 0, "anomalies": 0, "cards": 0, "firstDraw": 0, "locations": 0},
"recruit": {"on": false, "anomaliesInDeck": 3, "price": 6, "pricePerCore": 0},
"buyAnomalies": {"on": false, "prices": [8, 12, 16]},
"copies": {"allowed": true, "waitATurn": false, "needAnomaly2": false},
"commands": {"on": true, "perPlayer": 2, "leads": "F", "snake": true},
"health": {"on": true, "override": 0, "recall": true},
}
## Rules read from JSON (a trace, a game record): numbers back to ints, and levelBandwidth keyed by
## int level.
static func from_json(d: Dictionary) -> Dictionary:
var r: Dictionary = Util.ints(d)
var lb := {}
for k in r.levelBandwidth:
lb[int(k)] = r.levelBandwidth[k]
r.levelBandwidth = lb
return r
## Anomalies kept outside the main deck: all of them, or just the starting one when recruiting.
static func anomalies_outside(rules: Dictionary) -> int:
return 1 if rules.recruit.on else rules.deck.anomalies
## A copy of `rules` with one setting changed, from text like "winLocations=9",
## "secondPlayer.bandwidth=4", "firstTurn.advance=false" or "levelBandwidth=4,4,4,4,4" (Lv 1 to 5).
## "board=grid4" also sets winLocations to 12, so give a winLocations after it to change that.
## Returns null (and records an error) for a bad spec.
static func with_rule(rules: Dictionary, spec: String) -> Variant:
var m := RegEx.create_from_string("^([\\w.]+)=(.+)$").search(spec)
if m == null:
return Util.fail("Rule \"%s\" should look like name=value" % spec)
var key := m.get_string(1)
var raw := m.get_string(2)
var next := rules.duplicate(true)
var path := key.split(".")
var obj: Dictionary = next
for part in path.slice(0, -1):
if not (obj.get(part) is Dictionary):
return Util.fail("Unknown rule \"%s\"" % key)
obj = obj[part]
var last := path[path.size() - 1]
var old = obj.get(last)
if key == "board":
if not GameMap.BOARDS.has(raw):
return Util.fail("Unknown board \"%s\". Boards: %s" % [raw, ", ".join(GameMap.BOARDS.keys())])
obj.board = raw
obj.winLocations = GameMap.BOARDS[raw].win
elif old is int or old is float:
var n = _num(key, raw)
if n == null:
return null
obj[last] = n
elif old is String:
obj[last] = raw
elif old is bool:
if raw != "true" and raw != "false":
return Util.fail("Rule \"%s\" needs true or false" % key)
obj[last] = raw == "true"
elif key == "levelBandwidth":
var lb := {}
var parts := raw.split(",")
for i in parts.size():
var n = _num(key, parts[i])
if n == null:
return null
lb[i + 1] = n
obj[last] = lb
elif old is Array:
var out := []
for x in raw.split(","):
var n = _num(key, x)
if n == null:
return null
out.append(n)
obj[last] = out
else:
return Util.fail("Unknown rule \"%s\"" % key)
return next
static func _num(key: String, x: String) -> Variant:
if x.is_valid_int():
return int(x)
if x.is_valid_float():
return float(x)
return Util.fail("Rule \"%s\" needs numbers, got \"%s\"" % [key, x])

1
engine/rules.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dg244m0aio8ur

71
engine/scripts.gd Normal file
View file

@ -0,0 +1,71 @@
class_name CardScripts
## Card scripts: what each card does, in one place per card (scripts.ts). The engine calls into them
## at fixed points (hooks). Every script records the card text it was written for, so an edited card
## in cards.csv is reported instead of silently simulated with the old wording.
##
## A script is a Dictionary keyed like the TS Script interface; every key but `text` is optional.
## Values are numbers and flags (bandwidthOnPlace, capacity, programSlots, noSlot, extraSlots, health,
## extraAttacks, blocksHardwareInCombat, blocksHardwareAbilities, blocksAttackerExecutions,
## bugImmunity, executionPower, copiesExecutions, savePriority) or Callables, always called with the
## arguments listed here:
##
## cores(s, src, fighter) -> int globalCores(s, fighter) -> int
## costMod(s, src, payment) -> int onPaid(s, src, payment)
## <hook>(s, src, data) for each hook in HOOKS; data is null where TS passes none
## onWearerDefeated(s, hw, ev) -> bool negates(s, src, item) -> bool
## ability: {cost?, hardwareOncePerTurn?, uses(s, src) -> Array of args,
## resolve(s, item, src), extraCost?(s, src, args) -> int}
## execution: {plays(s, p) -> Array of {target, args}, resolve(s, item),
## targetsAnomalies?(s, item) -> Array of refs}
## resume: {fn name: Callable(s, data, value)}, continuations after a choice or a delayed task
const HOOKS: Array[String] = [
"onTurnStart", "onDraw", "onAttackDeclared", "onBreach", "onCaptured", "onPlaced", "onInstall",
"onCombatStart", "onDefeat", "onDamage", "onCombatEnd",
]
## Returned for cards with no script, so lookups don't need a null check.
const NONE := {}
static var _registry: Dictionary = {}
## All scripts by card name. Built on first use.
static func all() -> Dictionary:
if _registry.is_empty():
for group in [ServerCards.scripts(), ProgramCards.scripts(), HardwareCards.scripts(),
ExecutionCards.scripts(), AnomalyCards.scripts()]:
_registry.merge(group, true)
return _registry
## The script for a card name, or an empty Dictionary.
static func of(card_name: Variant) -> Dictionary:
return all().get(card_name, NONE)
static func is_implemented(card: Dictionary) -> bool:
return all().has(card.name)
## The text a card's script checks: the Ability for Anomalies, the description for everything else.
static func scripted_text(card: Dictionary) -> String:
if card.kind == "anomaly":
return card.ability.text.strip_edges() if card.has("ability") else ""
return card.text.strip_edges()
## Scripts whose card is missing from, or worded differently in, the CSV; and cards with no script.
static func stale_scripts(pool: Dictionary) -> Array:
var warnings := []
var scripts := all()
for card_name in scripts:
var card = pool.by_name.get(card_name)
if card == null:
warnings.append("%s: has a script but isn't in cards.csv" % card_name)
elif scripted_text(card) != scripts[card_name].text:
warnings.append("%s: card text changed; the script was written for \"%s\"" % [card_name, scripts[card_name].text])
for card in pool.all:
if not is_implemented(card):
warnings.append("%s: no script yet" % card.name)
return warnings

1
engine/scripts.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cm83bbjxm0dcx

487
engine/state.gd Normal file
View file

@ -0,0 +1,487 @@
class_name State
## Small helpers for reading and changing a game state (state.ts). Nothing here knows about
## individual cards, so both the engine and the card scripts can use it.
##
## A state `s` is the TS GameState as Dictionaries and Arrays, with the same keys. An Anomaly ref
## is {player, slot}: slots 1–4 are the printed Anomalies and slot k + 4 is the copy of Anomaly k.
static func other(p: int) -> int:
return 1 if p == 0 else 0
static func def_of(s: Dictionary, id: int) -> Dictionary:
return s.defs[s.cards[id].name]
static func name_of(s: Dictionary, id: int) -> String:
return "a hidden card" if id < 0 else s.cards[id].name
static func owner_of(s: Dictionary, id: int) -> int:
return s.cards[id].owner
static func controls(s: Dictionary, p: int, loc: String) -> bool:
return s.locations[loc].owner == p
static func is_open(s: Dictionary, line: Dictionary) -> bool:
return not s.firewalls.get(line.id, 0)
## Bandwidth to place, upgrade to, or clear a Firewall of `level`, before discounts; 0 for no Firewall.
static func firewall_cost(s: Dictionary, level: int) -> int:
var costs: Array = s.rules.firewallCost
return costs[level - 1] if level >= 1 and level <= costs.size() else 0
static func grid_count(s: Dictionary, p: int) -> int:
var n := 0
for loc in GameMap.GRID:
if controls(s, p, loc):
n += 1
return n
## Rolls a d6 (or takes the next rigged result).
static func roll_die(s: Dictionary) -> int:
var rigged = s.get("rigged")
if rigged != null and not rigged.is_empty():
return rigged.pop_front()
return Rng.d6(s.rng)
## Adds a line to the play-by-play. `meta` tags what it's about; give `to` and `public` when the
## line names cards only one player may see, and the other player reads `public` instead. Null
## values are left out, as TS leaves out undefined ones.
static func say(s: Dictionary, msg: String, meta := {}) -> void:
if s.log == null:
return
var line := {"text": msg}
for k in meta:
if meta[k] != null:
line[k] = meta[k]
s.log.append(line)
## The play-by-play as `viewer` may read it, or every line in full for null.
static func log_for(s: Dictionary, viewer: Variant) -> Array:
var out := []
for l in (s.log if s.log != null else []):
if viewer == null or not l.has("to") or l.to == viewer:
out.append(l.text)
else:
out.append(l.get("public", ""))
return out
static func stat(s: Dictionary, key: String, p: int, n := 1) -> void:
s.stats[key][p] += n
static func _use(s: Dictionary, card_name: String) -> Dictionary:
if not s.cardUse.has(card_name):
s.cardUse[card_name] = {"played": [0, 0], "fired": [0, 0]}
return s.cardUse[card_name]
## Counts a card being played, installed or activated.
static func played(s: Dictionary, card_name: String, p: int) -> void:
_use(s, card_name).played[p] += 1
## Counts a card's effect happening.
static func fired(s: Dictionary, card_name: String, p: int) -> void:
_use(s, card_name).fired[p] += 1
# ---------------------------------------------------------------------------------------------
# Time
static func end_of_turn(s: Dictionary) -> int:
return 2 * s.turn + 1
static func start_of(turn: int) -> int:
return 2 * turn
static func end_of(turn: int) -> int:
return 2 * turn + 1
## The turn number of `p`'s next turn (not the current one). Under the command rule, their next command.
static func next_turn_of(s: Dictionary, p: int) -> int:
if not s.rules.commands.on:
return s.turn + 2 if s.active == p else s.turn + 1
var t: int = s.turn + 1
while commander_of(s, t) != p:
t += 1
return t
# Command rule: game turns are commands. A round is 2 × perPlayer of them, alternating players,
# and the lead alternates by round.
static func _commands_per_round(s: Dictionary) -> int:
return 2 * s.rules.commands.perPlayer
## Command rule: who takes game turn `turn`.
static func commander_of(s: Dictionary, turn: int) -> int:
var leads: String = s.rules.commands.leads
var snake: bool = s.rules.commands.snake
var per := _commands_per_round(s)
var round_no := Util.floordiv(turn - 1, per)
var i := (turn - 1) % per
var mark := ""
if leads == "thue":
mark = "FS"[Util.popcount(round_no) % 2]
else:
mark = leads[posmod(round_no, leads.length())]
if mark != "F" and mark != "S":
Util.fail("commands.leads should use F and S, or be \"thue\": \"%s\"" % leads)
var lead: int = s.firstPlayer if mark == "F" else other(s.firstPlayer)
var leads_this := (i % 4 == 0 or i % 4 == 3) if snake else i % 2 == 0
return lead if leads_this else other(lead)
## Command rule: the round game turn `turn` belongs to, from 1.
static func round_of(s: Dictionary, turn: int) -> int:
return Util.floordiv(turn - 1, _commands_per_round(s)) + 1
## Command rule: whether `turn` is its commander's first command of the round.
static func first_command(s: Dictionary, turn: int) -> bool:
return (turn - 1) % _commands_per_round(s) < 2
## Rounds played so far: both players taking a turn (or all their commands).
static func rounds_played(s: Dictionary) -> int:
return round_of(s, s.turn) if s.rules.commands.on else ceili(s.turn / 2.0)
static func running(s: Dictionary, until: int) -> bool:
return until > s.clock
## Once-per-turn bookkeeping. Returns how many times `key` was used this turn.
static func used_this_turn(s: Dictionary, key: String) -> int:
return s.used.get(key, 0)
static func mark_used(s: Dictionary, key: String) -> void:
s.used[key] = s.used.get(key, 0) + 1
# ---------------------------------------------------------------------------------------------
# Anomalies
static func ref(p: int, slot: int) -> Dictionary:
return {"player": p, "slot": slot}
static func ref_key(r: Dictionary) -> String:
return "%d:%d" % [r.player, r.slot]
static func same_ref(a: Variant, b: Variant) -> bool:
return a != null and b != null and a.player == b.player and a.slot == b.slot
static func anomaly(s: Dictionary, r: Dictionary) -> Dictionary:
return s.players[r.player].anomalies[r.slot - 1]
static func is_copy(r: Dictionary) -> bool:
return r.slot > 4
## The printed Anomaly a ref belongs to (a copy's original).
static func original_of(r: Dictionary) -> Dictionary:
return ref(r.player, r.slot - 4) if r.slot > 4 else r
static func copy_of(r: Dictionary) -> Dictionary:
return ref(r.player, original_of(r).slot + 4)
static func in_play(s: Dictionary, r: Dictionary) -> bool:
return anomaly(s, r).at != null
static func anomaly_def(s: Dictionary, r: Dictionary) -> Dictionary:
return def_of(s, anomaly(s, r).card)
static func anomaly_name(s: Dictionary, r: Dictionary) -> String:
var n: int = original_of(r).slot
var card: int = anomaly(s, r).card
var nm := "?" if card < 0 else name_of(s, card)
return ("the copy of Anomaly %d (%s)" if is_copy(r) else "Anomaly %d (%s)") % [n, nm]
## Every Anomaly of `p` in play, originals first.
static func refs_in_play(s: Dictionary, p: int) -> Array:
var out := []
var avs: Array = s.players[p].anomalies
for i in avs.size():
if avs[i].at != null:
out.append(ref(p, i + 1))
return out
## Anomalies standing on `loc`. Only the location's owner can have Anomalies there.
static func anomalies_at(s: Dictionary, loc: String) -> Array:
var owner = s.locations[loc].owner
if owner == null:
return []
return refs_in_play(s, owner).filter(func(r): return anomaly(s, r).at == loc)
static func defenders_at(s: Dictionary, loc: String) -> Array:
return anomalies_at(s, loc)
## Hardware that counts for an Anomaly. A copy uses its original's Hardware.
static func hardware_of(s: Dictionary, r: Dictionary) -> Array:
return anomaly(s, original_of(r)).hardware
## The Anomaly wearing a Hardware card, if it's installed.
static func wearer_of(s: Dictionary, hw: int) -> Variant:
var p := owner_of(s, hw)
var avs: Array = s.players[p].anomalies
for i in avs.size():
if avs[i].hardware.has(hw):
return ref(p, i + 1)
return null
static func is_rooted(s: Dictionary, r: Dictionary) -> bool:
return running(s, anomaly(s, r).rootedUntil)
static func is_disabled_anomaly(s: Dictionary, r: Dictionary) -> bool:
return running(s, anomaly(s, r).disabledUntil)
## Copy-rule variant: a copy made this player-turn can't advance or attack yet. It can still defend.
static func fresh_copy(s: Dictionary, r: Dictionary) -> bool:
return is_copy(r) and s.rules.copies.waitATurn and anomaly(s, r).createdTurn == s.turn
## Can act: advance, attack, move, use its Ability.
static func can_act(s: Dictionary, r: Dictionary) -> bool:
return in_play(s, r) and not is_rooted(s, r) and not is_disabled_anomaly(s, r)
## Temporary modifiers that currently apply to an Anomaly.
static func active_mods(s: Dictionary, av: Dictionary) -> Array:
return av.mods.filter(func(m):
if m.has("combat"):
return s.combat != null and s.combat.id == m.combat
return running(s, m.get("until", 0)))
## Adds a temporary Core modifier. `scope` is {combat: id} or {until: clock}.
static func add_mod(s: Dictionary, r: Dictionary, cores: int, source: String, by: int, scope: Dictionary) -> void:
s.seq += 1
var m := {"seq": s.seq, "cores": cores, "source": source, "by": by}
m.merge(scope)
anomaly(s, r).mods.append(m)
static func infection_of(av: Dictionary) -> int:
return av.infection + av.permanentInfection
# ---------------------------------------------------------------------------------------------
# Combat
static func in_combat(s: Dictionary, r: Dictionary) -> bool:
var c = s.combat
if c == null or c.ended:
return false
if same_ref(c.attacker, r):
return true
for d in c.defenders:
if same_ref(d, r):
return true
return false
## The other side of the current combat from `r`'s point of view.
static func opponents_in_combat(s: Dictionary, r: Dictionary) -> Array:
var c = s.combat
if c == null or c.ended:
return []
if same_ref(c.attacker, r):
return c.defenders.duplicate()
for d in c.defenders:
if same_ref(d, r):
return [c.attacker]
return []
static func fighters_of(c: Dictionary) -> Array:
return [c.attacker] + c.defenders
## Anomalies "at" a location for card text: the ones standing there, plus an enemy attacking it in
## the current combat.
static func at_server(s: Dictionary, loc: String) -> Array:
var out := anomalies_at(s, loc)
var c = s.combat
if c != null and not c.ended and c.loc == loc:
var found := false
for r in out:
if same_ref(r, c.attacker):
found = true
if not found:
out.append(c.attacker)
return out
# ---------------------------------------------------------------------------------------------
# Map
## Locations joined to `loc` by a line with no Firewall.
static func neighbors(s: Dictionary, loc: String) -> Array:
var out := []
for l in GameMap.LINES_AT[loc]:
if is_open(s, l):
out.append(GameMap.other_end(l, loc))
return out
static func adjacent(s: Dictionary, a: String, b: String) -> bool:
return neighbors(s, a).has(b)
# ---------------------------------------------------------------------------------------------
# Cards moving between zones
## Clears play-time status when a card leaves play.
static func reset_card(s: Dictionary, id: int) -> void:
var c: Dictionary = s.cards[id]
c.disabledUntil = 0
c.ignoredUntil = 0
c.erase("wormTo")
c.erase("protects")
c.erase("copies")
c.erase("spent")
c.erase("pushedUntil")
static func to_discard(s: Dictionary, id: int) -> void:
reset_card(s, id)
s.players[owner_of(s, id)].discard.append(id)
static func to_hand(s: Dictionary, id: int) -> void:
reset_card(s, id)
s.players[owner_of(s, id)].hand.append(id)
static func remove_from(list: Array, id: int) -> bool:
var i := list.find(id)
if i < 0:
return false
list.remove_at(i)
return true
## Takes an installed Program off its location. Returns where it was, or null.
static func uninstall_program(s: Dictionary, id: int) -> Variant:
for loc in s.locations:
if remove_from(s.locations[loc].programs, id):
return loc
return null
static func uninstall_hardware(s: Dictionary, id: int) -> Variant:
var r = wearer_of(s, id)
if r != null:
remove_from(anomaly(s, r).hardware, id)
return r
static func program_location(s: Dictionary, id: int) -> Variant:
for loc in s.locations:
if s.locations[loc].programs.has(id):
return loc
return null
static func gain_bandwidth(s: Dictionary, p: int, n: int, key := "bandwidthFromEffects") -> void:
if n <= 0:
return
s.players[p].bandwidth += n
stat(s, key, p, n)
# ---------------------------------------------------------------------------------------------
# Tasks and choices
## Queues tasks to run next, in the order given.
static func push_tasks(s: Dictionary, tasks: Array) -> void:
var queue: Array = s.tasks
for i in range(tasks.size() - 1, -1, -1):
queue.push_front(tasks[i])
## Asks a player to choose. The game waits until they do.
static func ask(s: Dictionary, choice: Dictionary) -> void:
if s.choice != null:
Util.fail("Two choices at once: %s and %s" % [s.choice.kind, choice.kind])
return
if choice.options.is_empty():
Util.fail("Choice %s has no options" % choice.kind)
return
s.choice = choice
## Runs a script function after the current task, like a choice would.
static func later(card_name: String, fn: String, data: Variant = null) -> Dictionary:
return {"t": "call", "name": card_name, "fn": fn, "data": data}
static func _window(kind: String, priority: int, base: int) -> Dictionary:
return {"t": "window", "kind": kind, "priority": priority, "passes": 0, "base": base, "resolving": false}
static func start_combat(s: Dictionary, attacker: Dictionary, origin: String, loc: String, kind: String) -> Dictionary:
s.seq += 1
var combat := {
"id": s.seq,
"loc": loc,
"attacker": attacker,
"origin": origin,
"defenders": defenders_at(s, loc),
"kind": kind,
"dice": {},
"rolled": false,
"ended": false,
"suppressed": [],
"race": [null, null],
"ties": 0,
}
s.combat = combat
push_tasks(s, [
{"t": "combat", "stage": "start"},
_window("preRoll", attacker.player, s.stack.size()),
{"t": "combat", "stage": "roll"},
_window("postRoll", attacker.player, s.stack.size()),
{"t": "combat", "stage": "result"},
{"t": "combat", "stage": "end"},
])
return combat
static func push_capture(s: Dictionary, r: Dictionary, loc: String, how: String) -> void:
push_tasks(s, [{"t": "capture", "ref": r, "loc": loc, "stage": "hooks", "how": how}])
static func player_name(p: int) -> String:
return Types.PLAYER_NAMES[p]

1
engine/state.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://ctm5cbbm4d3bk

47
engine/types.gd Normal file
View file

@ -0,0 +1,47 @@
class_name Types
## Constants from the TS engine's types.ts.
##
## The game state is plain Dictionaries and Arrays shaped exactly like the TS GameState's JSON, with
## the same keys (see godot-plan.md §3), so these are the only "types" the port needs. The shapes are
## documented in files-tcg/sim/src/types.ts.
## 0 = South (starts on S1), 1 = North (starts on S2).
const PLAYER_NAMES: Array[String] = ["South", "North"]
## Status timers count half-turns: the clock is 2T at the start of player-turn T and 2T + 1 at its
## end. A status with `until: n` is active while the clock is below n.
const FOREVER := 1000000000
const STAT_KEYS: Array[String] = [
"capturesUnowned",
"capturesUndefended",
"capturesInCombat",
"attacks",
"attacksWon",
"combatsTied",
"damageDealt",
"anomaliesDestroyed",
"recalls",
"combatsEnded",
"firewallsPlaced",
"firewallsUpgraded",
"firewallsCleared",
"bandwidthFromCaptures",
"bandwidthFromSalvage",
"bandwidthFromEffects",
"bandwidthOnFirewalls",
"bandwidthOnCards",
"bandwidthOnAbilities",
"cardsSalvaged",
"cardsDrawn",
"hardwareInstalled",
"hardwareLost",
"programsInstalled",
"programsLost",
"executionsPlayed",
"abilitiesUsed",
"anomaliesRecruited",
"anomaliesRetired",
"anomaliesBought",
"bandwidthOnAnomalies",
]

1
engine/types.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://deyqnc662phe1

109
engine/util.gd Normal file
View file

@ -0,0 +1,109 @@
class_name Util
## Helpers for the places where GDScript and TypeScript differ (godot-plan.md §3, "Porting
## hazards"): errors, stable sorting, ordered sets, floor division and JS-style formatting.
## Engine errors so far. TS throws; GDScript has no exceptions, so failures are recorded here and
## pushed to the debugger, and tests check this is still empty.
static var errors: Array[String] = []
## Set while the bot tries out a card on a copy of its view (GreedyBot simulate): failures are still
## recorded, so the bot can tell, but not pushed to the debugger.
static var quiet := false
## Reports an engine error (where TS throws). Returns null so callers can `return Util.fail(...)`.
static func fail(msg: String) -> Variant:
if not quiet:
push_error(msg)
errors.append(msg)
return null
## A copy of `items` sorted by `key` (a Callable returning an int for an item), keeping the order of
## ties. TS's Array.sort is stable; sort_custom isn't.
static func sorted_by(items: Array, key: Callable) -> Array:
var keyed := []
for i in items.size():
keyed.append([key.call(items[i]), i, items[i]])
keyed.sort_custom(func(a, b): return a[0] < b[0] or (a[0] == b[0] and a[1] < b[1]))
var out := []
for k in keyed:
out.append(k[2])
return out
## A copy of `items` sorted like TS's `[...items].sort(cmp)`: `cmp(a, b)` returns a number, negative
## when a goes first, and ties keep their order.
static func sorted_cmp(items: Array, cmp: Callable) -> Array:
var keyed := []
for i in items.size():
keyed.append([i, items[i]])
keyed.sort_custom(func(a, b):
var c: float = cmp.call(a[1], b[1])
return c < 0 or (c == 0 and a[0] < b[0]))
var out := []
for k in keyed:
out.append(k[1])
return out
## Distinct values in first-seen order, like [...new Set(items)].
static func uniq(items: Array) -> Array:
var seen := {}
var out := []
for x in items:
if not seen.has(x):
seen[x] = true
out.append(x)
return out
static func sum(items: Array) -> int:
var t := 0
for x in items:
t += x
return t
## Floor division, like Math.floor(a / b). GDScript's int division truncates toward zero.
static func floordiv(a: int, b: int) -> int:
return (a - posmod(a, b)) / b
static func popcount(n: int) -> int:
var c := 0
while n > 0:
c += n & 1
n >>= 1
return c
## A value as a JS template string shows it: null is "null", not "<null>".
static func js(v: Variant) -> String:
if v == null:
return "null"
return str(v)
## Concatenates arrays into a new one, like [...a, ...b].
static func concat(a: Array, b: Array) -> Array:
var out := a.duplicate()
out.append_array(b)
return out
## JSON numbers as ints. JSON.parse_string returns every number as a float, while the engine's state
## holds only ints; whole floats become ints, recursively. Use on traces, records and saves.
static func ints(v: Variant) -> Variant:
match typeof(v):
TYPE_FLOAT:
return int(v) if v == floorf(v) and absf(v) < 9.0e15 else v
TYPE_ARRAY:
var out := []
for x in v:
out.append(ints(x))
return out
TYPE_DICTIONARY:
var out := {}
for k in v:
out[k] = ints(v[k])
return out
return v

1
engine/util.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://ct6brxi508dhp