games.battleship.agent¶
Battleship game agent implementation.
- This module implements the main agent for the Battleship game, including:
LangGraph workflow for game logic
Turn-based gameplay management
LLM-powered player actions
Game state transitions
Ship placement and move execution
Classes¶
Battleship game agent with LLM-powered players. |
Module Contents¶
- class games.battleship.agent.BattleshipAgent(config)¶
Bases:
haive.core.engine.agent.agent.Agent
[haive.games.battleship.config.BattleshipAgentConfig
]Battleship game agent with LLM-powered players.
This agent implements a complete Battleship game with: - LLM-powered ship placement strategy - Turn-based gameplay with move validation - Strategic analysis of board state - Game state tracking and persistence - Visualization options
The agent uses LangGraph for workflow management and supports configurable LLM engines for different game actions.
- state_manager¶
Manager for game state transitions
- Type:
- config¶
Agent configuration
- Type:
- graph¶
LangGraph workflow
- Type:
Graph
Examples
>>> config = BattleshipAgentConfig() >>> agent = BattleshipAgent(config) >>> result = agent.run_game(visualize=True)
Initialize the Battleship agent.
- Parameters:
config (haive.games.battleship.config.BattleshipAgentConfig) â Configuration for the agent
- analyze_position(state, player)¶
Analyze game state and generate strategic insights.
Uses the playerâs analyzer engine to generate strategic analysis of the current game state, which helps inform move decisions.
- Parameters:
- Returns:
LangGraph command with updated state and next node
- Return type:
Command
Note
If an error occurs during analysis, itâs logged but doesnât stop the game - control flows to the playerâs move node.
- check_game_over(state)¶
Check if the game is over and update game state accordingly.
This node checks for game-ending conditions (all ships of a player being sunk) and updates the game state with the winner if the game is over.
- check_game_status(state)¶
Check the game status after a move.
Assesses whether the game is over, updates the winner if needed, and determines the next playerâs turn.
- ensure_state(state)¶
Ensure that state is a proper BattleshipState instance.
Converts dictionary representations to BattleshipState objects to ensure type safety throughout the agent.
- Parameters:
state (Any) â State object or dictionary
- Returns:
Properly typed state object
- Return type:
BattleshipState
Examples
>>> agent = BattleshipAgent(BattleshipAgentConfig()) >>> state_dict = {"game_phase": "setup", "current_player": "player1"} >>> state_obj = agent.ensure_state(state_dict) >>> isinstance(state_obj, BattleshipState) True
- initialize_game(state)¶
Initialize a new Battleship game.
Creates a fresh game state and starts the setup phase for ship placement.
- make_move(state, player, next_node='check_game_over')¶
Make an attack move for a player.
Uses the playerâs move engine to generate an attack coordinate, validates it, and updates the game state with the result.
- Parameters:
- Returns:
LangGraph command with updated state and next node
- Return type:
Command
- Raises:
ValueError â If the required engine is missing
Note
If the LLM fails to generate a valid move, a fallback move is generated using a deterministic strategy.
- place_ships(state, player)¶
Generate strategic ship placements for a player.
Uses the playerâs ship placement engine to generate optimal placements for all ships, validates them, and updates the game state.
- Parameters:
- Returns:
LangGraph command with updated state and next node
- Return type:
Command
- Raises:
ValueError â If the required engine is missing
Note
If an error occurs during placement, the game is reinitialized.
- place_ships_player1(state)¶
Place ships for player 1.
Delegates to the common place_ships method for player1.
- place_ships_player2(state)¶
Place ships for player 2.
Delegates to the common place_ships method for player2.
- player1_analysis(state)¶
Analyze position for player 1.
Delegates to the common analyze_position method for player1.
- player1_move(state)¶
Make a move for player 1.
Delegates to the common make_move method for player1.
- player2_analysis(state)¶
Analyze position for player 2.
Delegates to the common analyze_position method for player2.
- player2_move(state)¶
Make a move for player 2.
Delegates to the common make_move method for player2.
- run_game(visualize=True)¶
Run a complete Battleship game with comprehensive state tracking.
Executes the full game workflow from initialization through ship placement and gameplay to completion. Provides detailed game state tracking, error handling, and optional console visualization for monitoring game progress and debugging.
The method handles all phases of Battleship gameplay: - Game initialization and state setup - Ship placement for both players - Turn-based combat with move validation - Game termination and winner determination - Comprehensive error handling and recovery
- Parameters:
visualize (bool) â Whether to display detailed game progress in console. When True, shows turn-by-turn updates, board statistics, move history, and error messages. When False, runs silently and returns final state.
- Returns:
- Final game state dictionary containing:
winner: Winning player identifier or None
game_phase: Final phase (typically âendedâ)
move_history: Complete record of all moves made
player1_state/player2_state: Final player board states
error_message: Any error that occurred during gameplay
- Return type:
- Raises:
RuntimeError â If the game workflow fails to compile or execute properly.
ConfigurationError â If the agent configuration is invalid.
Examples
Running a visualized game for debugging::n
agent = BattleshipAgent(BattleshipAgentConfig()) result = agent.run_game(visualize=True)
# Console output shows: # â GAME STATE (Step 1) â # Turn: player1 # Phase: setup # Player 1 placed ships: False # Player 2 placed ships: False # # â GAME STATE (Step 2) â # Turn: player1 # Phase: playing # Player 1 Hits: 0, Ships Sunk: 0 # Player 2 Hits: 0, Ships Sunk: 0 # # đź GAME OVER! Winner: player1 đź
Running a silent game for automated testing::n
agent = BattleshipAgent(BattleshipAgentConfig()) result = agent.run_game(visualize=False)
winner = result.get(âwinnerâ) if winner:
print(fâGame completed, winner: {winner}â)
Handling game errors gracefully::n
- try:
result = agent.run_game(visualize=True) if result.get(âerror_messageâ):
print(fâGame error: {result[âerror_messageâ]}â) # Could retry with different configuration
- except Exception as e:
print(fâCritical game failure: {e}â)
Analyzing game performance::n
result = agent.run_game(visualize=False)
# Extract performance metrics move_history = result.get(âmove_historyâ, []) total_moves = len(move_history)
p1_state = result.get(âplayer1_stateâ, {}) p1_hits = len(p1_state.get(âboardâ, {}).get(âsuccessful_hitsâ, [])) hit_rate = p1_hits / total_moves if total_moves > 0 else 0
print(fâGame completed in {total_moves} movesâ) print(fâPlayer 1 hit rate: {hit_rate:.2%}â)
Note
The visualization mode provides detailed game state information that is valuable for debugging agent behavior, understanding game flow, and monitoring performance. Silent mode is optimized for automated testing and batch game execution.
- setup_workflow()¶
Set up the workflow for the Battleship game.
Creates a LangGraph workflow with nodes for: - Game initialization - Ship placement for both players - Move selection - Strategic analysis (if enabled) - Turn switching - Game over checking
The workflow includes conditional routing based on game state and supports different paths depending on whether analysis is enabled.
- switch_to_player1(state)¶
Switch to player 1âs turn.
Updates the current player to player1 and routes to the appropriate next node based on configuration (analysis or move).
- switch_to_player2(state)¶
Switch to player 2âs turn.
Updates the current player to player2 and routes to the appropriate next node based on configuration (analysis or move).