From d424ccb74c732fa159a89c326665377bf738822a Mon Sep 17 00:00:00 2001 From: KoalaTrapLord <265133236+KoalaTrapLord@users.noreply.github.com> Date: Mon, 23 Mar 2026 16:52:19 -0400 Subject: [PATCH] feat(86): add combat priority checkpoints with CombatState and split engine methods (#96) --- src/commander_ai_lab/sim/engine.py | 227 +++++++++++++++++++++++ src/commander_ai_lab/sim/game_state.py | 62 ++++++- src/commander_ai_lab/sim/models.py | 33 ++++ src/commander_ai_lab/sim/turn_manager.py | 66 ++++++- tests/test_combat_priority.py | 160 ++++++++++++++++ 5 files changed, 537 insertions(+), 11 deletions(-) create mode 100644 tests/test_combat_priority.py diff --git a/src/commander_ai_lab/sim/engine.py b/src/commander_ai_lab/sim/engine.py index 3197fee..5b0b052 100644 --- a/src/commander_ai_lab/sim/engine.py +++ b/src/commander_ai_lab/sim/engine.py @@ -28,6 +28,7 @@ from typing import Optional from commander_ai_lab.sim.models import ( Card, + CombatState, GameResult, Phase, PHASE_ORDER, @@ -848,6 +849,232 @@ class GameEngine: ) events.extend(combat_details) + # ────────────────────────────────────────────────────────── + # Split combat methods for turn_manager priority windows + # (Issue #86 Item 1). The original _resolve_combat() above + # remains as the backward-compatible atomic path for run_n(). + # ────────────────────────────────────────────────────────── + + def assign_attackers( + self, sim: SimState, pi: int, events: list | None = None, + ) -> Optional[CombatState]: + """Phase 1 of split combat: choose attackers, populate CombatState. + + Returns a CombatState with attackers set and tapped, or None if + no valid attack is possible. Does NOT deal any damage. + """ + p = sim.players[pi] + opp_idx = self._select_attack_target(sim, pi) + if opp_idx == -1: + return None + + opp = sim.players[opp_idx] + w = self.weights + my_creatures = [ + c + for c in sim.get_battlefield(pi) + if ( + c.is_creature() + and not c.tapped + and (c.turn_played < sim.turn or c.has_keyword("haste")) + ) + ] + if not my_creatures: + return None + + opp_blockers = [ + c + for c in sim.get_battlefield(opp_idx) + if c.is_creature() and not c.tapped + ] + + attackers = [] + total_my_power = sum(c.get_power() for c in my_creatures) + for atk in my_creatures: + a_pow = atk.get_power() + a_tou = atk.get_toughness() + has_flying = atk.has_keyword("flying") + has_trample = atk.has_keyword("trample") + has_haste = atk.has_keyword("haste") + + if has_flying or has_trample or has_haste or a_pow >= 3 or opp.life <= total_my_power: + attackers.append(atk) + atk.tapped = True + continue + + can_die_profitably = any( + ( + (not has_flying or b.has_keyword("flying") or b.has_keyword("reach")) + and (b.get_power() >= a_tou or b.has_keyword("deathtouch")) + and b.get_toughness() > a_pow + ) + for b in opp_blockers + ) + if not can_die_profitably or p.life > 25: + attackers.append(atk) + atk.tapped = True + + if not attackers: + return None + + if events is not None: + atk_names = [f"{a.name} ({a.pt})" for a in attackers] + events.append(f"Attacks {opp.name} with: {', '.join(atk_names)}") + + # Build and store CombatState + combat = CombatState( + defending_seat=opp_idx, + attackers={atk.id: opp_idx for atk in attackers}, + active=True, + ) + sim.combat = combat + return combat + + def assign_blockers( + self, sim: SimState, pi: int, combat: CombatState, + events: list | None = None, + ) -> None: + """Phase 2 of split combat: assign blockers into CombatState. + + Populates combat.blockers and combat.player_damage. + Does NOT apply any damage to players or creatures yet. + """ + opp_idx = combat.defending_seat + opp_blockers = [ + c for c in sim.get_battlefield(opp_idx) + if c.is_creature() and not c.tapped + ] + used_blockers: set[int] = set() + + for atk_id in combat.attackers: + atk = next((c for bf in sim.battlefields for c in bf if c.id == atk_id), None) + if atk is None: + continue + a_pow = atk.get_power() + has_flying = atk.has_keyword("flying") + valid_blockers = [ + b for b in opp_blockers + if b.id not in used_blockers + and (not has_flying or b.has_keyword("flying") or b.has_keyword("reach")) + ] + + blocker = None + if valid_blockers and (not atk.has_keyword("menace") or len(valid_blockers) >= 2): + if atk.has_keyword("menace") and len(valid_blockers) >= 2: + valid_blockers.sort(key=lambda b: -b.get_toughness()) + blocker = valid_blockers[0] + used_blockers.add(valid_blockers[1].id) + else: + blocker = next( + (b for b in valid_blockers if b.get_toughness() > a_pow), + None, + ) + opp = sim.players[opp_idx] + if blocker is None and opp.life <= a_pow * 2 and valid_blockers: + blocker = valid_blockers[0] + + if blocker: + used_blockers.add(blocker.id) + combat.blockers[atk_id] = [blocker.id] + if events is not None: + events.append(f"{atk.name} blocked by {blocker.name}") + else: + # Unblocked — full damage goes to player + combat.player_damage[atk_id] = a_pow + + def resolve_combat_damage( + self, sim: SimState, pi: int, combat: CombatState, + first_strike_only: bool = False, + events: list | None = None, + ) -> None: + """Phase 3 of split combat: apply damage from CombatState. + + When first_strike_only=True, only processes creatures with + first_strike or double_strike. When False, processes all + remaining (skipping first-strikers if already resolved). + """ + opp_idx = combat.defending_seat + p = sim.players[pi] + total_damage = 0 + attacker_damage: list[tuple[Card, int]] = [] + combat_details: list[str] = [] + + for atk_id, def_seat in list(combat.attackers.items()): + atk = next((c for bf in sim.battlefields for c in bf if c.id == atk_id), None) + if atk is None: + continue # removed by instant before damage + + is_fs = atk.has_keyword("first_strike") or atk.has_keyword("double_strike") + if first_strike_only and not is_fs: + continue + if not first_strike_only and is_fs and combat.first_strike_resolved: + if not atk.has_keyword("double_strike"): + continue # already dealt damage in FS step + + a_pow = atk.get_power() + a_tou = atk.get_toughness() + blocker_ids = combat.blockers.get(atk_id, []) + + if blocker_ids: + blocker = next((c for bf in sim.battlefields for c in bf if c.id == blocker_ids[0]), None) + if blocker is None: + # Blocker removed — attacker is still blocked but deals no combat damage to player + continue + b_pow = blocker.get_power() + blocker.damage_marked += a_pow + if blocker.damage_marked >= blocker.get_toughness() or atk.has_keyword("deathtouch"): + sim.remove_from_battlefield(blocker.id) + self._send_to_graveyard(sim, blocker, opp_idx) + if events is not None: + combat_details.append(f" {blocker.name} dies") + atk.damage_marked += b_pow + if atk.damage_marked >= a_tou or blocker.has_keyword("deathtouch"): + sim.remove_from_battlefield(atk.id) + self._send_to_graveyard(sim, atk, pi) + if events is not None: + combat_details.append(f" {atk.name} dies") + # Trample over + trample_over = 0 + if atk.has_keyword("trample") and a_pow > blocker.get_toughness(): + trample_over = a_pow - blocker.get_toughness() + attacker_damage.append((atk, trample_over)) + total_damage += trample_over + if atk.has_keyword("lifelink"): + p.life += min(a_pow, blocker.get_toughness()) + trample_over + else: + # Unblocked + atk_dmg = a_pow * 2 if atk.has_keyword("double_strike") else a_pow + if atk.has_keyword("lifelink"): + p.life += atk_dmg + attacker_damage.append((atk, atk_dmg)) + total_damage += atk_dmg + + # Route each attacker's damage through deal_damage() + for atk_card, dmg in attacker_damage: + if dmg > 0: + self.deal_damage( + sim, dmg, opp_idx, + source_card=atk_card, source_seat=pi, + is_combat=True, + ) + + if first_strike_only: + combat.first_strike_resolved = True + + if events is not None and total_damage > 0: + opp = sim.players[opp_idx] + total_cmd_damage = sum( + dmg for (atk_card, dmg) in attacker_damage + if atk_card.is_commander and dmg > 0 + ) + cmd_note = f" ({total_cmd_damage} cmdr)" if total_cmd_damage > 0 else "" + events.append( + f"Dealt {total_damage} combat damage{cmd_note} to {opp.name} (now {opp.life} life)" + ) + events.extend(combat_details) + + + def _build_result( self, sim: SimState, diff --git a/src/commander_ai_lab/sim/game_state.py b/src/commander_ai_lab/sim/game_state.py index 3d6c29b..48fd122 100644 --- a/src/commander_ai_lab/sim/game_state.py +++ b/src/commander_ai_lab/sim/game_state.py @@ -15,7 +15,7 @@ import json from dataclasses import dataclass, field from typing import Optional -from commander_ai_lab.sim.models import Card, Phase, Player, SimState +from commander_ai_lab.sim.models import Card, CombatState, Phase, Player, SimState # ── Mana Pool ──────────────────────────────────────────────── @@ -232,13 +232,65 @@ class CommanderGameState: # Bug 9 fix: stub get_legal_moves() and apply_move() so turn_manager # doesn't crash. These delegate to the rules engine once implemented. def get_legal_moves(self, seat: int) -> list[dict]: - """Return legal moves for a seat. Stub — returns pass-only.""" - return [{"id": 0, "category": "pass_priority", "description": "Pass"}] + """Return legal moves for a seat. + During DECLARE_BLOCKERS phase, emits block moves for defending + creatures against each attacker in sim_state.combat. + Otherwise returns pass-only (stub for remaining rules engine). + """ + moves: list[dict] = [{"id": 0, "category": "pass_priority", "description": "Pass"}] + combat = self.sim_state.combat + + # Emit block moves during declare_blockers phase + if ( + combat + and combat.active + and self.current_phase in (Phase.DECLARE_BLOCKERS, "declare_blockers") + and seat != self.active_player_seat + ): + move_id = 1000 + my_creatures = [ + c for c in self.sim_state.get_battlefield(seat) + if c.is_creature() and not c.tapped + ] + for atk_id in combat.attackers: + atk = next( + (c for bf in self.sim_state.battlefields for c in bf if c.id == atk_id), + None, + ) + if atk is None: + continue + for blocker in my_creatures: + moves.append({ + "id": move_id, + "category": "block", + "blocker_id": blocker.id, + "attacker_id": atk_id, + "description": f"Block {atk.name} with {blocker.name}", + }) + move_id += 1 + + return moves def apply_move(self, seat: int, move_id: int) -> None: - """Apply a chosen move. Stub — no-op until rules engine is wired.""" - pass + """Apply a chosen move. + Handles 'block' moves by updating sim_state.combat.blockers. + Other categories are no-op stubs until the rules engine is wired. + """ + # Find the move dict + all_moves = self.get_legal_moves(seat) + move = next((m for m in all_moves if m["id"] == move_id), None) + if move is None: + return + + if move.get("category") == "block": + combat = self.sim_state.combat + if combat and combat.active: + atk_id = move["attacker_id"] + blocker_id = move["blocker_id"] + if atk_id not in combat.blockers: + combat.blockers[atk_id] = [] + combat.blockers[atk_id].append(blocker_id) def living_players(self) -> list[CommanderPlayer]: return [p for p in self.commander_players if not p.eliminated] diff --git a/src/commander_ai_lab/sim/models.py b/src/commander_ai_lab/sim/models.py index 6b80614..e6954a5 100644 --- a/src/commander_ai_lab/sim/models.py +++ b/src/commander_ai_lab/sim/models.py @@ -48,6 +48,36 @@ PHASE_ORDER: tuple[Phase, ...] = tuple(Phase) SORCERY_PHASES: frozenset[Phase] = frozenset({Phase.MAIN1, Phase.MAIN2}) +# ── Combat State ─────────────────────────────────────────── + +@dataclass +class CombatState: + """Transient combat state shared across combat sub-phases. + + Created at BEGIN_COMBAT, cleared to None at END_COMBAT. + Allows priority windows between attacker declaration, blocker + declaration, and damage resolution (Issue #86 Item 1). + """ + + # Seat index of the defending player (multiplayer: chosen target) + defending_seat: int = -1 + + # attacker card_id -> defending seat + attackers: dict[int, int] = field(default_factory=dict) + + # attacker card_id -> list of blocker card_ids + blockers: dict[int, list[int]] = field(default_factory=dict) + + # Damage routed to the defending player per-attacker (for unblocked / trample) + player_damage: dict[int, int] = field(default_factory=dict) + + # Whether the first-strike damage sub-step has already resolved + first_strike_resolved: bool = False + + # Whether combat is currently active + active: bool = False + + @dataclass class Card: """A single card in the simulation.""" @@ -237,6 +267,9 @@ class SimState: current_phase: Phase = Phase.MAIN1 active_player_index: int = 0 + # Combat state (transient, set during combat phases) + combat: Optional[CombatState] = None + # ── Battlefield helpers ────────────────────────────────── def get_battlefield(self, seat: int) -> list[Card]: diff --git a/src/commander_ai_lab/sim/turn_manager.py b/src/commander_ai_lab/sim/turn_manager.py index 8e8689e..954f7b8 100644 --- a/src/commander_ai_lab/sim/turn_manager.py +++ b/src/commander_ai_lab/sim/turn_manager.py @@ -52,9 +52,8 @@ from collections import deque from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field from typing import Awaitable, Callable, Optional, Set - +from commander_ai_lab.sim.models import Phase, PHASE_ORDER, SORCERY_PHASES, CombatState from commander_ai_lab.sim.game_state import CommanderGameState, CommanderPlayer -from commander_ai_lab.sim.models import Phase, PHASE_ORDER, SORCERY_PHASES from commander_ai_lab.sim.ai_opponent import AIOpponent from commander_ai_lab.sim.threat_assessor import assess_threats, ThreatScore @@ -68,8 +67,6 @@ ACTION_PHASES = {p.value for p in SORCERY_PHASES} # Phases where instant-speed responses can happen RESPONSE_PHASES = { Phase.UPKEEP.value, - Phase.BEGIN_COMBAT.value, - Phase.END_COMBAT.value, Phase.END_STEP.value, } @@ -356,7 +353,13 @@ class CommanderTurnManager: await self._apnap_priority_window(active_seat, turn_num, phase) async def _phase_combat(self, active_seat: int, turn_num: int) -> None: - """Declare attackers phase.""" + """Full combat sequence with priority windows at each sub-phase (Issue #86).""" + sim = self.gs.sim_state + + # 1. Beginning of combat — priority window BEFORE attackers chosen + await self._apnap_priority_window(active_seat, turn_num, "begin_combat") + + # 2. Declare attackers legal_moves = self.get_legal_moves(active_seat) attack_moves = [m for m in legal_moves if m.get("category") == "attack"] if not attack_moves: @@ -385,9 +388,44 @@ class CommanderTurnManager: narration=narration, )) - # Defending players get priority to declare blockers + # 3. After-attackers priority window + await self._apnap_priority_window(active_seat, turn_num, "declare_attackers") + + # 4. Declare blockers — each defending player in APNAP order + for defender_seat in [s for s in range(len(self.gs.players)) + if s != active_seat + and not self.gs.players[s].eliminated]: + block_moves = [m for m in self.get_legal_moves(defender_seat) + if m.get("category") == "block"] + if block_moves: + block_id = await self._get_action(defender_seat, block_moves, turn_num) + if block_id is not None: + self.gs.apply_move(defender_seat, block_id) + + # 5. After-blockers priority window await self._apnap_priority_window(active_seat, turn_num, "declare_blockers") + # 6. First-strike damage sub-step (if applicable) + if self._has_first_strikers(): + # Resolve first-strike damage via engine split method + if sim.combat and sim.combat.active: + from commander_ai_lab.sim.engine import GameEngine + engine = GameEngine() + engine.resolve_combat_damage(sim, active_seat, sim.combat, first_strike_only=True) + await self._apnap_priority_window(active_seat, turn_num, "first_strike_damage") + + # 7. Normal combat damage + if sim.combat and sim.combat.active: + from commander_ai_lab.sim.engine import GameEngine + engine = GameEngine() + engine.resolve_combat_damage(sim, active_seat, sim.combat, first_strike_only=False) + + # 8. End of combat priority window + await self._apnap_priority_window(active_seat, turn_num, "end_combat") + + # 9. Clear combat state + sim.combat = None + async def _phase_cleanup(self, active_seat: int) -> None: """Discard to hand size (7), remove end-of-turn effects.""" player = self.gs.players[active_seat] @@ -400,6 +438,22 @@ class CommanderTurnManager: player.name, discarded.name, ) + def _has_first_strikers(self) -> bool: + """Check if any creature in active combat has first_strike or double_strike.""" + sim = self.gs.sim_state + combat = sim.combat + if not combat or not combat.active: + return False + all_combat_ids = ( + list(combat.attackers.keys()) + + [bid for blist in combat.blockers.values() for bid in blist] + ) + for card_id in all_combat_ids: + card = next((c for bf in sim.battlefields for c in bf if c.id == card_id), None) + if card and (card.has_keyword("first_strike") or card.has_keyword("double_strike")): + return True + return False + # ── Priority Passing (APNAP) ────────────────────────────────────────────── async def _apnap_priority_window( diff --git a/tests/test_combat_priority.py b/tests/test_combat_priority.py new file mode 100644 index 0000000..8c0bcf4 --- /dev/null +++ b/tests/test_combat_priority.py @@ -0,0 +1,160 @@ +"""Tests for combat priority checkpoints (Issue #86 Item 1). + +Validates CombatState lifecycle, split combat methods, +priority windows, first-strike ordering, and instant-speed +interaction during combat. +""" +import pytest +from commander_ai_lab.sim.models import ( + Card, CombatState, Phase, Player, PlayerStats, SimState, +) +from commander_ai_lab.sim.engine import GameEngine + + +# ── Helpers ────────────────────────────────────────────────────── + +def _make_creature(name, power, toughness, card_id, owner=0, keywords=None, is_commander=False): + """Build a minimal creature Card for testing.""" + return Card( + name=name, + type_line="Creature", + power=str(power), + toughness=str(toughness), + pt=f"{power}/{toughness}", + id=card_id, + owner_id=owner, + keywords=keywords or [], + is_commander=is_commander, + turn_played=-1, + ) + + +def _two_player_sim(p0_creatures, p1_creatures, p0_life=40, p1_life=40): + """Build a minimal 2-player SimState with creatures on the battlefield.""" + sim = SimState( + players=[ + Player(name="Attacker", life=p0_life, owner_id=0, stats=PlayerStats()), + Player(name="Defender", life=p1_life, owner_id=1, stats=PlayerStats()), + ], + battlefields=[list(p0_creatures), list(p1_creatures)], + turn=2, + ) + return sim + + +# ── Tests ─────────────────────────────────────────────────────── + +class TestCombatState: + """CombatState dataclass lifecycle.""" + + def test_combat_state_defaults(self): + cs = CombatState() + assert cs.defending_seat == -1 + assert cs.attackers == {} + assert cs.blockers == {} + assert cs.player_damage == {} + assert cs.first_strike_resolved is False + assert cs.active is False + + def test_combat_state_on_simstate(self): + sim = SimState() + assert sim.combat is None + sim.combat = CombatState(active=True) + assert sim.combat.active is True + sim.combat = None + assert sim.combat is None + + +class TestAssignAttackers: + """Engine.assign_attackers() populates CombatState.""" + + def test_assigns_and_taps(self): + atk = _make_creature("Bear", 3, 3, 100) + sim = _two_player_sim([atk], []) + engine = GameEngine() + combat = engine.assign_attackers(sim, 0) + assert combat is not None + assert combat.active is True + assert 100 in combat.attackers + assert atk.tapped is True + assert sim.combat is combat + + def test_no_attack_returns_none(self): + sim = _two_player_sim([], []) # no creatures + engine = GameEngine() + assert engine.assign_attackers(sim, 0) is None + assert sim.combat is None + + +class TestResolveCombatDamage: + """Engine.resolve_combat_damage() applies damage from CombatState.""" + + def test_unblocked_attacker_deals_damage(self): + atk = _make_creature("Bear", 3, 3, 100) + sim = _two_player_sim([atk], [], p1_life=20) + combat = CombatState(defending_seat=1, attackers={100: 1}, active=True) + sim.combat = combat + engine = GameEngine() + engine.resolve_combat_damage(sim, 0, combat) + assert sim.players[1].life == 17 # 20 - 3 + + def test_attacker_removed_before_damage_deals_nothing(self): + """Simulates instant-speed removal of attacker after declare attackers.""" + atk = _make_creature("Bear", 3, 3, 100) + sim = _two_player_sim([atk], [], p1_life=20) + combat = CombatState(defending_seat=1, attackers={100: 1}, active=True) + sim.combat = combat + # Simulate instant-speed removal: remove attacker before damage + sim.remove_from_battlefield(100) + engine = GameEngine() + engine.resolve_combat_damage(sim, 0, combat) + assert sim.players[1].life == 20 # no damage dealt + + def test_first_strike_only_skips_non_fs(self): + fs = _make_creature("Knight", 2, 2, 200, keywords=["first_strike"]) + normal = _make_creature("Bear", 3, 3, 201) + sim = _two_player_sim([fs, normal], [], p1_life=20) + combat = CombatState( + defending_seat=1, + attackers={200: 1, 201: 1}, + active=True, + ) + sim.combat = combat + engine = GameEngine() + # First-strike step: only the knight deals damage + engine.resolve_combat_damage(sim, 0, combat, first_strike_only=True) + assert sim.players[1].life == 18 # 20 - 2 (knight only) + assert combat.first_strike_resolved is True + # Normal damage step: bear deals damage, knight skipped + engine.resolve_combat_damage(sim, 0, combat, first_strike_only=False) + assert sim.players[1].life == 15 # 18 - 3 (bear only) + + def test_combat_state_cleared_after_end_combat(self): + """Verifies sim.combat is None after combat cleanup.""" + sim = SimState() + sim.combat = CombatState(active=True) + # Simulate end-of-combat cleanup + sim.combat = None + assert sim.combat is None + + def test_commander_damage_attributed(self): + """Commander attacker routes damage through commander_damage_by_card.""" + cmd = _make_creature("Atraxa", 4, 4, 300, is_commander=True) + sim = _two_player_sim([cmd], [], p1_life=40) + combat = CombatState(defending_seat=1, attackers={300: 1}, active=True) + sim.combat = combat + engine = GameEngine() + engine.resolve_combat_damage(sim, 0, combat) + assert sim.players[1].life == 36 # 40 - 4 + assert sim.players[1].commander_damage_by_card.get((0, "Atraxa"), 0) == 4 + + +class TestResponsePhasesCleanup: + """Verify BEGIN_COMBAT and END_COMBAT removed from RESPONSE_PHASES.""" + + def test_no_duplicate_apnap_begin_end_combat(self): + from commander_ai_lab.sim.turn_manager import RESPONSE_PHASES + assert "begin_combat" not in RESPONSE_PHASES + assert "end_combat" not in RESPONSE_PHASES + assert "upkeep" in RESPONSE_PHASES + assert "end_step" in RESPONSE_PHASES \ No newline at end of file