chessai.agents.positional
1import collections 2import math 3import typing 4 5import chessai.agents.greedy 6import chessai.chess.gamestate 7import chessai.core.action 8import chessai.core.agent 9import chessai.core.agentinfo 10import chessai.core.board 11import chessai.core.coordinate 12import chessai.core.gamestate 13import chessai.core.piece 14import chessai.util.alias 15import chessai.util.reflection 16 17POSITIONAL_STATE_EVAL: str = chessai.util.alias.STATE_EVAL_POSITIONAL.long 18 19class PositionalAgent(chessai.agents.greedy.GreedyAgent): 20 """ 21 A greedy chess opponent that values material and central squares. 22 23 This class inherits its move-selection behavior from GreedyAgent. 24 Its only change is using positional_state_eval() as the default evaluator. 25 """ 26 27 def __init__(self, 28 name: chessai.util.reflection.Reference | str = chessai.util.alias.AGENT_POSITIONAL.long, 29 state_eval_func: chessai.core.gamestate.AgentStateEvaluationFunction | chessai.util.reflection.Reference | str = 30 POSITIONAL_STATE_EVAL, 31 display_name: str = '') -> None: 32 # AgentInfo supplies the shared default when no evaluator was requested. 33 if (state_eval_func == chessai.core.agentinfo.DEFAULT_STATE_EVAL): 34 state_eval_func = POSITIONAL_STATE_EVAL 35 36 super().__init__(name, state_eval_func, display_name) 37 38 self.heat_map: dict[type[chessai.core.piece.Piece], dict[chessai.core.coordinate.Coordinate, float]] = {} 39 """ Positional values, optionally specialized by piece type. """ 40 41 def game_start(self, 42 initial_state: chessai.core.gamestate.GameState) -> None: 43 player = self.player 44 if (player is None): 45 player = initial_state.turn 46 47 # Build a heat map given for the player the agent is playing as. 48 self.heat_map = self._build_heat_map(initial_state.board, player) 49 50 def get_square_score(self, 51 piece: chessai.core.piece.Piece, 52 coordinate: chessai.core.coordinate.Coordinate, 53 ) -> float: 54 """ Return a piece's positional value, using its type-specific map when available. """ 55 56 return self._get_heat_map_score(self.heat_map, piece, coordinate) + self.rng.uniform(-0.1, 0.1) 57 58 @staticmethod 59 def _get_heat_map_score( 60 heat_map: dict[type[chessai.core.piece.Piece], dict[chessai.core.coordinate.Coordinate, float]], 61 piece: chessai.core.piece.Piece, 62 coordinate: chessai.core.coordinate.Coordinate, 63 ) -> float: 64 """ Return a piece's positional value from a supplied heat map. """ 65 66 for piece_type in type(piece).mro(): 67 if piece_type in heat_map: 68 return heat_map[piece_type][coordinate] 69 70 return heat_map[chessai.core.piece.Piece][coordinate] 71 72 @staticmethod 73 def _build_heat_map( 74 board: chessai.core.board.Board, 75 player: chessai.core.types.Color, 76 ) -> dict[type[chessai.core.piece.Piece], dict[chessai.core.coordinate.Coordinate, float]]: 77 """ 78 Build the default heat map. 79 80 Kings prefer to move to the edge of the board. 81 Pawns prefer to move to the opposite side of the board to promote. 82 Other pieces prefer moving to the center of the board. 83 """ 84 85 central_heat_map = {} 86 edge_heat_map = {} 87 opposite_heat_map = {} 88 89 final_rank = board.num_ranks - 1 90 if (player == chessai.core.types.Color.BLACK): 91 final_rank = 0 92 93 maximum_distance = (board.num_files - 1) + (board.num_ranks - 1) 94 95 for file in range(board.num_files): 96 for rank in range(board.num_ranks): 97 coordinate = chessai.core.coordinate.Coordinate(file, rank) 98 distance_from_center = abs((2 * file) - (board.num_files - 1)) 99 distance_from_center += abs((2 * rank) - (board.num_ranks - 1)) 100 central_heat_map[coordinate] = float(maximum_distance - distance_from_center) 101 edge_heat_map[coordinate] = float(distance_from_center - maximum_distance) 102 opposite_heat_map[coordinate] = 2.5 * ((board.num_ranks - 1) - abs(final_rank - rank)) 103 104 return { 105 # Default to always scoring the piece as 0. 106 chessai.core.piece.Piece: collections.defaultdict(float), 107 108 # Prefer to move the king to the edge of the map. 109 chessai.chess.piece.King: edge_heat_map, 110 111 # Prefer to move attacking pieces to the center. 112 chessai.chess.piece.Queen: central_heat_map, 113 chessai.chess.piece.Rook: central_heat_map, 114 chessai.chess.piece.Bishop: central_heat_map, 115 chessai.chess.piece.Knight: central_heat_map, 116 117 # Prefer to move the pawns to the other side of the board to promote. 118 chessai.chess.piece.Pawn: opposite_heat_map, 119 } 120 121def positional_state_eval( 122 state: chessai.core.gamestate.GameState, 123 action: chessai.core.action.Action | None = None, 124 agent: typing.Any | None = None, 125 **kwargs: typing.Any) -> float: 126 """ 127 Evaluate a position from the requesting agent's perspective. 128 129 In addition to material, pieces receive a reward based on their position. 130 By default, the positional scoring is based on PositionalAgent._build_heat_map(). 131 """ 132 133 player = state.turn 134 positional_agent = None 135 if isinstance(agent, chessai.core.agent.Agent): 136 if (agent.player is not None): 137 player = agent.player 138 139 if isinstance(agent, PositionalAgent): 140 positional_agent = agent 141 142 heat_maps = { 143 color: PositionalAgent._build_heat_map(state.board, color) 144 for color in chessai.core.types.Color 145 } 146 147 if ((len(state.get_legal_move_actions()) == 0) and state.is_check(state.turn)): 148 if (state.turn == player): 149 return -math.inf 150 151 return math.inf 152 153 score = chessai.chess.gamestate.base_eval(state, action = action, agent = agent) 154 155 for (coordinate, piece) in state.get_coordinate_map().items(): 156 piece_heat_map = heat_maps[piece.color] 157 square_score = PositionalAgent._get_heat_map_score(piece_heat_map, piece, coordinate) 158 if ((positional_agent is not None) and (piece.color == player)): 159 square_score = positional_agent.get_square_score(piece, coordinate) 160 161 if (piece.color == player): 162 score += 0.15 * square_score 163 else: 164 score -= 0.15 * square_score 165 166 return score
20class PositionalAgent(chessai.agents.greedy.GreedyAgent): 21 """ 22 A greedy chess opponent that values material and central squares. 23 24 This class inherits its move-selection behavior from GreedyAgent. 25 Its only change is using positional_state_eval() as the default evaluator. 26 """ 27 28 def __init__(self, 29 name: chessai.util.reflection.Reference | str = chessai.util.alias.AGENT_POSITIONAL.long, 30 state_eval_func: chessai.core.gamestate.AgentStateEvaluationFunction | chessai.util.reflection.Reference | str = 31 POSITIONAL_STATE_EVAL, 32 display_name: str = '') -> None: 33 # AgentInfo supplies the shared default when no evaluator was requested. 34 if (state_eval_func == chessai.core.agentinfo.DEFAULT_STATE_EVAL): 35 state_eval_func = POSITIONAL_STATE_EVAL 36 37 super().__init__(name, state_eval_func, display_name) 38 39 self.heat_map: dict[type[chessai.core.piece.Piece], dict[chessai.core.coordinate.Coordinate, float]] = {} 40 """ Positional values, optionally specialized by piece type. """ 41 42 def game_start(self, 43 initial_state: chessai.core.gamestate.GameState) -> None: 44 player = self.player 45 if (player is None): 46 player = initial_state.turn 47 48 # Build a heat map given for the player the agent is playing as. 49 self.heat_map = self._build_heat_map(initial_state.board, player) 50 51 def get_square_score(self, 52 piece: chessai.core.piece.Piece, 53 coordinate: chessai.core.coordinate.Coordinate, 54 ) -> float: 55 """ Return a piece's positional value, using its type-specific map when available. """ 56 57 return self._get_heat_map_score(self.heat_map, piece, coordinate) + self.rng.uniform(-0.1, 0.1) 58 59 @staticmethod 60 def _get_heat_map_score( 61 heat_map: dict[type[chessai.core.piece.Piece], dict[chessai.core.coordinate.Coordinate, float]], 62 piece: chessai.core.piece.Piece, 63 coordinate: chessai.core.coordinate.Coordinate, 64 ) -> float: 65 """ Return a piece's positional value from a supplied heat map. """ 66 67 for piece_type in type(piece).mro(): 68 if piece_type in heat_map: 69 return heat_map[piece_type][coordinate] 70 71 return heat_map[chessai.core.piece.Piece][coordinate] 72 73 @staticmethod 74 def _build_heat_map( 75 board: chessai.core.board.Board, 76 player: chessai.core.types.Color, 77 ) -> dict[type[chessai.core.piece.Piece], dict[chessai.core.coordinate.Coordinate, float]]: 78 """ 79 Build the default heat map. 80 81 Kings prefer to move to the edge of the board. 82 Pawns prefer to move to the opposite side of the board to promote. 83 Other pieces prefer moving to the center of the board. 84 """ 85 86 central_heat_map = {} 87 edge_heat_map = {} 88 opposite_heat_map = {} 89 90 final_rank = board.num_ranks - 1 91 if (player == chessai.core.types.Color.BLACK): 92 final_rank = 0 93 94 maximum_distance = (board.num_files - 1) + (board.num_ranks - 1) 95 96 for file in range(board.num_files): 97 for rank in range(board.num_ranks): 98 coordinate = chessai.core.coordinate.Coordinate(file, rank) 99 distance_from_center = abs((2 * file) - (board.num_files - 1)) 100 distance_from_center += abs((2 * rank) - (board.num_ranks - 1)) 101 central_heat_map[coordinate] = float(maximum_distance - distance_from_center) 102 edge_heat_map[coordinate] = float(distance_from_center - maximum_distance) 103 opposite_heat_map[coordinate] = 2.5 * ((board.num_ranks - 1) - abs(final_rank - rank)) 104 105 return { 106 # Default to always scoring the piece as 0. 107 chessai.core.piece.Piece: collections.defaultdict(float), 108 109 # Prefer to move the king to the edge of the map. 110 chessai.chess.piece.King: edge_heat_map, 111 112 # Prefer to move attacking pieces to the center. 113 chessai.chess.piece.Queen: central_heat_map, 114 chessai.chess.piece.Rook: central_heat_map, 115 chessai.chess.piece.Bishop: central_heat_map, 116 chessai.chess.piece.Knight: central_heat_map, 117 118 # Prefer to move the pawns to the other side of the board to promote. 119 chessai.chess.piece.Pawn: opposite_heat_map, 120 }
A greedy chess opponent that values material and central squares.
This class inherits its move-selection behavior from GreedyAgent. Its only change is using positional_state_eval() as the default evaluator.
28 def __init__(self, 29 name: chessai.util.reflection.Reference | str = chessai.util.alias.AGENT_POSITIONAL.long, 30 state_eval_func: chessai.core.gamestate.AgentStateEvaluationFunction | chessai.util.reflection.Reference | str = 31 POSITIONAL_STATE_EVAL, 32 display_name: str = '') -> None: 33 # AgentInfo supplies the shared default when no evaluator was requested. 34 if (state_eval_func == chessai.core.agentinfo.DEFAULT_STATE_EVAL): 35 state_eval_func = POSITIONAL_STATE_EVAL 36 37 super().__init__(name, state_eval_func, display_name) 38 39 self.heat_map: dict[type[chessai.core.piece.Piece], dict[chessai.core.coordinate.Coordinate, float]] = {} 40 """ Positional values, optionally specialized by piece type. """
Positional values, optionally specialized by piece type.
42 def game_start(self, 43 initial_state: chessai.core.gamestate.GameState) -> None: 44 player = self.player 45 if (player is None): 46 player = initial_state.turn 47 48 # Build a heat map given for the player the agent is playing as. 49 self.heat_map = self._build_heat_map(initial_state.board, player)
Notify this agent that the game is about to start. The state represents the initial state of the game. Any precomputation for this game should be done in this method. Calls to this method may be subject to a timeout.
51 def get_square_score(self, 52 piece: chessai.core.piece.Piece, 53 coordinate: chessai.core.coordinate.Coordinate, 54 ) -> float: 55 """ Return a piece's positional value, using its type-specific map when available. """ 56 57 return self._get_heat_map_score(self.heat_map, piece, coordinate) + self.rng.uniform(-0.1, 0.1)
Return a piece's positional value, using its type-specific map when available.
122def positional_state_eval( 123 state: chessai.core.gamestate.GameState, 124 action: chessai.core.action.Action | None = None, 125 agent: typing.Any | None = None, 126 **kwargs: typing.Any) -> float: 127 """ 128 Evaluate a position from the requesting agent's perspective. 129 130 In addition to material, pieces receive a reward based on their position. 131 By default, the positional scoring is based on PositionalAgent._build_heat_map(). 132 """ 133 134 player = state.turn 135 positional_agent = None 136 if isinstance(agent, chessai.core.agent.Agent): 137 if (agent.player is not None): 138 player = agent.player 139 140 if isinstance(agent, PositionalAgent): 141 positional_agent = agent 142 143 heat_maps = { 144 color: PositionalAgent._build_heat_map(state.board, color) 145 for color in chessai.core.types.Color 146 } 147 148 if ((len(state.get_legal_move_actions()) == 0) and state.is_check(state.turn)): 149 if (state.turn == player): 150 return -math.inf 151 152 return math.inf 153 154 score = chessai.chess.gamestate.base_eval(state, action = action, agent = agent) 155 156 for (coordinate, piece) in state.get_coordinate_map().items(): 157 piece_heat_map = heat_maps[piece.color] 158 square_score = PositionalAgent._get_heat_map_score(piece_heat_map, piece, coordinate) 159 if ((positional_agent is not None) and (piece.color == player)): 160 square_score = positional_agent.get_square_score(piece, coordinate) 161 162 if (piece.color == player): 163 score += 0.15 * square_score 164 else: 165 score -= 0.15 * square_score 166 167 return score
Evaluate a position from the requesting agent's perspective.
In addition to material, pieces receive a reward based on their position. By default, the positional scoring is based on PositionalAgent._build_heat_map().