From 605ff774eda66a836fe7ece5062e5240b981f1dd Mon Sep 17 00:00:00 2001 From: KoalaTrapLord Date: Sat, 14 Mar 2026 19:35:50 -0400 Subject: [PATCH] Phase 3: Add turn_manager.py, threat_assessor.py, tests/test_phase3.py --- src/commander_ai_lab/sim/threat_assessor.py | 165 ++++++ src/commander_ai_lab/sim/turn_manager.py | 624 ++++++++++++++++++++ tests/test_phase3.py | 290 +++++++++ 3 files changed, 1079 insertions(+) create mode 100644 src/commander_ai_lab/sim/threat_assessor.py create mode 100644 src/commander_ai_lab/sim/turn_manager.py create mode 100644 tests/test_phase3.py diff --git a/src/commander_ai_lab/sim/threat_assessor.py b/src/commander_ai_lab/sim/threat_assessor.py new file mode 100644 index 0000000..12824ff --- /dev/null +++ b/src/commander_ai_lab/sim/threat_assessor.py @@ -0,0 +1,165 @@ +""" +Commander AI Lab — Threat Assessor (Phase 3) +============================================= +Scores every seat's threat level so the turn manager and AI opponents can +make targeting / blocking decisions. + +Threat score is a weighted sum of: + - Board power (total creature power) + - Board size (non-land permanents) + - Hand size (unknown cards = potential) + - Life total proximity to win (40 is baseline) + - Combo proximity (commanders in play, key enchantments, etc.) + +Scores are normalized to [0.0, 1.0]. Higher = more dangerous. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional + +from commander_ai_lab.sim.game_state import CommanderGameState + + +@dataclass +class ThreatScore: + seat: int + name: str + total: float # Normalized [0.0, 1.0] + board_power: float + board_size: float + hand_potential: float + life_threat: float # How much damage they could deal relative to opponents' life + combo_proximity: float + raw: dict = field(default_factory=dict) # Raw sub-scores before normalization + + def __repr__(self) -> str: + return ( + f"ThreatScore(seat={self.seat} name={self.name!r} " + f"total={self.total:.3f} board_power={self.board_power:.3f} " + f"life_threat={self.life_threat:.3f})" + ) + + +# Weight config — tune these without changing logic +_W_BOARD_POWER = 0.35 +_W_BOARD_SIZE = 0.20 +_W_HAND = 0.15 +_W_LIFE_THREAT = 0.20 +_W_COMBO = 0.10 + +# Combo-indicator keywords / oracle phrases +_COMBO_KEYWORDS = [ + "infinite", "you win the game", "extra turn", "search your library", + "whenever .* enters", "double", "each opponent loses", +] + + +def assess_threats( + game_state: CommanderGameState, + viewer_seat: int, +) -> list[ThreatScore]: + """ + Return a list of ThreatScore for every non-eliminated seat, ordered by + descending threat. The viewer's own seat is included but marked. + + Args: + game_state: Current CommanderGameState. + viewer_seat: The AI seat requesting the assessment (used for relative + life threat calculation). + + Returns: + List[ThreatScore] sorted by total descending. + """ + scores: list[ThreatScore] = [] + players = game_state.players + viewer = players[viewer_seat] if viewer_seat < len(players) else None + viewer_life = viewer.life if viewer else 40 + + for seat, player in enumerate(players): + if player.eliminated: + continue + + # --- Board power --- + total_power = 0 + board_size = 0 + combo_score = 0 + for c in player.battlefield: + if c.get("type") in ("creature", "Creature") or "creature" in c.get("type", "").lower(): + try: + pt = c.get("pt", "0/0") + pw = int(pt.split("/")[0]) if "/" in pt else 0 + except (ValueError, IndexError): + pw = 0 + total_power += pw + if not (c.get("type", "").lower() == "land"): + board_size += 1 + # Combo proximity: scan oracle text for combo indicators + oracle = (c.get("oracle", "") or "").lower() + for kw in _COMBO_KEYWORDS: + import re + if re.search(kw, oracle): + combo_score += 1 + break + + hand_size = len(player.hand) + + # Normalize sub-scores to [0, 1] + bp_norm = min(total_power / 20.0, 1.0) + bs_norm = min(board_size / 10.0, 1.0) + hand_norm = min(hand_size / 10.0, 1.0) + combo_norm = min(combo_score / 5.0, 1.0) + + # Life threat: how close are they to killing the viewer? + # If their total power >= viewer's life → maximum threat + life_threat_raw = total_power / max(viewer_life, 1) + lt_norm = min(life_threat_raw, 1.0) + + total = ( + _W_BOARD_POWER * bp_norm + + _W_BOARD_SIZE * bs_norm + + _W_HAND * hand_norm + + _W_LIFE_THREAT * lt_norm + + _W_COMBO * combo_norm + ) + + scores.append(ThreatScore( + seat=seat, + name=player.name, + total=round(total, 4), + board_power=round(bp_norm, 4), + board_size=round(bs_norm, 4), + hand_potential=round(hand_norm, 4), + life_threat=round(lt_norm, 4), + combo_proximity=round(combo_norm, 4), + raw={ + "total_power": total_power, + "board_non_land": board_size, + "hand_size": hand_size, + "combo_indicators": combo_score, + "life": player.life, + }, + )) + + scores.sort(key=lambda s: -s.total) + return scores + + +def top_threat( + game_state: CommanderGameState, + viewer_seat: int, + exclude_self: bool = True, +) -> Optional[ThreatScore]: + """ + Return the single highest-threat opponent. + + Args: + exclude_self: If True (default), skip viewer_seat. + """ + threats = assess_threats(game_state, viewer_seat) + for t in threats: + if exclude_self and t.seat == viewer_seat: + continue + return t + return None diff --git a/src/commander_ai_lab/sim/turn_manager.py b/src/commander_ai_lab/sim/turn_manager.py new file mode 100644 index 0000000..eb89993 --- /dev/null +++ b/src/commander_ai_lab/sim/turn_manager.py @@ -0,0 +1,624 @@ +""" +Commander AI Lab — Commander Turn Manager (Phase 3) +==================================================== +Asynchronous multi-player turn queue with full Commander structure. + +Features: + - Variable player count (2–4 seats), any mix of human / AIOpponent + - Human seats supported: decide_action() is skipped; caller injects the + move via human_play(move_id) instead + - Correct phase ordering: Untap → Upkeep → Draw → Main1 → Combat + → Main2 → End Step + - Priority-passing: each phase dispatches to priority_seat and cycles + through APNAP order until all players pass in sequence + - AI decisions run in a thread pool so the event loop stays responsive; + UI can display the "thinking" status via on_thinking callback + - Player elimination mid-game: eliminated players are removed from the + turn queue immediately after any damage is dealt + - Per-turn threat re-evaluation at the start of each AI main phase + - All game events surfaced through optional async callbacks + +Usage (AI-only game):: + + from commander_ai_lab.sim.turn_manager import CommanderTurnManager + from commander_ai_lab.sim.ai_opponent import create_four_player_ai_roster + from commander_ai_lab.sim.game_state import CommanderGameState + + gs = CommanderGameState(...) # build your initial state + ai_list = create_four_player_ai_roster() # Phase 2 factory + + tm = CommanderTurnManager(game_state=gs, ai_opponents=ai_list) + asyncio.run(tm.run_game()) + +Usage with a human player at seat 0:: + + tm = CommanderTurnManager( + game_state=gs, + ai_opponents=ai_list, + human_seats={0}, + on_action=my_ui_callback, + ) + # In your UI event handler: + await tm.human_play(move_id=chosen_id) +""" + +from __future__ import annotations + +import asyncio +import logging +import time +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.game_state import CommanderGameState, CommanderPlayer +from commander_ai_lab.sim.ai_opponent import AIOpponent +from commander_ai_lab.sim.threat_assessor import assess_threats, ThreatScore + +logger = logging.getLogger("turn_manager") + +# Commander turn phases in order +PHASES = [ + "untap", + "upkeep", + "draw", + "main1", + "begin_combat", + "declare_attackers", + "declare_blockers", + "combat_damage", + "end_combat", + "main2", + "end_step", + "cleanup", +] + +# Phases where a player can take an action (play land, cast spell, etc.) +ACTION_PHASES = {"main1", "main2"} +# Phases where instant-speed responses can happen +RESPONSE_PHASES = {"upkeep", "begin_combat", "end_combat", "end_step"} + + +@dataclass +class GameEvent: + """A single event emitted by the turn manager.""" + event_type: str # 'phase_change', 'action', 'narration', 'thinking', 'elimination', 'game_over' + seat: int + player_name: str + phase: str + turn: int + move_id: Optional[int] = None + move_description: str = "" + narration: str = "" + extra: dict = field(default_factory=dict) + + +@dataclass +class TurnManagerConfig: + """Tunable parameters for the turn manager.""" + max_turns: int = 40 + ai_decision_timeout: float = 30.0 # seconds before fallback + ai_narration_enabled: bool = True + ai_decision_delay: float = 0.0 # cosmetic pause (set > 0 for UI readability) + priority_pass_limit: int = 8 # max APNAP passes per phase before auto-advance + thread_pool_size: int = 3 # concurrent AI threads + + +class CommanderTurnManager: + """ + Async Commander turn manager. + + Drives the game loop, dispatching each seat's turn through the correct + Commander phases, running AI decisions off-thread, and surfacing all + events via optional callbacks. + + Parameters + ---------- + game_state : CommanderGameState + Mutable game state that this manager operates on. + ai_opponents : list[AIOpponent] + One AIOpponent per AI seat. Must have seat attribute matching + game_state.players index. Human seats are gaps in this list. + human_seats : set[int] + Seats controlled by human players. Turns for these seats block + until human_play() is called. + on_event : async callable, optional + Async callback invoked for every GameEvent (UI integration hook). + on_thinking : async callable, optional + Async callback invoked when AI starts / finishes thinking. + Signature: on_thinking(seat, is_thinking: bool) + config : TurnManagerConfig + """ + + def __init__( + self, + game_state: CommanderGameState, + ai_opponents: list[AIOpponent], + human_seats: Optional[Set[int]] = None, + on_event: Optional[Callable[[GameEvent], Awaitable[None]]] = None, + on_thinking: Optional[Callable[[int, bool], Awaitable[None]]] = None, + config: Optional[TurnManagerConfig] = None, + ) -> None: + self.gs = game_state + self.config = config or TurnManagerConfig() + self.human_seats: Set[int] = human_seats or set() + self.on_event = on_event + self.on_thinking = on_thinking + + # Build seat → AIOpponent map + self._ai_map: dict[int, AIOpponent] = {ai.seat: ai for ai in ai_opponents} + + # Human move injection: seat → asyncio.Future + self._human_move_futures: dict[int, asyncio.Future] = {} + + # Turn queue: double-ended queue of active seat indices + self._turn_queue: deque[int] = deque( + i for i in range(len(game_state.players)) + ) + + # Thread pool for AI inference (keeps event loop unblocked) + self._executor = ThreadPoolExecutor( + max_workers=self.config.thread_pool_size, + thread_name_prefix="ai_worker", + ) + + # Stats + self._total_actions: int = 0 + self._fallback_count: int = 0 + self.game_over: bool = False + self.winner_seat: Optional[int] = None + + # Latest threat scores per seat (refreshed each main phase) + self._threat_cache: dict[int, list[ThreatScore]] = {} + + # ── Public API ──────────────────────────────────────────────────────────── + + async def run_game(self) -> Optional[int]: + """ + Run the full game loop until one player wins or max_turns is reached. + + Returns the winner's seat index, or None if the game timed out. + """ + logger.info("Game started. Players: %s", + [p.name for p in self.gs.players]) + + for turn_num in range(1, self.config.max_turns + 1): + self.gs.turn = turn_num + + if self.game_over: + break + + # Snapshot the active seats at the start of each full round + active_seats = list(self._turn_queue) + for seat in active_seats: + if self.gs.players[seat].eliminated: + continue + self.gs.active_player_seat = seat + await self._run_player_turn(seat, turn_num) + + # Check for eliminations after each player's turn + await self._check_eliminations() + if self.game_over: + break + + if self.game_over: + break + + if not self.game_over: + # Timeout — winner is highest life total + alive = [ + (p.life, i) + for i, p in enumerate(self.gs.players) + if not p.eliminated + ] + if alive: + _, self.winner_seat = max(alive) + self.game_over = True + await self._emit(GameEvent( + event_type="game_over", + seat=self.winner_seat or 0, + player_name=self.gs.players[self.winner_seat or 0].name, + phase="cleanup", + turn=self.gs.turn, + extra={"reason": "timeout", "winner": self.winner_seat}, + )) + + logger.info("Game over. Winner seat: %s", self.winner_seat) + self._executor.shutdown(wait=False) + return self.winner_seat + + async def human_play(self, move_id: int) -> None: + """ + Inject a move from a human player. + + Call this from your UI event handler when the human selects an action. + The turn manager is blocking on an asyncio.Future for the active + human seat — this resolves it. + """ + # Find the currently-waiting human seat + active = self.gs.active_player_seat + if active in self._human_move_futures: + fut = self._human_move_futures[active] + if not fut.done(): + fut.get_event_loop().call_soon_threadsafe(fut.set_result, move_id) + else: + logger.warning("human_play called but future already resolved for seat %d", active) + else: + logger.warning("human_play called but no future pending for seat %d", active) + + def get_legal_moves(self, seat: int) -> list[dict]: + """ + Return the current legal moves for a seat. + Delegates to the rules engine on game_state. + """ + return self.gs.get_legal_moves(seat) + + def get_threat_scores(self, viewer_seat: int) -> list[ThreatScore]: + """Return the latest cached threat scores from viewer_seat's perspective.""" + return self._threat_cache.get(viewer_seat, []) + + def get_stats(self) -> dict: + """Return turn manager statistics.""" + return { + "turn": self.gs.turn, + "total_actions": self._total_actions, + "fallback_count": self._fallback_count, + "game_over": self.game_over, + "winner_seat": self.winner_seat, + "active_seats": list(self._turn_queue), + } + + # ── Turn Phases ─────────────────────────────────────────────────────────── + + async def _run_player_turn(self, seat: int, turn_num: int) -> None: + """Drive all phases of one player's turn.""" + player = self.gs.players[seat] + logger.debug("Turn %d — %s's turn begins", turn_num, player.name) + + for phase in PHASES: + if self.game_over: + return + + self.gs.current_phase = phase + self.gs.priority_seat = seat + + await self._emit(GameEvent( + event_type="phase_change", + seat=seat, + player_name=player.name, + phase=phase, + turn=turn_num, + )) + + if phase == "untap": + await self._phase_untap(seat) + elif phase == "draw": + await self._phase_draw(seat, turn_num) + elif phase in ACTION_PHASES: + await self._phase_main(seat, turn_num, phase) + elif phase == "declare_attackers": + await self._phase_combat(seat, turn_num) + elif phase == "cleanup": + await self._phase_cleanup(seat) + elif phase in RESPONSE_PHASES: + # APNAP priority window — AI opponents may respond + await self._apnap_priority_window(seat, turn_num, phase) + + # ── Individual Phases ───────────────────────────────────────────────────── + + async def _phase_untap(self, active_seat: int) -> None: + """Untap all permanents for active player. No priority.""" + player = self.gs.players[active_seat] + for card in player.battlefield: + card["tapped"] = False + logger.debug(" [untap] %s untapped all permanents", player.name) + + async def _phase_draw(self, active_seat: int, turn_num: int) -> None: + """Active player draws one card (skip on turn 1 seat 0 by default).""" + player = self.gs.players[active_seat] + if turn_num == 1 and active_seat == 0: + return # Traditional no-draw-on-first-turn rule + if player.library: + drawn = player.library.pop() + player.hand.append(drawn) + logger.debug(" [draw] %s drew %s", player.name, drawn.get("name", "?")) + + async def _phase_main(self, active_seat: int, turn_num: int, phase: str) -> None: + """ + Main phase: active player takes one action, then APNAP window. + Threat scores re-evaluated at the start of main1. + """ + if phase == "main1": + self._refresh_threat_scores(active_seat) + + legal_moves = self.get_legal_moves(active_seat) + if not legal_moves: + return + + move_id = await self._get_action(active_seat, legal_moves, turn_num) + if move_id is not None: + desc = self._move_desc(move_id, legal_moves) + self.gs.apply_move(active_seat, move_id) + self._total_actions += 1 + + narration = "" + if self.config.ai_narration_enabled and active_seat in self._ai_map: + ai = self._ai_map[active_seat] + narration = ai.narrate_play(move_id, legal_moves, self.gs) + + await self._emit(GameEvent( + event_type="action", + seat=active_seat, + player_name=self.gs.players[active_seat].name, + phase=phase, + turn=turn_num, + move_id=move_id, + move_description=desc, + narration=narration, + )) + + # APNAP: other players respond after active player acts + 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.""" + 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: + return + + move_id = await self._get_action(active_seat, attack_moves, turn_num) + if move_id is not None: + desc = self._move_desc(move_id, attack_moves) + self.gs.apply_move(active_seat, move_id) + self._total_actions += 1 + + narration = "" + if self.config.ai_narration_enabled and active_seat in self._ai_map: + narration = self._ai_map[active_seat].narrate_play( + move_id, attack_moves, self.gs + ) + + await self._emit(GameEvent( + event_type="action", + seat=active_seat, + player_name=self.gs.players[active_seat].name, + phase="declare_attackers", + turn=turn_num, + move_id=move_id, + move_description=desc, + narration=narration, + )) + + # Defending players get priority to declare blockers + await self._apnap_priority_window(active_seat, turn_num, "declare_blockers") + + 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] + max_hand = 7 + while len(player.hand) > max_hand: + discarded = player.hand.pop() # Simplified: discard last + player.graveyard.append(discarded) + logger.debug( + " [cleanup] %s discarded %s", + player.name, discarded.get("name", "?"), + ) + + # ── Priority Passing (APNAP) ────────────────────────────────────────────── + + async def _apnap_priority_window( + self, + active_seat: int, + turn_num: int, + phase: str, + ) -> None: + """ + APNAP priority window: Active Player, Non-Active Players in seat order. + + Cycles until all players pass consecutively, or pass_limit is reached. + AI players may cast instants / activate abilities. + Human players are skipped (assumed to respond via separate UI flow). + """ + n = len(self.gs.players) + # Build APNAP order: active first, then the rest in seat order + apnap_order = [active_seat] + [ + i for i in range(n) + if i != active_seat and not self.gs.players[i].eliminated + ] + + consecutive_passes = 0 + passes_needed = len(apnap_order) + iterations = 0 + max_iter = passes_needed * self.config.priority_pass_limit + + while consecutive_passes < passes_needed and iterations < max_iter: + for seat in apnap_order: + if self.gs.players[seat].eliminated: + consecutive_passes += 1 + continue + + # Human seats: auto-pass in APNAP window (they act in main phase) + if seat in self.human_seats: + consecutive_passes += 1 + continue + + # AI instant-speed response + if seat in self._ai_map: + legal = [ + m for m in self.get_legal_moves(seat) + if m.get("category") in ("instant", "activate_ability", "trigger") + ] + if legal: + move_id = await self._get_action(seat, legal, turn_num) + if move_id is not None: + self.gs.apply_move(seat, move_id) + self._total_actions += 1 + consecutive_passes = 0 + await self._emit(GameEvent( + event_type="action", + seat=seat, + player_name=self.gs.players[seat].name, + phase=phase, + turn=turn_num, + move_id=move_id, + move_description=self._move_desc(move_id, legal), + extra={"apnap": True}, + )) + continue + + consecutive_passes += 1 + iterations += 1 + + if iterations >= max_iter: + logger.debug("APNAP pass limit reached in phase %s", phase) + break + + # ── AI Decision (off-thread) ────────────────────────────────────────────── + + async def _get_action( + self, + seat: int, + legal_moves: list[dict], + turn_num: int, + ) -> Optional[int]: + """ + Dispatch a decision request to the correct handler: + - Human seat: await the injected future + - AI seat: run decide_action() in thread pool + """ + if seat in self.human_seats: + return await self._await_human_move(seat) + + if seat in self._ai_map: + return await self._run_ai_decision(seat, legal_moves) + + # Headless seat (no AI assigned) — pass + return None + + async def _await_human_move(self, seat: int) -> Optional[int]: + """Block until human_play() injects a move for this seat.""" + loop = asyncio.get_event_loop() + fut: asyncio.Future = loop.create_future() + self._human_move_futures[seat] = fut + try: + move_id = await asyncio.wait_for(fut, timeout=300.0) # 5-min timeout + except asyncio.TimeoutError: + logger.warning("Human seat %d timed out — passing", seat) + move_id = None + finally: + self._human_move_futures.pop(seat, None) + return move_id + + async def _run_ai_decision( + self, + seat: int, + legal_moves: list[dict], + ) -> Optional[int]: + """ + Run AIOpponent.decide_action() in a thread pool so the event loop + stays responsive during LLM inference. + """ + ai = self._ai_map[seat] + + # Signal UI: AI is thinking + if self.on_thinking: + await self.on_thinking(seat, True) + + loop = asyncio.get_event_loop() + t_start = time.monotonic() + + try: + move_id = await asyncio.wait_for( + loop.run_in_executor( + self._executor, + ai.decide_action, + self.gs, + legal_moves, + ), + timeout=self.config.ai_decision_timeout, + ) + except asyncio.TimeoutError: + logger.warning( + "[seat %d %s] AI decision timed out after %.1fs — using fallback", + seat, ai.name, self.config.ai_decision_timeout, + ) + move_id = ai._heuristic_move(self.gs, legal_moves) + self._fallback_count += 1 + finally: + # Signal UI: AI done thinking + if self.on_thinking: + await self.on_thinking(seat, False) + + elapsed = time.monotonic() - t_start + logger.debug("[seat %d %s] decided move=%s in %.2fs", seat, ai.name, move_id, elapsed) + + # Cosmetic delay so humans can follow the AI's play + if self.config.ai_decision_delay > 0: + await asyncio.sleep(self.config.ai_decision_delay) + + return move_id + + # ── Eliminations ───────────────────────────────────────────────────────── + + async def _check_eliminations( + self, + ) -> None: + """Detect newly eliminated players and remove from turn queue.""" + for seat, player in enumerate(self.gs.players): + if player.eliminated and seat in self._turn_queue: + self._turn_queue.remove(seat) + logger.info("%s (seat %d) eliminated", player.name, seat) + await self._emit(GameEvent( + event_type="elimination", + seat=seat, + player_name=player.name, + phase=self.gs.current_phase, + turn=self.gs.turn, + extra={"remaining": list(self._turn_queue)}, + )) + + alive = [i for i in self._turn_queue if not self.gs.players[i].eliminated] + if len(alive) <= 1: + self.game_over = True + self.winner_seat = alive[0] if alive else None + if self.winner_seat is not None: + await self._emit(GameEvent( + event_type="game_over", + seat=self.winner_seat, + player_name=self.gs.players[self.winner_seat].name, + phase=self.gs.current_phase, + turn=self.gs.turn, + extra={"winner": self.winner_seat, "reason": "elimination"}, + )) + + # ── Threat Re-evaluation ────────────────────────────────────────────────── + + def _refresh_threat_scores(self, active_seat: int) -> None: + """Recompute threat scores for all non-eliminated seats.""" + for seat in range(len(self.gs.players)): + if not self.gs.players[seat].eliminated: + self._threat_cache[seat] = assess_threats(self.gs, viewer_seat=seat) + logger.debug( + "[seat %d] Threat scores refreshed: %s", + active_seat, + {s: round(ts[0].total, 3) if ts else 0 for s, ts in self._threat_cache.items()}, + ) + + # ── Helpers ─────────────────────────────────────────────────────────────── + + async def _emit(self, event: GameEvent) -> None: + """Fire the on_event callback if registered.""" + if self.on_event: + try: + await self.on_event(event) + except Exception as exc: + logger.warning("on_event callback raised: %s", exc) + + @staticmethod + def _move_desc(move_id: Optional[int], moves: list[dict]) -> str: + for m in moves: + if m["id"] == move_id: + return m.get("description", f"Move {move_id}") + return f"Move {move_id}" diff --git a/tests/test_phase3.py b/tests/test_phase3.py new file mode 100644 index 0000000..9250438 --- /dev/null +++ b/tests/test_phase3.py @@ -0,0 +1,290 @@ +""" +Phase 3 Unit Tests — Turn Manager, Threat Assessor +=================================================== +Run with: pytest tests/test_phase3.py -v + +All tests run fully offline (no Ollama required). The turn manager is +tested using a mock game state with stub legal_moves / apply_move, +avoiding any dependency on the live rules engine. +""" + +from __future__ import annotations + +import asyncio +from dataclasses import dataclass, field +from typing import Optional + +import pytest + +from commander_ai_lab.sim.threat_assessor import assess_threats, top_threat, ThreatScore +from commander_ai_lab.sim.turn_manager import ( + CommanderTurnManager, + TurnManagerConfig, + GameEvent, + PHASES, + ACTION_PHASES, +) +from commander_ai_lab.sim.ai_opponent import AIOpponent +from commander_ai_lab.sim.personality_prompts import AGGRO_TIMMY, CONTROL_SPIKE + + +# ── Stub Game State ──────────────────────────────────────────────────────── + +@dataclass +class _StubPlayer: + name: str + life: int = 40 + eliminated: bool = False + hand: list = field(default_factory=list) + library: list = field(default_factory=list) + graveyard: list = field(default_factory=list) + battlefield: list = field(default_factory=list) + + +class _StubGameState: + """Minimal CommanderGameState-compatible stub.""" + + def __init__(self, num_players: int = 4): + self.players = [_StubPlayer(name=f"P{i}", life=40) for i in range(num_players)] + self.turn = 0 + self.current_phase = "main1" + self.active_player_seat = 0 + self.priority_seat = 0 + self._move_counter = 0 + + def get_legal_moves(self, seat: int) -> list[dict]: + """Always return one pass move per seat.""" + return [ + {"id": 1, "category": "pass_priority", "description": "Pass"}, + {"id": 2, "category": "play_land", "description": "Play Forest"}, + ] + + def apply_move(self, seat: int, move_id: int) -> None: + self._move_counter += 1 + + +def _stub_gs(num_players: int = 4) -> _StubGameState: + return _StubGameState(num_players=num_players) + + +def _offline_ai(seat: int, personality=None) -> AIOpponent: + import tempfile + ai = AIOpponent( + name=f"AI_{seat}", + seat=seat, + personality=personality or AGGRO_TIMMY, + log_dir=tempfile.mkdtemp(), + ) + ai.brain._connected = False + return ai + + +def _make_tm( + num_players: int = 4, + max_turns: int = 2, + human_seats: set | None = None, +) -> CommanderTurnManager: + gs = _stub_gs(num_players) + ai_list = [_offline_ai(i) for i in range(num_players)] + cfg = TurnManagerConfig(max_turns=max_turns, ai_decision_delay=0.0) + return CommanderTurnManager( + game_state=gs, + ai_opponents=ai_list, + human_seats=human_seats or set(), + config=cfg, + ) + + +# ── ThreatAssessor Tests ──────────────────────────────────────────────────── + +class TestThreatAssessor: + def _gs_with_creatures(self) -> _StubGameState: + gs = _stub_gs(4) + # Give seat 0 a big creature + gs.players[0].battlefield = [ + {"name": "Dragon", "type": "creature", "pt": "6/6", "oracle": ""}, + {"name": "Forest", "type": "land", "pt": "", "oracle": ""}, + ] + gs.players[1].hand = [{"name": f"Card{i}"} for i in range(7)] + return gs + + def test_returns_score_per_non_eliminated_player(self): + gs = _stub_gs(4) + scores = assess_threats(gs, viewer_seat=0) + assert len(scores) == 4 + + def test_eliminated_players_excluded(self): + gs = _stub_gs(4) + gs.players[2].eliminated = True + scores = assess_threats(gs, viewer_seat=0) + assert len(scores) == 3 + assert all(s.seat != 2 for s in scores) + + def test_high_power_creature_raises_threat(self): + gs = self._gs_with_creatures() + scores = assess_threats(gs, viewer_seat=1) + seat0_score = next(s for s in scores if s.seat == 0) + seat2_score = next(s for s in scores if s.seat == 2) + assert seat0_score.total > seat2_score.total + + def test_scores_normalized_0_to_1(self): + gs = self._gs_with_creatures() + for score in assess_threats(gs, viewer_seat=0): + assert 0.0 <= score.total <= 1.0 + + def test_sorted_descending(self): + gs = self._gs_with_creatures() + scores = assess_threats(gs, viewer_seat=1) + totals = [s.total for s in scores] + assert totals == sorted(totals, reverse=True) + + def test_top_threat_excludes_self(self): + gs = self._gs_with_creatures() + threat = top_threat(gs, viewer_seat=0, exclude_self=True) + assert threat is not None + assert threat.seat != 0 + + def test_top_threat_includes_self_when_asked(self): + gs = self._gs_with_creatures() + threat = top_threat(gs, viewer_seat=0, exclude_self=False) + # seat 0 has biggest creature — should be top threat + assert threat is not None + assert threat.seat == 0 + + def test_threat_score_has_raw_dict(self): + gs = _stub_gs() + for score in assess_threats(gs, viewer_seat=0): + assert "total_power" in score.raw + assert "life" in score.raw + + +# ── TurnManager Construction ──────────────────────────────────────────────── + +class TestTurnManagerConstruction: + def test_ai_map_built_correctly(self): + tm = _make_tm(num_players=4) + assert len(tm._ai_map) == 4 + assert all(seat in tm._ai_map for seat in range(4)) + + def test_turn_queue_initialized(self): + tm = _make_tm(num_players=4) + assert list(tm._turn_queue) == [0, 1, 2, 3] + + def test_human_seats_excluded_from_ai_map(self): + gs = _stub_gs(4) + ai_list = [_offline_ai(i) for i in range(1, 4)] # seats 1-3 only + cfg = TurnManagerConfig(max_turns=1, ai_decision_delay=0.0) + tm = CommanderTurnManager( + game_state=gs, + ai_opponents=ai_list, + human_seats={0}, + config=cfg, + ) + assert 0 not in tm._ai_map + assert 1 in tm._ai_map + + def test_two_player_game(self): + tm = _make_tm(num_players=2) + assert list(tm._turn_queue) == [0, 1] + + +# ── TurnManager async run_game ────────────────────────────────────────────── + +class TestRunGame: + def test_game_completes_within_max_turns(self): + tm = _make_tm(num_players=4, max_turns=2) + winner = asyncio.run(tm.run_game()) + # Stub has no elimination logic → game times out, winner by life + assert tm.game_over is True + + def test_elimination_removes_from_queue(self): + tm = _make_tm(num_players=4, max_turns=1) + # Manually eliminate seat 2 before running + tm.gs.players[2].eliminated = True + asyncio.run(tm.run_game()) + assert 2 not in tm._turn_queue + + def test_events_fired(self): + events: list[GameEvent] = [] + + async def collect(ev: GameEvent): + events.append(ev) + + gs = _stub_gs(2) + ai_list = [_offline_ai(0), _offline_ai(1)] + cfg = TurnManagerConfig(max_turns=1, ai_decision_delay=0.0) + tm = CommanderTurnManager( + game_state=gs, + ai_opponents=ai_list, + config=cfg, + on_event=collect, + ) + asyncio.run(tm.run_game()) + types = {e.event_type for e in events} + assert "phase_change" in types + + def test_thinking_callbacks_fired(self): + thinking_log: list[tuple] = [] + + async def on_think(seat: int, is_thinking: bool): + thinking_log.append((seat, is_thinking)) + + gs = _stub_gs(2) + ai_list = [_offline_ai(0), _offline_ai(1)] + cfg = TurnManagerConfig(max_turns=1, ai_decision_delay=0.0) + tm = CommanderTurnManager( + game_state=gs, ai_opponents=ai_list, config=cfg, on_thinking=on_think + ) + asyncio.run(tm.run_game()) + # Each AI turn should emit (seat, True) and (seat, False) + assert len(thinking_log) > 0 + starts = [(s, t) for s, t in thinking_log if t] + ends = [(s, t) for s, t in thinking_log if not t] + assert len(starts) == len(ends) + + def test_get_stats_structure(self): + tm = _make_tm(num_players=2, max_turns=1) + asyncio.run(tm.run_game()) + stats = tm.get_stats() + assert "turn" in stats + assert "total_actions" in stats + assert "game_over" in stats + + +# ── APNAP Priority ────────────────────────────────────────────────────────── + +class TestAPNAP: + def test_phases_constant_has_all_required_phases(self): + for phase in ("untap", "draw", "main1", "main2", + "declare_attackers", "cleanup"): + assert phase in PHASES + + def test_action_phases_subset_of_phases(self): + assert ACTION_PHASES.issubset(set(PHASES)) + + def test_apnap_does_not_deadlock(self): + """APNAP window should complete even if all AI pass immediately.""" + tm = _make_tm(num_players=4, max_turns=1) + async def run(): + await tm._apnap_priority_window( + active_seat=0, turn_num=1, phase="main1" + ) + asyncio.run(run()) # Should not hang + + +# ── Threat Score Refresh ──────────────────────────────────────────────────── + +class TestThreatRefresh: + def test_threat_cache_populated_after_main1(self): + tm = _make_tm(num_players=4, max_turns=1) + asyncio.run(tm.run_game()) + # After at least one main1 phase, cache should have entries + assert len(tm._threat_cache) > 0 + + def test_threat_scores_per_seat_are_lists(self): + tm = _make_tm(num_players=4, max_turns=1) + asyncio.run(tm.run_game()) + for seat, scores in tm._threat_cache.items(): + assert isinstance(scores, list) + for s in scores: + assert isinstance(s, ThreatScore)