Surround Morris is a 2-player territorial strategy game on a Nine Men's Morris board. Unlike the original game which uses "mills" (three in a row), this variant captures pieces by spatial surrounding using numerical superiority. ## Game Overview The game is played on a 24-spot board consisting of three concentric squares connected at midpoints. Each player has 7 pieces (Black 'B' vs White 'W'). The goal is to eliminate all opponent pieces from the board. ## Board Layout ``` 0-----------1-----------2 | | | | 3-------4-------5 | | | | | | | | 6---7---8 | | | | | | | | 9--10--11 12--13--14 | | | | | | | | 15--16--17 | | | | | | | | 18------19------20 | | | | 21----------22----------23 ``` Spots are numbered 0-23. Lines between spots indicate adjacency (legal movement paths). ## Adjacency Graph ```python ADJACENCY = { 0: [1, 9], 1: [0, 2, 4], 2: [1, 14], 3: [4, 10], 4: [1, 3, 5, 7], 5: [4, 13], 6: [7, 11], 7: [4, 6, 8], 8: [7, 12], 9: [0, 10, 21], 10: [3, 9, 11, 18], 11: [6, 10, 15], 12: [8, 13, 17], 13: [5, 12, 14, 20], 14: [2, 13, 23], 15: [11, 16], 16: [15, 17, 19], 17: [12, 16], 18: [10, 19], 19: [16, 18, 20, 22], 20: [13, 19], 21: [9, 22], 22: [19, 21, 23], 23: [14, 22], } ``` ## The Capture Rule: "Overwhelm" A piece is captured and removed when it satisfies BOTH conditions: 1. It has **zero empty adjacent spots** (completely blocked) 2. The number of **adjacent opponents is strictly greater** than the number of **adjacent friendlies** ``` IF (empty_neighbors == 0) AND (opponent_neighbors > friendly_neighbors) -> CAPTURED ``` ### Critical Capture Logic: "Suicide First, Self-Harm Priority" Captures are processed in a specific order after every move (Placement or Movement): 1. **Active Piece Suicide Check:** The engine checks the piece you just played. * If it meets capture criteria -> **It is removed immediately.** * **Consequence:** It dies *before* it can help capture any neighbors. It captures nothing. The turn ends. 2. **Universal Capture Sweep (Self-Harm Priority):** * Only if the active piece *survived* step 1, the engine scans the board. * **Step 2a:** All **friendly pieces** (same color as mover) that are now overwhelmed are removed first. * **Step 2b:** The engine **re-checks** all **enemy pieces**. Some enemy pieces that were overwhelmed before step 2a may now have empty neighbors (from removed friendly pieces) and survive. * This means your own pieces always die before enemies in a mutual capture scenario. You cannot kill an enemy by blocking them if doing so also blocks your own piece — your piece dies first, potentially freeing the enemy. ## Gameplay Phases ### Phase 1: Placement 1. Board starts empty. Players alternate placing one piece at a time onto any vacant spot. 2. Black ('B') always places first. 3. **Suicide is LEGAL:** You are allowed to place a piece into a spot where it will die immediately. However, due to the "Suicide First" rule, this is usually a wasted move (you die, enemy survives). 4. **Elimination during placement:** If a player has 0 pieces on board AND 0 pieces in hand, they lose immediately. 5. Phase ends when both players have placed all 7 pieces (14 total placements). Note that some of these pieces may have been captured during the placement phase. ### Phase 2: Movement 1. Players alternate sliding one piece along a line to an adjacent empty spot. 2. **No flying:** Even with few pieces, you must slide to adjacent spots only. 3. **Universal Capture:** Moving a piece can trigger the death of **any** piece on the board. * Be careful not to block your own pieces ("Friendly Fire"). * In mutual capture scenarios, your pieces die first (Self-Harm Priority). 4. **Mate:** If a player has **no legal moves** (all pieces are blocked), the game ends immediately. The stuck player **LOSES**. ## Game End Conditions The game can end during **either phase** for elimination, and during the **movement phase** for all other conditions: 1. **Elimination (both phases):** A player has **0 pieces on board** (and during placement, also **0 pieces in hand**) -> Opponent wins. If a move harms both sides, the mover is checked first (self-harm priority), so the mover loses. 2. **Mate:** A player has **no legal moves** -> The stuck player **LOSES**. The other player wins. 3. **Turn Limit (movement only):** **200 movement turns** have elapsed -> Draw. Move count starts in the movement phase. 4. **Repetition (movement only):** The exact same board position (pieces + active player) occurs **3 times**. * Repetition is checked **before** each move. History is recorded at the start of each turn. * **Result:** The game ends immediately in a **DRAW**. ## Board Geometry & Capture Thresholds **CRITICAL:** The thresholds below apply *only* if the piece has **0 empty neighbors**. If `empty_neighbors > 0`, the piece is **SAFE**, regardless of the opponent count. | Position Type | Total Neighbors | To Capture (With 0 Empty & 0 Friendlies) | To Capture (With 0 Empty & 1 Friendly) | |---------------|:---------:|:-------------------------:|:-----------------------:| | Corner | 2 | 2 opponents | Impossible (1 vs 1 tie) | | T-junction | 3 | 3 opponents | 2 opponents (2 > 1) | | Crossroad | 4 | 4 opponents | 3 opponents (3 > 1) | ## Game Engine Reference The game engine provides a `SurroundMorrisGame` class with this state: ```python class SurroundMorrisGame: board: list[str] # 24 elements: '', 'B', or 'W' phase: str # 'placement' or 'movement' pieces_in_hand: dict # {'B': int, 'W': int} pieces_on_board: dict # {'B': int, 'W': int} current_player: str # 'B' or 'W' move_count: int # movement turns elapsed history: list[tuple] # list of (board_tuple, current_player) for repetition checking def get_legal_placements(color) -> list[int] # All empty spots (Suicide is legal) def get_legal_movements(color) -> list[tuple[int, int]] # All (from_spot, to_spot) pairs. Returns empty list if mated. def is_captured(spot, board) -> bool # Check capture condition for piece at spot ``` ## Error Codes Reference ### Placement Errors | Code | Meaning | |------|---------| | `INVALID_SPOT_OOB` | Spot not in [0, 23] | | `INVALID_SPOT_OCCUPIED` | Spot already has a piece | | `INVALID_WRONG_PHASE` | Not in placement phase | | `INVALID_OUTPUT` | Return value was not an integer | ### Movement Errors | Code | Meaning | |------|---------| | `INVALID_SPOT_OOB` | Source spot not in [0, 23] | | `INVALID_DEST_OOB` | Destination spot not in [0, 23] | | `INVALID_NOT_YOUR_PIECE` | Source spot doesn't have your piece | | `INVALID_DEST_OCCUPIED` | Destination spot is not empty | | `INVALID_NOT_ADJACENT` | Source and destination are not adjacent | | `INVALID_WRONG_PHASE` | Not in movement phase | | `INVALID_OUTPUT` | Return value was not a (from, to) tuple | ## Error Handling There is no retry mechanism. On any failure (crash, timeout, or invalid move), a random valid move is made immediately on your behalf. You will not receive feedback or a second chance for that turn. ## Implementation Task Implement a `SurroundMorrisAgent` class that plays the game. ## SurroundMorrisAgent Interface ```python import random class SurroundMorrisAgent: """ Your agent for Surround Morris. """ def __init__(self, name: str, color: str): """ Initialize your agent. Parameters: ----------- name : str Your agent name (e.g., "Agent-1"). color : str Your piece color: 'B' (Black) or 'W' (White). """ self.name = name self.color = color def make_move(self, state: dict, feedback: dict | None = None): """ Called each turn. Return your move based on the current game state. Parameters: ----------- state : dict { "board": list[str], # 24-element list. Each element is '', 'B', or 'W'. # Index corresponds to spot number on the board. "phase": str, # 'placement' or 'movement' "your_color": str, # Your color: 'B' or 'W' "opponent_color": str, # Opponent's color "pieces_in_hand": dict, # {'B': int, 'W': int} - pieces not yet placed "pieces_on_board": dict, # {'B': int, 'W': int} - pieces currently on the board "move_count": int, # Number of movement turns elapsed (0 during placement) "history": list[tuple], # List of (board_tuple, current_player) states seen so far. # Use this to detect and avoid 3-fold repetition. # Reset when transitioning from placement to movement phase. } feedback : dict or None Always None. Kept for interface compatibility. Returns: -------- During placement phase: int - the spot number (0-23) to place your piece During movement phase: tuple[int, int] - (from_spot, to_spot) to slide your piece """ board = state["board"] phase = state["phase"] color = state["your_color"] opp = state["opponent_color"] if phase == "placement": # Find empty spots and pick one randomly empty = [i for i in range(24) if board[i] == ''] return random.choice(empty) if empty else 0 else: # Find legal moves: from your piece to adjacent empty spot moves = [] for spot in range(24): if board[spot] != color: continue for neighbor in ADJACENCY[spot]: if board[neighbor] == '': moves.append((spot, neighbor)) return random.choice(moves) if moves else (0, 1) ``` ### Agent Coding Requirements - **No Internal Imports**: Do not import any game engine files, match runners, or project-specific modules. Use only standard library imports. - **Isolation**: Your agent must be completely self-contained. Do not assume any specific file structure or directory hierarchy. - **Single Class Implementation**: Do not implement any class other than the one provided in the starter code. - **Class-Only Output**: Output ONLY the agent class and necessary standard imports. Do not include testing code, game logic outside the class, or example usage. - **No Broad Exception Handlers**: Do not wrap the body of `make_move()` in a broad exception handler such as `except Exception:`, `except BaseException:`, or a bare `except:`. The engine uses `signal.alarm` to enforce move time limits; broad catches will swallow the timeout exception and cause the match to hang. **IMPORTANT**: Output ONLY the `SurroundMorrisAgent` class definition and any additional imports you need (`random` is already available). Do NOT output the entire game code. The `ADJACENCY` dict is available as a global variable at runtime. ## Strategy Tips 1. **Avoid Suicide:** Suicide moves are legal but usually disastrous. Your piece is removed *before* it can capture enemies. Only use it if you are forced or have a specific deep-search reason. 2. **Watch for Friendly Fire:** Before moving, check if your move will block a friendly piece's last air hole. The engine kills your pieces first in the sweep, which may then free the enemy pieces you were trying to capture. 3. **Control crossroads (4 neighbors):** Spots 4, 10, 13, 19 give the most influence. 4. **Target corners (2 neighbors):** Corner pieces are easy to trap (needs only 2 enemies). 5. **Preserve empty neighbors:** Keep escape routes open to avoid Mate. 6. **Placement phase is critical:** Fight for central positions while disrupting opponent clusters. 7. **Avoid Repetition When Ahead:** If you draw by repetition, both players get 0 score. 8. **Use History:** The `history` field in the state dict lets you detect positions that have occurred before. ## Competition Format - 1 vs 1 match. - Scoring Rules: - Win by Elimination: Score = Winner's remaining pieces (e.g., 5 pieces vs 0 -> Winner +5, Loser -5). - Win by Mate: Score = **+7 for Winner, -7 for Loser** (Fixed). - Draw (Turn Limit or Repetition): Each player receives 0 score.