chessai.puzzle.game
1import argparse 2import logging 3import random 4import typing 5 6import chessai.agents.multiscripted 7import chessai.chess.game 8import chessai.core.agentinfo 9import chessai.core.board 10import chessai.core.game 11import chessai.core.gamestate 12import chessai.puzzle.gamestate 13 14class Game(chessai.chess.game.Game): 15 """ 16 A game following the rules of a chess puzzle. 17 18 The agent wins by completing any one of the board's valid move lines. 19 The opposing side is played by a multi scripted agent that follows a scripted continuation. 20 21 The game ends as soon as: 22 - The agent plays a move that satisfies the final step of a move line (puzzle solved). 23 - The agent plays a move that is not consistent with ANY remaining move line (puzzle failed). 24 """ 25 26 def __init__(self, 27 game_info: chessai.core.game.GameInfo, 28 save_path: str | None = None, 29 is_replay: bool = False, 30 move_lines: list[list[chessai.core.action.Action]] | str | dict[str, typing.Any] | None = None) -> None: 31 super().__init__(game_info, save_path, is_replay) 32 33 if (move_lines is None): 34 move_lines = [] 35 36 if (isinstance(move_lines, dict)): 37 move_lines = str(move_lines.get(chessai.puzzle.parser.MOVE_LINES_KEY, "")) 38 39 if (isinstance(move_lines, str)): 40 move_lines = chessai.core.action.process_raw_action_list(move_lines) 41 42 self.move_lines: list[list[chessai.core.action.Action]] = move_lines 43 """ The move lines of this puzzle. """ 44 45 self.start_move_lines: list[list[chessai.core.action.Action]] = move_lines.copy() 46 """ The starting move lines of the puzzle, which will remain static throughout the game. """ 47 48 def process_args(self, args: argparse.Namespace) -> None: 49 # Let the gamestate parse the FEN and determine the puzzle agent. 50 initial_state = chessai.puzzle.gamestate.GameState.from_fen(fen = args.board, _capture_move_lines = True) 51 52 move_lines: list[list[chessai.core.action.Action]] = [] 53 if (args.move_lines is not None): 54 # Override the move lines from the file if there are move lines from the CLI. 55 move_lines = chessai.core.action.process_raw_action_list(args.move_lines) 56 elif (initial_state._move_lines is not None): 57 # If the game does not have move lines, use the move lines found in the file. 58 move_lines = initial_state._move_lines 59 60 self.move_lines = move_lines 61 self.start_move_lines = self.move_lines.copy() 62 63 # Override the dummy player with a scripted agent that follows the move lines. 64 self.game_info.agent_infos[initial_state.dummy_player].extra_arguments['move_lines'] = self.start_move_lines.copy() 65 66 def get_initial_state(self, 67 rng: random.Random, 68 fen: str | None = None) -> chessai.core.gamestate.GameState: 69 return chessai.puzzle.gamestate.GameState.from_fen(fen = fen) 70 71 def process_turn(self, 72 state: chessai.core.gamestate.GameState, 73 action_record: chessai.core.agentaction.AgentActionRecord, 74 result: chessai.core.game.GameResult, 75 rng: random.Random, 76 ) -> chessai.core.gamestate.GameState: 77 """ 78 Process the given agent action and return an updated game state. 79 The returned game state may be a copy or modified version of the passed-in game state. 80 """ 81 82 state = typing.cast(chessai.puzzle.gamestate.GameState, state) 83 84 # The agent has timed out. 85 if (action_record.timeout): 86 result.timeout_agent_teams.append(action_record.player) 87 state.process_agent_timeout(action_record.player) 88 return state 89 90 # The agent has crashed. 91 if (action_record.crashed): 92 result.crash_agent_teams.append(action_record.player) 93 state.process_agent_crash(action_record.player) 94 return state 95 96 action = action_record.get_action() 97 if (action not in state.get_legal_actions()): 98 raise ValueError(f"Illegal action for agent {action_record.player}: '{action}' of type '{type(action)}'.") 99 100 # Check whether the move follows any of the remaining move lines. 101 if (action not in self._next_puzzle_moves()): 102 logging.info( 103 "Incorrect action for agent '%s': '%s' of type '%s'.", 104 action_record.player, action, type(action), 105 ) 106 107 # The agent failed to solve the puzzle, so the game is over. 108 state.game_over = True 109 return state 110 111 self._call_state_process_turn_full(state, action, rng) 112 113 # Progress the move lines of the puzzle. 114 self._update_move_lines(state, action) 115 116 return state 117 118 def check_end(self, state: chessai.core.gamestate.GameState) -> bool: 119 if state.game_over: 120 return True 121 122 return (len(self.move_lines) == 0) 123 124 def _next_puzzle_moves(self) -> list[chessai.core.action.Action]: 125 """ Get the list of possible next moves from the puzzle's move lines. """ 126 127 move_options = [] 128 129 for move_line in self.move_lines: 130 if (len(move_line) > 0): 131 move_options.append(move_line[0]) 132 133 return move_options 134 135 def _update_move_lines(self, state: chessai.puzzle.gamestate.GameState, action: chessai.core.action.Action) -> bool: 136 """ 137 Update the possible puzzle lines based on the action taken. 138 139 Returns whether the action matched at least one move line. 140 """ 141 142 new_move_lines = [] 143 matched_move_line = False 144 145 for move_line in self.move_lines: 146 if (len(move_line) == 0): 147 continue 148 149 # Skip if the action is not consistent with the move line. 150 if (move_line[0] != action): 151 continue 152 153 matched_move_line = True 154 155 new_move_line = move_line[1:] 156 157 # If there is nothing left in the move line, skip it. 158 if (len(new_move_line) == 0): 159 continue 160 161 new_move_lines.append(new_move_line) 162 163 self.move_lines = new_move_lines 164 165 # If the action matched a move line and there are no remaining move lines, the puzzle is solved. 166 if (matched_move_line and (len(self.move_lines) == 0)): 167 state.puzzle_solved = True 168 169 return matched_move_line
15class Game(chessai.chess.game.Game): 16 """ 17 A game following the rules of a chess puzzle. 18 19 The agent wins by completing any one of the board's valid move lines. 20 The opposing side is played by a multi scripted agent that follows a scripted continuation. 21 22 The game ends as soon as: 23 - The agent plays a move that satisfies the final step of a move line (puzzle solved). 24 - The agent plays a move that is not consistent with ANY remaining move line (puzzle failed). 25 """ 26 27 def __init__(self, 28 game_info: chessai.core.game.GameInfo, 29 save_path: str | None = None, 30 is_replay: bool = False, 31 move_lines: list[list[chessai.core.action.Action]] | str | dict[str, typing.Any] | None = None) -> None: 32 super().__init__(game_info, save_path, is_replay) 33 34 if (move_lines is None): 35 move_lines = [] 36 37 if (isinstance(move_lines, dict)): 38 move_lines = str(move_lines.get(chessai.puzzle.parser.MOVE_LINES_KEY, "")) 39 40 if (isinstance(move_lines, str)): 41 move_lines = chessai.core.action.process_raw_action_list(move_lines) 42 43 self.move_lines: list[list[chessai.core.action.Action]] = move_lines 44 """ The move lines of this puzzle. """ 45 46 self.start_move_lines: list[list[chessai.core.action.Action]] = move_lines.copy() 47 """ The starting move lines of the puzzle, which will remain static throughout the game. """ 48 49 def process_args(self, args: argparse.Namespace) -> None: 50 # Let the gamestate parse the FEN and determine the puzzle agent. 51 initial_state = chessai.puzzle.gamestate.GameState.from_fen(fen = args.board, _capture_move_lines = True) 52 53 move_lines: list[list[chessai.core.action.Action]] = [] 54 if (args.move_lines is not None): 55 # Override the move lines from the file if there are move lines from the CLI. 56 move_lines = chessai.core.action.process_raw_action_list(args.move_lines) 57 elif (initial_state._move_lines is not None): 58 # If the game does not have move lines, use the move lines found in the file. 59 move_lines = initial_state._move_lines 60 61 self.move_lines = move_lines 62 self.start_move_lines = self.move_lines.copy() 63 64 # Override the dummy player with a scripted agent that follows the move lines. 65 self.game_info.agent_infos[initial_state.dummy_player].extra_arguments['move_lines'] = self.start_move_lines.copy() 66 67 def get_initial_state(self, 68 rng: random.Random, 69 fen: str | None = None) -> chessai.core.gamestate.GameState: 70 return chessai.puzzle.gamestate.GameState.from_fen(fen = fen) 71 72 def process_turn(self, 73 state: chessai.core.gamestate.GameState, 74 action_record: chessai.core.agentaction.AgentActionRecord, 75 result: chessai.core.game.GameResult, 76 rng: random.Random, 77 ) -> chessai.core.gamestate.GameState: 78 """ 79 Process the given agent action and return an updated game state. 80 The returned game state may be a copy or modified version of the passed-in game state. 81 """ 82 83 state = typing.cast(chessai.puzzle.gamestate.GameState, state) 84 85 # The agent has timed out. 86 if (action_record.timeout): 87 result.timeout_agent_teams.append(action_record.player) 88 state.process_agent_timeout(action_record.player) 89 return state 90 91 # The agent has crashed. 92 if (action_record.crashed): 93 result.crash_agent_teams.append(action_record.player) 94 state.process_agent_crash(action_record.player) 95 return state 96 97 action = action_record.get_action() 98 if (action not in state.get_legal_actions()): 99 raise ValueError(f"Illegal action for agent {action_record.player}: '{action}' of type '{type(action)}'.") 100 101 # Check whether the move follows any of the remaining move lines. 102 if (action not in self._next_puzzle_moves()): 103 logging.info( 104 "Incorrect action for agent '%s': '%s' of type '%s'.", 105 action_record.player, action, type(action), 106 ) 107 108 # The agent failed to solve the puzzle, so the game is over. 109 state.game_over = True 110 return state 111 112 self._call_state_process_turn_full(state, action, rng) 113 114 # Progress the move lines of the puzzle. 115 self._update_move_lines(state, action) 116 117 return state 118 119 def check_end(self, state: chessai.core.gamestate.GameState) -> bool: 120 if state.game_over: 121 return True 122 123 return (len(self.move_lines) == 0) 124 125 def _next_puzzle_moves(self) -> list[chessai.core.action.Action]: 126 """ Get the list of possible next moves from the puzzle's move lines. """ 127 128 move_options = [] 129 130 for move_line in self.move_lines: 131 if (len(move_line) > 0): 132 move_options.append(move_line[0]) 133 134 return move_options 135 136 def _update_move_lines(self, state: chessai.puzzle.gamestate.GameState, action: chessai.core.action.Action) -> bool: 137 """ 138 Update the possible puzzle lines based on the action taken. 139 140 Returns whether the action matched at least one move line. 141 """ 142 143 new_move_lines = [] 144 matched_move_line = False 145 146 for move_line in self.move_lines: 147 if (len(move_line) == 0): 148 continue 149 150 # Skip if the action is not consistent with the move line. 151 if (move_line[0] != action): 152 continue 153 154 matched_move_line = True 155 156 new_move_line = move_line[1:] 157 158 # If there is nothing left in the move line, skip it. 159 if (len(new_move_line) == 0): 160 continue 161 162 new_move_lines.append(new_move_line) 163 164 self.move_lines = new_move_lines 165 166 # If the action matched a move line and there are no remaining move lines, the puzzle is solved. 167 if (matched_move_line and (len(self.move_lines) == 0)): 168 state.puzzle_solved = True 169 170 return matched_move_line
A game following the rules of a chess puzzle.
The agent wins by completing any one of the board's valid move lines. The opposing side is played by a multi scripted agent that follows a scripted continuation.
The game ends as soon as:
- The agent plays a move that satisfies the final step of a move line (puzzle solved).
- The agent plays a move that is not consistent with ANY remaining move line (puzzle failed).
27 def __init__(self, 28 game_info: chessai.core.game.GameInfo, 29 save_path: str | None = None, 30 is_replay: bool = False, 31 move_lines: list[list[chessai.core.action.Action]] | str | dict[str, typing.Any] | None = None) -> None: 32 super().__init__(game_info, save_path, is_replay) 33 34 if (move_lines is None): 35 move_lines = [] 36 37 if (isinstance(move_lines, dict)): 38 move_lines = str(move_lines.get(chessai.puzzle.parser.MOVE_LINES_KEY, "")) 39 40 if (isinstance(move_lines, str)): 41 move_lines = chessai.core.action.process_raw_action_list(move_lines) 42 43 self.move_lines: list[list[chessai.core.action.Action]] = move_lines 44 """ The move lines of this puzzle. """ 45 46 self.start_move_lines: list[list[chessai.core.action.Action]] = move_lines.copy() 47 """ The starting move lines of the puzzle, which will remain static throughout the game. """
The starting move lines of the puzzle, which will remain static throughout the game.
49 def process_args(self, args: argparse.Namespace) -> None: 50 # Let the gamestate parse the FEN and determine the puzzle agent. 51 initial_state = chessai.puzzle.gamestate.GameState.from_fen(fen = args.board, _capture_move_lines = True) 52 53 move_lines: list[list[chessai.core.action.Action]] = [] 54 if (args.move_lines is not None): 55 # Override the move lines from the file if there are move lines from the CLI. 56 move_lines = chessai.core.action.process_raw_action_list(args.move_lines) 57 elif (initial_state._move_lines is not None): 58 # If the game does not have move lines, use the move lines found in the file. 59 move_lines = initial_state._move_lines 60 61 self.move_lines = move_lines 62 self.start_move_lines = self.move_lines.copy() 63 64 # Override the dummy player with a scripted agent that follows the move lines. 65 self.game_info.agent_infos[initial_state.dummy_player].extra_arguments['move_lines'] = self.start_move_lines.copy()
Process any special arguments from the command-line.
67 def get_initial_state(self, 68 rng: random.Random, 69 fen: str | None = None) -> chessai.core.gamestate.GameState: 70 return chessai.puzzle.gamestate.GameState.from_fen(fen = fen)
Create the initial state for this game.
72 def process_turn(self, 73 state: chessai.core.gamestate.GameState, 74 action_record: chessai.core.agentaction.AgentActionRecord, 75 result: chessai.core.game.GameResult, 76 rng: random.Random, 77 ) -> chessai.core.gamestate.GameState: 78 """ 79 Process the given agent action and return an updated game state. 80 The returned game state may be a copy or modified version of the passed-in game state. 81 """ 82 83 state = typing.cast(chessai.puzzle.gamestate.GameState, state) 84 85 # The agent has timed out. 86 if (action_record.timeout): 87 result.timeout_agent_teams.append(action_record.player) 88 state.process_agent_timeout(action_record.player) 89 return state 90 91 # The agent has crashed. 92 if (action_record.crashed): 93 result.crash_agent_teams.append(action_record.player) 94 state.process_agent_crash(action_record.player) 95 return state 96 97 action = action_record.get_action() 98 if (action not in state.get_legal_actions()): 99 raise ValueError(f"Illegal action for agent {action_record.player}: '{action}' of type '{type(action)}'.") 100 101 # Check whether the move follows any of the remaining move lines. 102 if (action not in self._next_puzzle_moves()): 103 logging.info( 104 "Incorrect action for agent '%s': '%s' of type '%s'.", 105 action_record.player, action, type(action), 106 ) 107 108 # The agent failed to solve the puzzle, so the game is over. 109 state.game_over = True 110 return state 111 112 self._call_state_process_turn_full(state, action, rng) 113 114 # Progress the move lines of the puzzle. 115 self._update_move_lines(state, action) 116 117 return state
Process the given agent action and return an updated game state. The returned game state may be a copy or modified version of the passed-in game state.
119 def check_end(self, state: chessai.core.gamestate.GameState) -> bool: 120 if state.game_over: 121 return True 122 123 return (len(self.move_lines) == 0)
Check to see if the game is over. Return True if the game is now over, False otherwise.
By default, this will check chessai.core.gamestate.GameState.game_over and chessai.core.gamestate.GameState.is_game_over(), but child games can override for more complex functionality.