haive.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¶

BattleshipAgent

Battleship game agent with LLM-powered players.

Module Contents¶

class haive.games.battleship.agent.BattleshipAgent(config)[source]¶

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:

BattleshipStateManager

engines¶

LLM engine configurations for different game actions

Type:

dict

config¶

Agent configuration

Type:

BattleshipAgentConfig

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)[source]¶

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:
  • state (dict[str, Any]) – Current game state

  • player (str) – Player for whom to generate analysis

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)[source]¶

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.

Parameters:

state (dict[str, Any]) – Current game state

Returns:

LangGraph command with updated state and next node

Return type:

Command

check_game_status(state)[source]¶

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.

Parameters:

state (dict[str, Any]) – Current game state

Returns:

LangGraph command with updated state and next node

Return type:

Command

ensure_state(state)[source]¶

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)[source]¶

Initialize a new Battleship game.

Creates a fresh game state and starts the setup phase for ship placement.

Parameters:

state (dict[str, Any]) – Initial state (usually empty)

Returns:

LangGraph command with initialized state

Return type:

Command

make_move(state, player, next_node='check_game_over')[source]¶

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:
  • state (dict[str, Any]) – Current game state

  • player (str) – Player making the move

  • next_node (str) – Next node to route to after the move

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)[source]¶

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:
  • state (dict[str, Any]) – Current game state

  • player (str) – Player for whom to place ships

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)[source]¶

Place ships for player 1.

Delegates to the common place_ships method for player1.

Parameters:

state (dict[str, Any]) – Current game state

Returns:

LangGraph command with updated state

Return type:

Command

place_ships_player2(state)[source]¶

Place ships for player 2.

Delegates to the common place_ships method for player2.

Parameters:

state (dict[str, Any]) – Current game state

Returns:

LangGraph command with updated state

Return type:

Command

player1_analysis(state)[source]¶

Analyze position for player 1.

Delegates to the common analyze_position method for player1.

Parameters:

state (dict[str, Any]) – Current game state

Returns:

LangGraph command with updated state

Return type:

Command

player1_move(state)[source]¶

Make a move for player 1.

Delegates to the common make_move method for player1.

Parameters:

state (dict[str, Any]) – Current game state

Returns:

LangGraph command with updated state

Return type:

Command

player2_analysis(state)[source]¶

Analyze position for player 2.

Delegates to the common analyze_position method for player2.

Parameters:

state (dict[str, Any]) – Current game state

Returns:

LangGraph command with updated state

Return type:

Command

player2_move(state)[source]¶

Make a move for player 2.

Delegates to the common make_move method for player2.

Parameters:

state (dict[str, Any]) – Current game state

Returns:

LangGraph command with updated state

Return type:

Command

run_game(visualize=True)[source]¶

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:

dict[str, Any]

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()[source]¶

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)[source]¶

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).

Parameters:

state (dict[str, Any]) – Current game state

Returns:

LangGraph command with updated state and next node

Return type:

Command

switch_to_player2(state)[source]¶

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).

Parameters:

state (dict[str, Any]) – Current game state

Returns:

LangGraph command with updated state and next node

Return type:

Command