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

1245 lines
49 KiB
GDScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

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

class_name GreedyBot
extends RefCounted
## The greedy bot (bots/greedy.ts). It plans each turn up front: grabs the best open locations,
## attacks when the odds clear `minWinChance`, guards threatened locations, installs Hardware and
## Programs, and walls off undefended locations. On the opponent's turn it answers with combat
## tricks after the roll and tries to stop advances into its locations.
##
## Same shape as RandomBot: `bot_name`, and `choose(view, actions, me)`. It keeps a plan per turn,
## so make one per game. It only reads `view` (which shares parts with the real state).
const DEFAULT := {
## Only attack when the chance to win is at least this.
"minWinChance": 0.6,
## Firewall level used to wall off undefended frontier locations; 0 = never place Firewalls.
"firewallLevel": 1,
"maxFirewallsPerTurn": 2,
## Bandwidth, counting salvageable cards, kept back after spending in step 6.
"bandwidthReserve": 6,
## Play Programs, Executions and Abilities. Off plays like the Phase 2 bot: Core Hardware only.
"useCards": true,
## Extra value of a capture per Anomaly it unlocks (a location is worth about 12). 0 ignores unlocks.
"unlockPoints": 15,
}
## Bot styles to pick from: parameter presets, as the app offers (BOT_STYLES in app/src/match.ts).
const STYLES := {
"greedy": {
"label": "Greedy",
"about": "The sim’s standard bot: attacks at 60%+ odds, walls with Lv 1 Firewalls, plays its cards.",
"params": {"minWinChance": 0.6, "firewallLevel": 1, "maxFirewallsPerTurn": 2, "bandwidthReserve": 6, "useCards": true, "unlockPoints": 15},
},
"cautious": {
"label": "Cautious",
"about": "Greedy, but attacks only at 75%+ odds.",
"params": {"minWinChance": 0.75, "firewallLevel": 1, "maxFirewallsPerTurn": 2, "bandwidthReserve": 6, "useCards": true, "unlockPoints": 15},
},
"bold": {
"label": "Bold",
"about": "Greedy, but attacks at 50%+ odds.",
"params": {"minWinChance": 0.5, "firewallLevel": 1, "maxFirewallsPerTurn": 2, "bandwidthReserve": 6, "useCards": true, "unlockPoints": 15},
},
"wall3": {
"label": "Wall builder",
"about": "Greedy, but walls off with Lv 3 Firewalls.",
"params": {"minWinChance": 0.6, "firewallLevel": 3, "maxFirewallsPerTurn": 2, "bandwidthReserve": 6, "useCards": true, "unlockPoints": 15},
},
"nocards": {
"label": "Easy",
"about": "Greedy, but only uses Core Hardware: no Programs, Executions or Abilities.",
"params": {"minWinChance": 0.6, "firewallLevel": 1, "maxFirewallsPerTurn": 2, "bandwidthReserve": 6, "useCards": false, "unlockPoints": 15},
},
}
const BP := BotEval.BANDWIDTH_POINTS
const CARD_POINTS := BotEval.CARD_POINTS
# ---------------------------------------------------------------------------------------------
# How much the bot wants each card
## Programs by how much they help where they're installed, roughly in points per turn.
const PROGRAM_WEIGHT := {
"Stack Overflow": 4, "Race Condition": 3, "Bloatware": 3, "Visual Artifact": 2, "Memory Parasite": 2,
"Recursive Infection": 2, "Resource Leech": 2, "Overflow Error": 2, "Persistent Infection": 1, "Stock Rice": 1.5,
"Packet Loss": 1.5, "Null Pointer": 1.5, "Fragmentation": 1, "Latency Spike": 1, "Desynchronization": 0.5,
"False Positive": 0.5, "Hotfix": 0.5, "Version Control": 1.5, "Compatibility Layer": 1.5, "Replication Routine": 1,
"Worm Protocol": 1.5, "Payload Injector": 0.5, "Ghost Process": 0.5, "Garbage Collection": 1, "Error Correction": 0.5,
"Rollback Routine": 1, "Undefined Behavior": 1.5, "Infinite Loop": 2,
}
## Programs that only matter when an enemy attacks their location.
const DEFENSIVE := {
"Stack Overflow": true, "Race Condition": true, "Bloatware": true, "Visual Artifact": true, "Memory Parasite": true,
"Recursive Infection": true, "Resource Leech": true, "Overflow Error": true, "Persistent Infection": true,
"Stock Rice": true, "Packet Loss": true, "Null Pointer": true, "Fragmentation": true, "Latency Spike": true,
"Desynchronization": true, "False Positive": true, "Version Control": true, "Undefined Behavior": true,
}
const UTILITY_HARDWARE := {
"Redundant Power Supply": 2, "RAID Array": 1.5, "Diagnostic Module": 1.5, "Firewall Appliance": 1, "ECC Memory": 1,
"Hardware Sandbox": 1, "Dedicated GPU": 1, "Quantum Coprocessor": 1, "Hot-Swap Bay": 1, "Solid-State Cache": 1,
"Cooling System": 0.5, "Network Interface Upgrade": 1.5,
}
## Executions worth holding for the opponent's turn.
const HELD := {
"Execute: Emergency Shutdown": true, "Execute: Disconnect": true, "Execute: Sabotage": true, "Execute: Packet Flood": true,
}
## Executions and Abilities that can change a combat already under way.
const COMBAT_TRICKS := {
"Execute: Disconnect": true, "Execute: Sabotage": true, "Execute: Kill Process": true, "Execute: Force Reboot": true,
"Execute: Fork": true, "Execute: Override": true, "Execute: Emergency Shutdown": true, "Execute: Process Clone": true,
"Execute: Defragment": true, "Execute: Remote Access": true, "Execute: Purge": true, "Corrupt Driver": true,
"Pixelated Picture": true, "Beta Version 1.0": true, "Code Zero": true, "Broken Bits": true, "Hot-Swap Bay": true,
"Rollback Routine": true, "Undefined Behavior": true,
}
## Enemy Programs that make an attack on a location harder.
const HARD_TARGET := {
"Stack Overflow": true, "Race Condition": true, "Bloatware": true, "Visual Artifact": true, "Memory Parasite": true,
"Stock Rice": true,
}
const DUPLICATE_RANK := ["Cloud Compute", "Server Farm", "MultiCore Server", "High Bandwidth Server", "Power Server",
"Cluster Server", "Pingable Server", "Backup Server", "Protected Server"]
var bot_name := "greedy"
var params: Dictionary
# Per-game memory.
## This turn's plan from the deploy step: {turn, deploy, attacks, attackers (slot -> true)}, or null.
var _plan = null
var _queue_for := ""
var _queue := []
var _copied_turn := -1
## Responses already tried in this window, so one that can't be paid for isn't retried forever.
var _tried := {}
var _tried_for := ""
func _init(p: Dictionary = {}) -> void:
params = DEFAULT.duplicate()
params.merge(p, true)
bot_name = "greedy" if params.useCards else "greedy-nocards"
# ---------------------------------------------------------------------------------------------
# Small helpers
static func _name(v: Dictionary, id: int) -> String:
return BotEval.card_name(v, id)
static func _bw(v: Dictionary, id: int) -> int:
return BotEval.printed_bandwidth(v, id)
## TS `===` for the values choices carry: numbers by value, everything else by type and value.
static func _same(a: Variant, b: Variant) -> bool:
var na := typeof(a) == TYPE_INT or typeof(a) == TYPE_FLOAT
var nb := typeof(b) == TYPE_INT or typeof(b) == TYPE_FLOAT
if na and nb:
return a == b
return typeof(a) == typeof(b) and a == b
## `a.args.to ?? a.target`.
static func _to_or_target(a: Dictionary) -> Variant:
var to = a.args.get("to")
return to if to != null else a.get("target")
## Board order as seen from `me`'s side. North gets South's order rotated 180°, which maps the board
## onto itself, so tie-breaks never favor a seat.
static func _grid_from(me: int) -> Array:
if me == 0:
return GameMap.GRID
var out: Array = GameMap.GRID.duplicate()
out.reverse()
return out
static func _locations_from(me: int) -> Array:
if me == 0:
return GameMap.LOCATIONS
var out: Array = GameMap.LOCATIONS.duplicate()
out.reverse()
return out
## How much the bot wants to keep a card rather than salvage it. Below 3 is fodder.
static func _keep_score(v: Dictionary, id: int) -> float:
var def := State.def_of(v, id)
if def.kind == "anomaly":
return 1.0 if _recruit_slot(v, v.cards[id].owner, id) == null else 7.0
if def.kind == "hardware":
if BotEval.hardware_cores(v, id) > 0 or BotEval.hardware_health(v, id) > 0:
return 6.0
return UTILITY_HARDWARE.get(def.name, 0) * 2.0
if def.kind == "program":
return PROGRAM_WEIGHT.get(def.name, 1)
if HELD.has(def.name):
return 4.0
return 1.5
## Bandwidth available this turn, counting cards the bot is willing to salvage.
static func _spendable(v: Dictionary, me: int) -> int:
var pl: Dictionary = v.players[me]
var n: int = pl.bandwidth
for id in pl.hand:
if _keep_score(v, id) < 3:
n += _bw(v, id)
return n
## The salvage that best covers `cost`, never the card being paid for. Null if none is needed or
## possible.
static func _salvage_for(v: Dictionary, me: int, cost: int, except: Variant = null) -> Variant:
var pl: Dictionary = v.players[me]
var need: int = cost - pl.bandwidth
if need <= 0:
return null
var hand: Array = pl.hand.filter(func(id): return id != except and id >= 0)
var total := 0
for id in hand:
total += _bw(v, id)
if total < need:
return null
var order := Util.sorted_cmp(hand, func(a, b):
var d := _keep_score(v, a) - _keep_score(v, b)
return d if d != 0 else float(_bw(v, b) - _bw(v, a)))
var fodder := order.filter(func(id): return _keep_score(v, id) < 3)
var fodder_bw := 0
for id in fodder:
fodder_bw += _bw(v, id)
var from := fodder if fodder_bw >= need else order
var card = null
for id in from:
if _bw(v, id) >= need:
card = id
break
if card == null:
card = from[0]
return {"type": "salvage", "card": card}
## The card an action spends from hand, so Salvage doesn't use it.
static func _spent_card(a: Dictionary) -> Variant:
if a.type in ["play", "installHardware", "installProgram", "recruit"]:
return a.card
return null
# ---------------------------------------------------------------------------------------------
# Recruiting (recruit rule)
## Where the bot would recruit Anomaly `id`: an empty slot while there's room, otherwise over a
## weaker Anomaly (fewer Cores) that carries no Hardware, preferring one sitting in its slot.
## `taken` are slots already planned this step.
static func _recruit_slot(v: Dictionary, me: int, id: int, taken: Array = []) -> Variant:
if not v.rules.recruit.on:
return null
var avs: Array = v.players[me].anomalies
var cores := func(card: int) -> int: return State.def_of(v, card).cores
var empty := -1
for i in avs.size():
if i < 4 and avs[i].card < 0 and not taken.has(i + 1):
empty = i
break
var planned := taken.filter(func(slot): return avs[slot - 1].card < 0).size()
var in_use := 0
for i in avs.size():
if (avs[i].card >= 0) if i < 4 else (avs[i].at != null):
in_use += 1
if empty >= 0 and Query.anomaly_room(v, me) and in_use + planned < 4:
return empty + 1
var weaker := RulesEngine.recruit_slots(v, me).filter(func(slot):
return not taken.has(slot) and avs[slot - 1].card >= 0 and avs[slot - 1].hardware.is_empty())
weaker = weaker.filter(func(slot): return cores.call(avs[slot - 1].card) < cores.call(id))
weaker = Util.sorted_cmp(weaker, func(a, b):
var d := int(avs[a - 1].at != null) - int(avs[b - 1].at != null)
return d if d != 0 else cores.call(avs[a - 1].card) - cores.call(avs[b - 1].card))
return weaker[0] if not weaker.is_empty() else null
## Recruit the strongest Anomalies in hand that fit, within `budget`.
static func _recruit_plan(v: Dictionary, me: int, budget: int) -> Array:
if not v.rules.recruit.on:
return []
var hand: Array = v.players[me].hand.filter(func(id): return id >= 0 and State.def_of(v, id).kind == "anomaly")
hand = Util.sorted_cmp(hand, func(a, b): return State.def_of(v, b).cores - State.def_of(v, a).cores)
var out := []
for card in hand:
var price := _bw(v, card)
var slot = _recruit_slot(v, me, card, out.map(func(a): return a.slot)) if price <= budget else null
if slot == null:
continue
out.append({"type": "recruit", "card": card, "slot": slot})
budget -= price
return out
static func _reach(v: Dictionary, me: int) -> int:
var n: int = v.players[me].bandwidth
for id in v.players[me].hand:
n += _bw(v, id)
return n
# ---------------------------------------------------------------------------------------------
# The board
static func _enemy_next_to(v: Dictionary, p: int, loc: String) -> bool:
for l in GameMap.LINES_AT[loc]:
if State.is_open(v, l) and State.controls(v, p, GameMap.other_end(l, loc)):
return true
return false
## My grid locations the opponent could advance into or attack, most valuable to them first.
static func _threatened(v: Dictionary, me: int) -> Array:
var opp := State.other(me)
var out := _grid_from(me).filter(func(loc): return State.controls(v, me, loc) and _enemy_next_to(v, opp, loc))
return Util.sorted_cmp(out, func(a, b): return BotEval.location_value(v, opp, b) - BotEval.location_value(v, opp, a))
## Anomalies `me` can place, advance or attack with this turn: [{at, slot}].
static func _ready_anomalies(v: Dictionary, me: int) -> Array:
var out := []
var avs: Array = v.players[me].anomalies
for i in avs.size():
var a: Dictionary = avs[i]
var slot := i + 1
if a.faceUp and not a.advanced and a.attacks == 0 and (a.at == null or State.can_act(v, State.ref(me, slot))):
out.append({"at": a.at, "slot": slot})
return out
static func _advance_count(v: Dictionary, me: int) -> int:
var n := 0
for loc in GameMap.GRID:
if not State.controls(v, me, loc) and State.defenders_at(v, loc).is_empty() and _enemy_next_to(v, me, loc):
n += 1
return n
## Infinite Loop: extra attacks for my Anomalies attacking from `loc`.
static func _extra_attacks_at(v: Dictionary, me: int, loc: String) -> int:
var n := 0
for x in Query.sources(v):
if x.at == loc and x.controller == me:
n = maxi(n, CardScripts.of(x.name).get("extraAttacks", 0))
return n
static func _clear_cost(v: Dictionary, o: Dictionary) -> int:
return State.firewall_cost(v, v.firewalls.get(o.clear, 0)) if o.clear != null else 0
## Deploy-step plan for the whole turn: which Anomalies advance, which attack and from where, and
## where the rest stand guard. An option is {kind, slot, to, origin, clear, score}; origin is where
## an attacker must stand and clear a Firewall to clear first (each null when there's none).
static func _plan_turn(v: Dictionary, me: int, params: Dictionary) -> Dictionary:
var pl: Dictionary = v.players[me]
var mine := _locations_from(me).filter(func(l): return State.controls(v, me, l))
var ready := _ready_anomalies(v, me)
var occupant := {}
for i in pl.anomalies.size():
if pl.anomalies[i].at != null:
occupant[pl.anomalies[i].at] = i + 1
for x in ready:
if x.at != null:
occupant[x.at] = x.slot
var budget := _spendable(v, me)
var options := []
var long_shots := []
for to in _grid_from(me):
if State.controls(v, me, to):
continue
var defended := not State.defenders_at(v, to).is_empty()
var value: float = BotEval.location_value(v, me, to) + params.unlockPoints * BotEval.unlocks_at(v, me, to)
for line in GameMap.LINES_AT[to]:
var from := GameMap.other_end(line, to)
if not State.controls(v, me, from):
continue
var level: int = v.firewalls.get(line.id, 0)
var clear_cost := State.firewall_cost(v, level)
if clear_cost > budget:
continue
var clear = line.id if level else null
for x in ready:
var slot: int = x.slot
var r := State.ref(me, slot)
if State.fresh_copy(v, r):
continue
if not defended:
# Advancing needs no dice, so prefer weak Anomalies and save strong ones for attacks.
var weakness := 0.01 * Query.cores_of(v, {"ref": r, "role": "attack", "at": null, "loc": null, "combat": null})
options.append({"kind": "advance", "slot": slot, "to": to, "origin": null, "clear": clear, "score": value - clear_cost * BP - weakness})
continue
var holder = occupant.get(from)
if holder != null and holder != slot:
continue
var chance := BotEval.attack_odds(v, r, from, to)
if chance < params.minWinChance:
# Health rule: a lost roll only costs damage, so a healthy Anomaly keeps a long shot in
# reserve for when there's nothing better to do (see below).
if v.rules.health.on and chance >= 0.25 and Query.health_left(v, r) * 2 >= Query.health_of(v, r):
long_shots.append({"kind": "attack", "slot": slot, "to": to, "origin": from, "clear": clear, "score": chance})
continue
var score := BotEval.attack_value(v, r, from, to, value) - clear_cost * BP
options.append({"kind": "attack", "slot": slot, "to": to, "origin": from, "clear": clear, "score": score})
options = Util.sorted_cmp(options, func(x, y): return y.score - x.score)
var chosen := []
var uses := {}
var used_targets := {}
var origins := {}
var clears := {}
for o in options:
if o.score <= 0:
break
if v.rules.commands.on and not chosen.is_empty():
break # one advance or attack per command
if used_targets.has(o.to):
continue
var n: int = uses.get(o.slot, 0)
if n > 0:
# A second attack only from an Infinite Loop location, from the same origin.
var first: Dictionary = {}
for c in chosen:
if c.slot == o.slot:
first = c
break
if first.kind != "attack" or o.kind != "attack" or o.origin != first.origin:
continue
if n > _extra_attacks_at(v, me, o.origin):
continue
elif o.origin != null and origins.has(o.origin) and origins[o.origin] != o.slot:
continue
var cost := State.firewall_cost(v, v.firewalls.get(o.clear, 0)) if o.clear != null and not clears.has(o.clear) else 0
if cost > budget:
continue
budget -= cost
if o.clear != null:
clears[o.clear] = true
uses[o.slot] = n + 1
used_targets[o.to] = true
if o.origin != null:
origins[o.origin] = o.slot
chosen.append(o)
if chosen.is_empty():
# Nothing to advance into and no attack at good odds: take the best long shot rather than let
# the game stall with every location defended.
long_shots = Util.sorted_cmp(long_shots, func(x, y): return y.score - x.score)
var shot = null
for o in long_shots:
if _clear_cost(v, o) <= budget:
shot = o
break
if shot != null:
budget -= _clear_cost(v, shot)
if shot.clear != null:
clears[shot.clear] = true
uses[shot.slot] = 1
used_targets[shot.to] = true
origins[shot.origin] = shot.slot
chosen.append(shot)
var deploy := []
for line in clears:
deploy.append({"type": "clearFirewall", "line": line})
var pos := {}
for x in ready:
pos[x.slot] = x.at
var occupied := occupant.duplicate()
var move := func(slot: int, to: String) -> void:
var from = pos.get(slot)
if from != null:
occupied.erase(from)
occupied[to] = slot
pos[slot] = to
deploy.append({"type": "place", "slot": slot, "to": to})
var free_spot := func(prefer: Array) -> Variant:
for l in prefer:
if not occupied.has(l) and not origins.has(l):
return l
return null
var risky := _threatened(v, me)
var final := []
for o in chosen:
if o.kind != "attack":
continue
if pos.get(o.slot) == o.origin:
final.append(o)
elif not occupied.has(o.origin):
move.call(o.slot, o.origin)
final.append(o)
elif final.any(func(f): return f.slot == o.slot and f.origin == o.origin):
final.append(o)
# Advancers still in their slot must enter play first; put them where nobody threatens.
var safe_first := mine.filter(func(l): return not risky.has(l)) + risky
for o in chosen:
if o.kind != "advance":
continue
if pos.get(o.slot) != null:
final.append(o)
else:
var spot = free_spot.call(safe_first)
if spot != null:
move.call(o.slot, spot)
final.append(o)
var busy := {}
for o in final:
busy[o.slot] = true
# Health rule: a badly hurt Anomaly with nothing to do goes back to its slot to heal.
if v.rules.health.on and v.rules.health.recall:
for x in ready:
var slot: int = x.slot
var cur = pos.get(slot)
if busy.has(slot) or cur == null or slot > 4:
continue
var r := State.ref(me, slot)
if Query.health_left(v, r) > maxi(2, ceili(Query.health_of(v, r) * 0.3)):
continue
if busy.has(slot + 4):
continue # recalling would remove its copy, which has a job
busy[slot] = true
occupied.erase(cur)
pos[slot] = null
deploy.append({"type": "recall", "slot": slot})
# Everyone else guards the most threatened free location.
for x in ready:
var slot: int = x.slot
if busy.has(slot):
continue
var cur = pos.get(slot)
if cur != null and risky.has(cur):
continue
var spot = free_spot.call(risky)
if spot == null and cur == null:
spot = free_spot.call(mine)
if spot != null:
move.call(slot, spot)
for o in final:
if o.kind == "advance":
deploy.append({"type": "advance", "slot": o.slot, "to": o.to})
var attacks := []
var attackers := {}
for o in final:
if o.kind == "attack":
attacks.append({"type": "attack", "slot": o.slot, "to": o.to})
attackers[o.slot] = true
return {"turn": v.turn, "deploy": deploy, "attacks": attacks, "attackers": attackers}
# ---------------------------------------------------------------------------------------------
# Playing cards on your own turn
static func _in_hand(v: Dictionary, me: int, card_name: String) -> Variant:
for id in v.players[me].hand:
if _name(v, id) == card_name:
return id
return null
## How much a performing Server adds: Dedicated GPU power, and a Quantum Coprocessor copy.
static func _from_value(v: Dictionary, me: int, from: Variant) -> float:
if from == null:
return 0.0
var qc := false
for r in State.refs_in_play(v, me):
if State.anomaly(v, r).at != from:
continue
for h in State.hardware_of(v, r):
if _name(v, h) == "Quantum Coprocessor" and Query.hardware_active(v, h):
qc = true
return RulesEngine.execution_power(v, me, from) + (0.5 if qc else 0.0)
## A legal play of a named Execution matching `pick`, ignoring Bandwidth, from the best Server.
static func _find_play(v: Dictionary, me: int, card_name: String, pick: Callable) -> Variant:
if _in_hand(v, me, card_name) == null:
return null
var best = null
for a in RulesEngine.execution_actions(v, me, "any"):
if a.type != "play" or _name(v, a.card) != card_name or not pick.call(a):
continue
if best == null or _from_value(v, me, a.from) > _from_value(v, me, best.from):
best = a
return best
## A legal use of a named card's Ability matching `pick`, ignoring Bandwidth.
static func _find_use(v: Dictionary, me: int, card_name: String, pick := Callable()) -> Variant:
for a in RulesEngine.ability_actions(v, me, "any"):
if a.type == "activate" and a.name == card_name and (not pick.is_valid() or pick.call(a)):
return a
return null
## Deploy: make a copy (Replicate, Backup Server) before planning, so it can advance too.
static func _copy_action(v: Dictionary, me: int) -> Variant:
if _advance_count(v, me) == 0:
return null
var risky := _threatened(v, me)
var spot = null
for l in _locations_from(me):
if Query.has_room(v, me, l) and not risky.has(l):
spot = l
break
if spot == null:
for l in _locations_from(me):
if Query.has_room(v, me, l):
spot = l
break
if spot == null:
return null
var backup = _find_use(v, me, "Backup Server", func(a): return a.args.get("to") == spot)
if backup != null:
return backup
var replicate = _find_use(v, me, "Carbon NanoBots", func(a): return a.args.get("to") == spot)
if replicate != null and _spendable(v, me) >= RulesEngine.action_cost(v, replicate) + 4:
return replicate
return null
## Hardware worth installing now: Core Hardware on fighters, useful utility Hardware anywhere.
static func _hardware_plan(v: Dictionary, me: int, attackers: Dictionary, budget: int, use_cards: bool) -> Array:
var pl: Dictionary = v.players[me]
var risky := _threatened(v, me)
var out := []
var wearers := State.refs_in_play(v, me).filter(func(r): return not State.is_copy(r))
wearers = Util.sorted_cmp(wearers, func(x, y): return int(attackers.has(y.slot)) - int(attackers.has(x.slot)))
var free_slots := {}
for r in wearers:
free_slots[r.slot] = Query.slots_free(v, r)
var fights := func(r: Dictionary) -> bool:
return attackers.has(r.slot) or risky.has(State.anomaly(v, r).at)
var has_executions: bool = pl.hand.any(func(id): return State.def_of(v, id).kind == "execution")
# Network Interface Upgrade first, since it opens an Expansion Slot for the rest.
var niu_first := func(id: int) -> int: return 1 if _name(v, id) == "Network Interface Upgrade" else 0
var hand := Util.sorted_cmp(pl.hand, func(a, b):
var d: int = niu_first.call(b) - niu_first.call(a)
return d if d != 0 else BotEval.hardware_cores(v, b) - BotEval.hardware_cores(v, a))
for card in hand:
var def := State.def_of(v, card)
if def.kind != "hardware":
continue
var cores := BotEval.hardware_cores(v, card) + BotEval.hardware_health(v, card)
var target = null
if cores > 0:
# Core Hardware, and Health Hardware (RAM Expansion), go on Anomalies that fight.
var attack_only: bool = def.name == "Packet Accelerator"
for r in wearers:
if free_slots[r.slot] > 0 and fights.call(r) and (not attack_only or attackers.has(r.slot)):
target = r
break
elif def.name == "Network Interface Upgrade":
# Adds an Expansion Slot: best on a fighter whose slots are full.
for r in Util.sorted_cmp(wearers, func(x, y): return free_slots[x.slot] - free_slots[y.slot]):
if fights.call(r):
target = r
break
if target == null and not wearers.is_empty():
target = wearers[0]
elif use_cards and UTILITY_HARDWARE.get(def.name, 0) > 0:
if def.name in ["Dedicated GPU", "Quantum Coprocessor"] and not has_executions:
continue
var protects: bool = def.name in ["Redundant Power Supply", "RAID Array"]
for r in wearers:
var ok: bool = (not State.anomaly(v, r).hardware.is_empty() and free_slots[r.slot] > 0) if protects else free_slots[r.slot] > 1
if ok:
target = r
break
if target == null:
continue
var cost := RulesEngine.hardware_cost(v, card, target)
if cost > budget:
continue
budget -= cost
free_slots[target.slot] += 1 if def.name == "Network Interface Upgrade" else -1
out.append({"type": "installHardware", "card": card, "slot": target.slot})
return out
## Negative effects on an Anomaly that Error Correction or Purge could clear.
static func _afflicted(v: Dictionary, r: Dictionary) -> bool:
var av := State.anomaly(v, r)
return av.infection + av.permanentInfection > 0 or State.hardware_of(v, r).any(func(h): return not Query.hardware_active(v, h))
static func _neighbors_mine(v: Dictionary, me: int, at: String) -> Array:
var out := []
for l in GameMap.LINES_AT[at]:
if State.is_open(v, l) and State.controls(v, me, GameMap.other_end(l, at)):
out.append(GameMap.other_end(l, at))
return out
## How much installing Program `name` on my location `at` is worth, in points.
static func _program_value(v: Dictionary, me: int, card_name: String, at: String, risky: Array) -> float:
var opp := State.other(me)
var w: float = PROGRAM_WEIGHT.get(card_name, 1)
var guarded := not State.defenders_at(v, at).is_empty()
var threat := (1.0 if guarded else 0.4) if risky.has(at) else 0.1
var here: Array = v.locations[at].programs.map(func(id): return _name(v, id))
var hand: Array = v.players[me].hand.map(func(id): return _name(v, id))
var enemy_near := _neighbors_mine(v, opp, at)
var slots: int = Query.program_slots(v, at) - here.size()
match card_name:
"Infinite Loop":
return w if enemy_near.filter(func(l): return not State.defenders_at(v, l).is_empty()).size() >= 2 and guarded else 0.0
"Compatibility Layer":
return w if risky.has(at) else 0.3
"Replication Routine":
var viruses: Array = v.players[me].hand.filter(func(id):
var d := State.def_of(v, id)
return d.type == "V" and d.kind == "program" and _name(v, id) != card_name)
if slots < 2 or viruses.is_empty():
return 0.0
var top := -INF
for id in viruses:
top = maxf(top, _program_value(v, me, _name(v, id), at, risky))
return 0.5 + top
"Garbage Collection", "Hotfix":
return w * threat if not here.is_empty() else 0.0
"Error Correction":
return 2.0 if State.refs_in_play(v, me).any(func(r): return State.anomaly(v, r).at == at and _afflicted(v, r)) else 0.0
"Rollback Routine":
# Helps my Anomalies attacking from here into Programs that cut Cores.
var cutters := enemy_near.any(func(l): return v.locations[l].programs.any(func(id): return _name(v, id) in ["Bloatware", "Visual Artifact"]))
return w * 1.5 if guarded and cutters else 0.0
"Payload Injector":
var n := hand.filter(func(x): return x in ["Execute: Memory Dump", "Execute: Process Clone", "Execute: Purge", "Execute: Hard Reset"]).size()
return w * 1.5 if n >= 1 else 0.0
"Ghost Process":
var tricks := hand.any(func(x): return x in ["Execute: Kill Process", "Execute: Override", "Execute: Sabotage"])
return 1.0 if tricks and enemy_near.any(func(l): return not v.locations[l].programs.is_empty()) else 0.0
"Worm Protocol":
var helps := here.any(func(x): return DEFENSIVE.has(x)) and _neighbors_mine(v, me, at).any(func(l): return risky.has(l))
return w if helps else 0.0
return w * threat * (BotEval.location_value(v, opp, at) / 18) if DEFENSIVE.has(card_name) else w * 0.4
## Programs worth installing, best first.
static func _program_plan(v: Dictionary, me: int, budget: int) -> Array:
var pl: Dictionary = v.players[me]
var risky := _threatened(v, me)
var mine := _locations_from(me).filter(func(l): return State.controls(v, me, l))
var room := {}
for l in mine:
room[l] = Query.program_slots(v, l) - v.locations[l].programs.size()
var picks := []
var seen := {}
for card in pl.hand:
var card_name := _name(v, card)
if not PROGRAM_WEIGHT.has(card_name) or seen.has(card_name):
continue
seen[card_name] = true
for at in mine:
if room[at] <= 0 or v.locations[at].programs.any(func(id): return _name(v, id) == card_name):
continue
var value := _program_value(v, me, card_name, at, risky)
picks.append({"card": card, "at": at, "value": value - RulesEngine.program_cost(v, me, card, at) * BP * 0.3})
picks = Util.sorted_cmp(picks, func(a, b): return b.value - a.value)
var out := []
var used := {}
for p in picks:
if p.value <= 0.3 or used.has(p.card) or room[p.at] <= 0:
continue
var cost := RulesEngine.program_cost(v, me, p.card, p.at)
if cost > budget:
continue
budget -= cost
used[p.card] = true
room[p.at] -= 1
out.append({"type": "installProgram", "card": p.card, "at": p.at})
return out
## Step 3: switch off a Program that guards a location I'm about to attack, when it's worth it.
static func _clear_the_way(v: Dictionary, me: int, plan: Variant) -> Array:
if plan == null or plan.turn != v.turn:
return []
var out := []
for a in plan.attacks:
if a.type != "attack":
continue
var r := State.ref(me, a.slot)
if State.anomaly(v, r).at == null:
continue # the planned attacker left play (a copy removed by a recall)
var origin = null
for i in range(plan.deploy.size() - 1, -1, -1):
var d: Dictionary = plan.deploy[i]
if d.type == "place" and d.slot == a.slot:
origin = d
break
var from = origin.to if origin != null else State.anomaly(v, r).at
if from == null:
continue
var before := BotEval.attack_odds(v, r, from, a.to)
var best = null
for card_name in ["Execute: Kill Process", "Execute: Override"]:
if _in_hand(v, me, card_name) == null:
continue
for play in RulesEngine.execution_actions(v, me, "any"):
if play.type != "play" or _name(v, play.card) != card_name:
continue
var prog = play.args.get("card")
if prog == null or State.program_location(v, prog) != a.to or not HARD_TARGET.has(_name(v, prog)):
continue
var after = _simulate(v, me, play)
if after == null:
continue
var gain := BotEval.attack_odds(after, r, from, a.to) - before
if gain > 0.08 and (best == null or gain > best.gain):
best = {"play": play, "gain": gain}
if best != null:
out.append(best.play)
return out
## Step 3: extra captures with Trace Route, and cleaning up Anomalies before they fight.
static func _pre_attack_plays(v: Dictionary, me: int, plan: Variant) -> Array:
var out := []
var planned: Dictionary = plan.attackers if plan != null and plan.turn == v.turn else {}
var trace = _in_hand(v, me, "Execute: Trace Route")
if trace != null and _spendable(v, me) >= 5:
var best = null
for a in RulesEngine.execution_actions(v, me, "any"):
if a.type != "play" or a.card != trace:
continue
var r: Dictionary = a.args.ref
var av := State.anomaly(v, r)
var t: String = a.target
if planned.has(r.slot) or av.advanced or av.attacks > 0 or State.controls(v, me, t):
continue
# Don't pull a guard off a threatened location.
if _threatened(v, me).has(av.at) and State.defenders_at(v, av.at).size() < 2:
continue
if v.declarations.any(func(d): return d.to == t):
continue
var value := BotEval.location_value(v, me, t)
var bonus: int = 1 + RulesEngine.execution_power(v, me, a.from)
var defended := not State.defenders_at(v, t).is_empty()
var chance := BotEval.attack_odds(v, r, av.at, t, bonus) if defended else 1.0
var score := (BotEval.attack_value(v, r, av.at, t, value, bonus) if defended else value) - 5 * BP - CARD_POINTS
if chance >= 0.6 and score > 0 and (best == null or score > best.score):
best = {"a": a, "score": score}
if best != null:
out.append(best.a)
# Clean up Anomalies carrying Infection or disabled Hardware.
for r in State.refs_in_play(v, me):
var av := State.anomaly(v, r)
var disabled := State.hardware_of(v, r).filter(func(h): return not Query.hardware_active(v, h))
if av.infection + av.permanentInfection < 2 and disabled.is_empty():
continue
var purge = _find_play(v, me, "Execute: Purge", func(a): return _to_or_target(a) == av.at)
if purge != null:
out.append(purge)
elif not disabled.is_empty():
var defrag = _find_play(v, me, "Execute: Defragment", func(a): return a.args.get("card") == disabled[0])
if defrag != null:
out.append(defrag)
return out
## Step 6: card draw, Exfiltrate, Restore Point and Undefined Behavior, when Bandwidth is spare.
static func _utility_plays(v: Dictionary, me: int, budget: int) -> Array:
var out := []
var left := [budget]
var add := func(a: Variant, cost: int) -> void:
if a != null and cost <= left[0]:
out.append(a)
left[0] -= cost
add.call(_find_play(v, me, "Execute: Memory Dump", func(a): return a.target != null and State.controls(v, me, a.target)), 4)
add.call(_find_play(v, me, "Execute: Ping Sweep", func(_a): return true), 4)
if not v.players[State.other(me)].hand.is_empty():
add.call(_find_use(v, me, "Data Leaker"), 3)
# Restore Point: heal a wounded Backup Machine first, otherwise recover a good card.
add.call(_find_use(v, me, "Backup Machine", func(a):
if not a.args.get("heal", false):
return false
for r in State.refs_in_play(v, me):
if State.anomaly(v, r).card == a.card and not State.is_copy(r):
return State.anomaly(v, r).damage >= 3
return false), 5)
add.call(_find_use(v, me, "Backup Machine", func(a):
if a.args.get("heal", false):
return false
var id: int = a.args.card
return BotEval.hardware_cores(v, id) > 0 or PROGRAM_WEIGHT.get(_name(v, id), 0) >= 2), 5)
# Undefined Behavior: copy a strong defensive Program onto its own location.
add.call(_find_use(v, me, "Undefined Behavior", func(a):
return _name(v, a.args.card) in ["Stack Overflow", "Race Condition", "Bloatware"]), 0)
return out
## Firewalls around undefended threatened locations whose every enemy line has a gateway.
static func _firewall_plan(v: Dictionary, me: int, params: Dictionary, budget: int) -> Array:
if params.firewallLevel <= 0:
return []
var pl: Dictionary = v.players[me]
var opp := State.other(me)
var out := []
var cost := State.firewall_cost(v, params.firewallLevel)
var left: int = params.maxFirewallsPerTurn
for loc in _threatened(v, me):
if pl.anomalies.any(func(a): return a.at == loc):
continue
var exposed: Array = GameMap.LINES_AT[loc].filter(func(l): return State.is_open(v, l) and State.controls(v, opp, GameMap.other_end(l, loc)))
# A location reachable along a gateway-free line can't be walled off.
if exposed.any(func(l): return not l.gateway) or exposed.size() > left:
continue
if budget - cost * exposed.size() < params.bandwidthReserve:
break
for line in exposed:
out.append({"type": "firewall", "line": line.id, "level": params.firewallLevel})
budget -= cost * exposed.size()
left -= exposed.size()
return out
## Bandwidth to keep for the opponent's turn: enough for the best trick held.
static func _held_reserve(v: Dictionary, me: int, params: Dictionary) -> int:
if not params.useCards:
return 0
var n := 0
for id in v.players[me].hand:
if HELD.has(_name(v, id)):
n = maxi(n, _bw(v, id))
return n
static func _total_cost(v: Dictionary, list: Array) -> int:
var n := 0
for a in list:
n += RulesEngine.action_cost(v, a)
return n
static func _plan_play(v: Dictionary, me: int, params: Dictionary, plan: Variant) -> Array:
var budget := _spendable(v, me)
var attackers: Dictionary = plan.attackers if v.step == "play" and plan != null and plan.turn == v.turn else {}
var sale = RulesEngine.anomaly_for_sale(v, me)
var recruits := _recruit_plan(v, me, budget)
if sale != null and sale.price <= budget:
recruits.append({"type": "buyAnomaly", "slot": sale.slot})
if v.step == "play":
var early := []
if params.useCards:
early = _clear_the_way(v, me, plan) + _pre_attack_plays(v, me, plan)
return recruits + early + _hardware_plan(v, me, attackers, budget - _total_cost(v, recruits + early), params.useCards)
var keep := _held_reserve(v, me, params)
var hw := _hardware_plan(v, me, attackers, budget - keep - _total_cost(v, recruits), params.useCards)
var left := budget - keep - _total_cost(v, recruits + hw)
var progs := _program_plan(v, me, left - params.bandwidthReserve) if params.useCards else []
left -= _total_cost(v, progs)
var walls := _firewall_plan(v, me, params, left)
left -= _total_cost(v, walls)
var extra := _utility_plays(v, me, left - params.bandwidthReserve) if params.useCards else []
return recruits + hw + progs + walls + extra
# ---------------------------------------------------------------------------------------------
# Responding
## Plays out an Execution or Ability on a copy of the view, to see what it would do. Null if it
## failed (where TS catches a throw).
static func _simulate(v: Dictionary, me: int, a: Dictionary) -> Variant:
# Copy only what card effects change; card definitions and rules are shared read-only.
var c := v.duplicate()
c.players = v.players.duplicate(true)
c.locations = v.locations.duplicate(true)
c.cards = v.cards.map(func(x): return x.duplicate())
c.firewalls = v.firewalls.duplicate()
c.declarations = v.declarations.duplicate()
c.tasks = v.tasks.duplicate()
c.stack = v.stack.duplicate()
c.combat = v.combat.duplicate(true) if v.combat != null else null
c.virtuals = v.virtuals.map(func(x): return x.duplicate())
c.used = v.used.duplicate()
c.stats = v.stats.duplicate(true)
c.cardUse = {}
c.log = null
var errors := Util.errors.size()
var was_quiet := Util.quiet
Util.quiet = true
if a.type == "play":
var card_name := _name(c, a.card)
State.remove_from(c.players[me].hand, a.card)
var item := {
"kind": "execution", "player": me, "card": a.card, "name": card_name, "target": a.target, "args": a.args,
"from": a.from, "power": RulesEngine.execution_power(c, me, a.from),
}
CardScripts.of(card_name).execution.resolve.call(c, item)
elif a.type == "activate":
var src = RulesEngine.ability_source(c, a.card, a.name)
if src == null:
Util.quiet = was_quiet
return null
var item := {"kind": "ability", "player": me, "card": a.card, "name": a.name, "target": null, "args": a.args, "from": null, "power": 0}
CardScripts.of(src.name).ability.resolve.call(c, item, src)
Util.quiet = was_quiet
if Util.errors.size() > errors:
Util.errors.resize(errors)
return null
c.choice = null
return c
## Whether a candidate touches the current combat at all, to skip pointless simulations.
static func _touches_combat(v: Dictionary, a: Dictionary) -> bool:
var c: Dictionary = v.combat
var near := [c.loc, c.origin]
if a.type == "activate":
return COMBAT_TRICKS.has(a.name)
if a.type != "play" or not COMBAT_TRICKS.has(_name(v, a.card)):
return false
if a.args.get("ref") != null:
return true
if a.args.get("card") != null:
var loc = State.program_location(v, a.args.card)
return near.has(loc) if loc != null else true
var to = a.args.get("to")
return near.has(a.target) or near.has(to if to != null else "")
static func _price(v: Dictionary, a: Dictionary) -> float:
var card: bool = a.type == "play" or (a.type == "activate" and a.name == "Beta Version 1.0")
return RulesEngine.action_cost(v, a) * BP + (CARD_POINTS if card else 0.0)
## The best combat trick for `me` once the dice are down, if one is worth its cost.
static func _combat_trick(v: Dictionary, me: int) -> Variant:
var c: Dictionary = v.combat
if not c.rolled:
return null
var base := BotEval.combat_value(v, me)
var best = null
var best_gain := 0.25
for a in RulesEngine.execution_actions(v, me, "reachable") + RulesEngine.ability_actions(v, me, "reachable"):
if not _touches_combat(v, a):
continue
var value: float
if a.type == "activate" and a.name == "Broken Bits":
var r = null
for x in State.refs_in_play(v, me):
if State.anomaly(v, x).card == a.card and not State.is_copy(x):
r = x
break
value = BotEval.combat_value(v, me, {"ref": r, "k": a.args.k})
else:
var after = _simulate(v, me, a)
if after == null:
continue
value = BotEval.combat_value(after, me) + (_from_value(v, me, a.from) * 0.1 if a.type == "play" else 0.0)
var gain := value - base - _price(v, a)
if gain > best_gain:
best = a
best_gain = gain
return best
## Outside combat: try to stop the opponent's newest advance or attack on one of my locations.
static func _stop_declaration(v: Dictionary, me: int) -> Variant:
if v.declarations.is_empty():
return null
var d: Dictionary = v.declarations[v.declarations.size() - 1]
if d.ref.player == me or not State.controls(v, me, d.to):
return null
var at = State.anomaly(v, d.ref).at
if at == null:
return null
var defended := not State.defenders_at(v, d.to).is_empty()
var risk := BotEval.fall_chance(v, d.ref, d.from, d.to) if defended else 1.0
var stake := risk * BotEval.location_value(v, d.ref.player, d.to)
# Root the Anomaly that declared, so it can't move.
var flood = _find_play(v, me, "Execute: Packet Flood", func(a): return _to_or_target(a) == at)
if flood != null and stake > 5 * BP + CARD_POINTS + 2:
return flood
if defended:
return null
# Put a copy in the way.
var replicate = _find_use(v, me, "Carbon NanoBots", func(a): return a.args.get("to") == d.to)
var copy = _find_use(v, me, "Backup Server", func(a): return a.args.get("to") == d.to)
if copy == null and replicate != null and _reach(v, me) >= RulesEngine.action_cost(v, replicate):
copy = replicate
if copy != null:
return copy
# Or cash in the Programs there before they're lost.
var progs: Array = v.locations[d.to].programs
if progs.is_empty():
return null
var top := 0
for i in progs.size():
top = _bw(v, progs[i]) if i == 0 else maxi(top, _bw(v, progs[i]))
var gc = _find_use(v, me, "Garbage Collection", func(a):
return State.program_location(v, a.args.card) == d.to and _bw(v, a.args.card) == top)
if gc != null:
return gc
var reset = _find_play(v, me, "Execute: Hard Reset", func(a): return a.target == d.to and a.args.cards.size() == progs.size())
var total := 0
for p in progs:
total += _bw(v, p)
return reset if reset != null and total >= 8 else null
## Sends back an expensive enemy Program or Hardware installed this turn.
static func _rollback_install(v: Dictionary, me: int) -> Variant:
return _find_play(v, me, "Execute: Rollback", func(a): return v.cards[a.args.card].owner != me and _bw(v, a.args.card) >= 7)
# ---------------------------------------------------------------------------------------------
# Choices
static func _choose_index(v: Dictionary, me: int, ch: Dictionary) -> int:
var opts: Array = ch.options
var val := func(i: int) -> Variant: return opts[i].value
var best := func(score: Callable) -> int:
var b := 0
for i in range(1, opts.size()):
if score.call(i) > score.call(b):
b = i
return b
var card_val := func(id: int) -> float: return _keep_score(v, id) + _bw(v, id) * 0.2
var find := func(pred: Callable) -> int:
for i in opts.size():
if pred.call(opts[i]):
return i
return -1
var yes_if_affordable := func(yes: Variant) -> int:
var i: int = find.call(func(o): return _same(o.value, yes))
if i >= 0 and opts[i].get("cost", 0) <= v.players[me].bandwidth:
return i
return find.call(func(o): return not _same(o.value, yes))
match ch.kind:
"Callable Server:redraw":
# The drawn card, unless it has left the hand since (salvaged while choosing).
var card: int = ch.resume.data.card
var redraw: bool = v.players[me].hand.has(card) and _keep_score(v, card) < 2
return find.call(func(o): return _same(o.value, redraw))
"Diagnostic Module:bottom":
var weak: bool = opts.any(func(o): return ["Network Interface", "Root Access", "Execute: Rollback", "Ping Sweep"].any(func(w): return o.label.contains(w)))
return find.call(func(o): return _same(o.value, weak))
"Duplicate Server:copy":
return best.call(func(i):
var k := DUPLICATE_RANK.find(str(val.call(i))) + 1
return -(k if k != 0 else 99))
"Memory Parasite:disable", "Overclocked CPU:disable":
return best.call(func(i): return -(BotEval.hardware_cores(v, val.call(i)) * 10 + card_val.call(val.call(i))))
"Replication Routine:install":
return best.call(func(i): return 0.5 if val.call(i) == null else PROGRAM_WEIGHT.get(_name(v, val.call(i)), 1))
"Worm Protocol:spread":
var risky := _threatened(v, me)
return best.call(func(i):
var loc = val.call(i)
return 2 if risky.has(loc) else (1 if State.controls(v, me, loc) else 0))
"Race Condition:pick":
return (v.seq + v.turn + me) % 2
"Overflow Error:hit":
return best.call(func(i):
var x: Dictionary = val.call(i)
return _bw(v, x.card) + (0.5 if x.mode == "destroy" else 0.0))
"Error Correction:remove":
return best.call(func(i):
var x := str(val.call(i))
if x.begins_with("hw:"):
return 4 + BotEval.hardware_cores(v, int(x.substr(3)))
return 3 if x == "permanent" else (2 if x == "infection" else 1))
"Version Control:save", "Hardware Sandbox:protect":
return best.call(func(i): return _bw(v, val.call(i)) + PROGRAM_WEIGHT.get(_name(v, val.call(i)), 0))
"RAID Array:keep", "Backup Machine:install":
return yes_if_affordable.call(true)
"Quantum Coprocessor:copy", "False Positive:redirect":
return 1 if opts.size() > 1 else 0
"Execute: Memory Dump:discard":
return best.call(func(i): return -card_val.call(val.call(i)))
"Data Leaker:discard":
return best.call(func(i): return _bw(v, val.call(i)))
return 0
# ---------------------------------------------------------------------------------------------
## The next action toward `a`: a Salvage to afford it, or `a` itself. Null if it can't happen.
static func _toward(v: Dictionary, me: int, a: Dictionary, legal: Dictionary) -> Variant:
var cost := RulesEngine.action_cost(v, a)
if cost > v.players[me].bandwidth:
return _salvage_for(v, me, cost, _spent_card(a))
return legal.get(RulesEngine.action_key(a))
func choose(v: Dictionary, actions: Array, me: int) -> Dictionary:
var legal := {}
for a in actions:
legal[RulesEngine.action_key(a)] = a
if v.choice != null:
var pick = legal.get("choose:%d" % _choose_index(v, me, v.choice))
if pick != null:
return pick
for a in actions:
if a.type == "choose":
return a
return actions[0]
var w = RulesEngine.open_window(v)
if w != null:
if not params.useCards:
return {"type": "pass"}
var combat_id: int = v.combat.id if v.combat != null else 0
var ties: int = v.combat.ties if v.combat != null else 0
var key := "%d:%s:%d:%d:%d" % [v.turn, w.kind, v.stack.size(), combat_id, ties]
if key != _tried_for:
_tried_for = key
_tried = {}
var want = null
if v.combat != null and not v.combat.ended:
if w.kind == "postRoll":
want = _combat_trick(v, me)
elif w.kind == "response" and v.active != me and v.stack.is_empty():
want = _stop_declaration(v, me)
if want == null:
want = _rollback_install(v, me)
if want != null and not _tried.has(RulesEngine.action_key(want)):
var next = _toward(v, me, want, legal)
if next != null:
if next.type != "salvage":
_tried[RulesEngine.action_key(want)] = true
return next
_tried[RulesEngine.action_key(want)] = true
return {"type": "pass"}
var step_key := "%d:%s" % [v.turn, v.step]
if step_key != _queue_for:
if v.step == "deploy" and params.useCards and _copied_turn != v.turn:
_copied_turn = v.turn
var copy = _copy_action(v, me)
var next = _toward(v, me, copy, legal) if copy != null else null
if next != null:
if next.type == "salvage":
_copied_turn = -1
return next
_queue_for = step_key
if v.step == "deploy":
_plan = _plan_turn(v, me, params)
_queue = _plan.deploy.duplicate()
elif v.step == "attack":
_queue = _plan.attacks.duplicate() if _plan != null and _plan.turn == v.turn else []
else:
_queue = _plan_play(v, me, params, _plan)
while not _queue.is_empty():
var next: Dictionary = _queue[0]
var cost := RulesEngine.action_cost(v, next)
if cost > v.players[me].bandwidth:
var salvage = _salvage_for(v, me, cost, _spent_card(next))
if salvage != null:
return salvage
_queue.pop_front()
continue
_queue.pop_front()
var action = legal.get(RulesEngine.action_key(next))
if action != null:
return action
return {"type": "end"}