haive.games.framework.multi_player.agent¶
Multi-player game agent implementation.
- This module provides the base agent class for multi-player games, supporting:
Variable number of players
Role-based player configurations
Phase-based game flow
Information hiding between players
Concurrent or sequential player actions
Example
>>> from haive.agents.agent_games.framework.multi_player.agent import MultiPlayerGameAgent
>>>
>>> class ChessAgent(MultiPlayerGameAgent[ChessState]):
... def __init__(self, config: ChessConfig):
... super().__init__(config)
... self.state_manager = ChessStateManager
Classes¶
Base game agent for multi-player games. |
Module Contents¶
- class haive.games.framework.multi_player.agent.MultiPlayerGameAgent(config)[source]¶
Bases:
haive.core.engine.agent.agent.Agent
[haive.games.framework.multi_player.config.MultiPlayerGameConfig
],Generic
[T
]Base game agent for multi-player games.
This class provides the foundation for implementing multi-player game agents with support for role-based configurations, phase-based gameplay, and information hiding between players.
- Type Parameters:
T: The game state type, must be a Pydantic BaseModel.
- config¶
Agent configuration.
- Type:
- state_manager¶
State manager class.
- Type:
- graph¶
Game workflow graph.
- Type:
StateGraph
Example
>>> class MafiaAgent(MultiPlayerGameAgent[MafiaState]): ... def __init__(self, config: MafiaConfig): ... super().__init__(config) ... self.state_manager = MafiaStateManager ... ... def prepare_move_context(self, state, player_id): ... return { ... "game_state": state.board_string, ... "player_role": self.get_player_role(state, player_id) ... }
Initialize the multi-player game agent.
- Parameters:
config (MultiPlayerGameConfig) â Agent configuration including state schema, LLM configurations, and game settings.
- determine_next_step_after_player_turn(state)[source]¶
Determine what to do after a playerâs turn.
This method handles complex game flow logic, including: - Checking game end conditions - Managing phase transitions - Handling night/day cycle transitions - Processing voting and action completions
- Parameters:
state (MultiPlayerGameState) â Current game state.
- Returns:
- Next step to take, one of:
âend_gameâ: Game is over
âphase_transitionâ: Move to next phase
ânext_playerâ: Continue with next player
- Return type:
Example
>>> state = MafiaGameState(game_phase="NIGHT", votes={"p1": "p2"}) >>> # If all night actions complete >>> agent.determine_next_step_after_player_turn(state) 'phase_transition' # Move to day phase >>> # If more players need to act >>> agent.determine_next_step_after_player_turn(state) 'next_player' # Continue with next player
- abstractmethod extract_move(response, role)[source]¶
Extract move from engine response.
- Parameters:
response (Any) â Response from the engine.
role (str) â Role of the player.
- Returns:
Extracted move.
- Return type:
Any
- Raises:
NotImplementedError â Must be implemented by subclass.
- get_engine_for_player(role, function)[source]¶
Get the appropriate engine for a player based on role and function.
- get_player_role(state, player_id)[source]¶
Get the role of a player, handling case sensitivity.
This method attempts to find the playerâs role while handling different case variations of player IDs and special roles like ânarratorâ.
- Parameters:
state (MultiPlayerGameState) â Current game state.
player_id (str) â ID of the player to look up.
- Returns:
Role of the player, defaulting to âVILLAGERâ if not found.
- Return type:
Example
>>> state = MafiaGameState(roles={"player1": "MAFIA", "narrator": "NARRATOR"}) >>> agent.get_player_role(state, "Player1") # Case-insensitive 'MAFIA' >>> agent.get_player_role(state, "narrator") 'NARRATOR'
- handle_end_game(state)[source]¶
Handle the end of the game.
- Parameters:
state (T) â Current game state.
- Returns:
Final game state.
- Return type:
Dict[str, Any]
- handle_narrator_turn(state)[source]¶
Handle the narratorâs turn in the game.
This method manages the narratorâs actions, including: - Getting the appropriate narrator engine - Preparing narrator context - Processing narrator decisions - Applying narrator actions to the game state
- Parameters:
state (MultiPlayerGameState) â Current game state.
- Returns:
Updated game state after narratorâs action.
- Return type:
Dict[str, Any]
Example
>>> state = MafiaGameState(phase="NIGHT") >>> # Narrator processes night actions >>> new_state = agent.handle_narrator_turn(state) >>> new_state["phase"] # Narrator may have changed phase 'DAY'
Notes
Handles case sensitivity issues with narrator role
Provides error handling for missing narrator engine
Converts state between dict and model forms as needed
- handle_phase_transition(state)[source]¶
Handle transition between game phases.
- Parameters:
state (T) â Current game state.
- Returns:
Updated game state in the new phase.
- Return type:
Dict[str, Any]
- handle_player_turn(state)[source]¶
Handle a playerâs turn.
This method: 1. Gets the current player and their role 2. Retrieves the appropriate move engine 3. Filters state information for the player 4. Gets and applies the playerâs move 5. Checks game status after the move
- Parameters:
state (T) â Current game state.
- Returns:
Updated game state after the playerâs move.
- Return type:
Dict[str, Any]
- handle_setup_phase(state)[source]¶
Handle the setup phase of the game.
- Parameters:
state (T) â Current game state.
- Returns:
Updated game state after setup.
- Return type:
Dict[str, Any]
- initialize_game(state)[source]¶
Initialize the game state.
- Parameters:
state (BaseModel) â Initial state data or empty state.
- Returns:
Initialized game state.
- Return type:
Dict[str, Any]
- Raises:
ValueError â If state manager is not set.
- abstractmethod prepare_move_context(state, player_id)[source]¶
Prepare context for move generation.
- Parameters:
state (T) â Current game state.
player_id (str) â ID of the player.
- Returns:
Context for move generation.
- Return type:
Dict[str, Any]
- Raises:
NotImplementedError â Must be implemented by subclass.
- abstractmethod prepare_narrator_context(state)[source]¶
Prepare context for narratorâs decision making.
This method should be implemented by game-specific agents to provide the narrator with appropriate context for the current game state.
- Parameters:
state (MultiPlayerGameState) â Current game state.
- Returns:
Context for narratorâs decision making.
- Return type:
Dict[str, Any]
- Raises:
NotImplementedError â Must be implemented by subclass.
Example
>>> def prepare_narrator_context(self, state): ... return { ... "phase": state.game_phase, ... "alive_players": [p for p in state.players if p.is_alive], ... "recent_actions": state.action_history[-5:] ... }
- setup_workflow()[source]¶
Setup the standard game workflow with phases.
- This method creates a workflow graph with the following structure:
Game initialization
Setup phase
Player turns
Phase transitions
Game end
The workflow supports conditional transitions based on game state and can be overridden for custom game flows.
- should_continue_after_phase_transition(state)[source]¶
Determine if we should continue after a phase transition.
- Parameters:
state (T) â Current game state.
- Returns:
True if game should continue.
- Return type:
- should_continue_to_main_phase(state)[source]¶
Determine if we should continue to the main phase.
- Parameters:
state (T) â Current game state.
- Returns:
True if game should continue to main phase.
- Return type:
- should_transition_phase(state)[source]¶
Determine if we should transition to a new phase.
- Parameters:
state (T) â Current game state.
- Returns:
True if phase transition should occur.
- Return type:
- abstractmethod visualize_state(state)[source]¶
Visualize the current game state.
- Parameters:
state (Dict[str, Any]) â Current game state.
- Raises:
NotImplementedError â Must be implemented by subclass.
- Return type:
None