chessai.escort.bin

  1import argparse
  2import logging
  3import typing
  4
  5import chessai.core.agentinfo
  6import chessai.core.game
  7import chessai.core.types
  8import chessai.escort.game
  9import chessai.escort.gamestate
 10import chessai.util.alias
 11import chessai.util.bin
 12
 13DEFAULT_BOARD: str = 'alcove-demo'
 14
 15def set_cli_args(parser: argparse.ArgumentParser, **kwargs: typing.Any) -> argparse.ArgumentParser:
 16    """
 17    Set Escort-specific command-line arguments.
 18    """
 19
 20    parser.add_argument('--agent', dest = 'agent', action = 'store', type = str,
 21            default = chessai.util.alias.AGENT_USER_INPUT.short,
 22            help = ('Select the Escort agent (default: %(default)s).'
 23                    + f' Builtin agents: {chessai.util.alias.AGENT_SHORT_NAMES}.'))
 24
 25    parser.add_argument('--search-targets', dest = 'search_targets',
 26            action = 'store', type = str, default = None,
 27            help = ('The target squares for the search problem (default: %(default)s).'
 28                    + ' Separate multiple targets with commas (e.g., \'0,42,63\').'))
 29
 30    return parser
 31
 32def init_from_args(args: argparse.Namespace) -> tuple[dict[chessai.core.types.Color, chessai.core.agentinfo.AgentInfo],
 33        list[chessai.core.types.Color], dict[str, typing.Any]]:
 34    """
 35    Setup agents based on King Escort rules.
 36
 37    The solver agent is whichever color has the first move according to the board's FEN (i.e., the side-to-move).
 38    The guard agent is assigned the opposite color so it can attack the king.
 39
 40    If the board hasn't been loaded yet (args.board is still a string or None),
 41    we parse the side-to-move directly from the FEN/board argument so we can
 42    assign colors before the full board object is constructed.
 43    """
 44
 45    solver_color = _detect_solver_color(args)
 46
 47    base_agent_infos: dict[chessai.core.types.Color, chessai.core.agentinfo.AgentInfo] = {
 48        solver_color:            chessai.core.agentinfo.AgentInfo(name = args.agent),
 49        solver_color.opposite(): chessai.core.agentinfo.AgentInfo(name = chessai.util.alias.AGENT_GUARD.short),
 50    }
 51
 52    return base_agent_infos, [], {}
 53
 54def _detect_solver_color(args: argparse.Namespace) -> chessai.core.types.Color:
 55    """
 56    Determine which color is the escort solver (i.e., the side that moves first).
 57    """
 58
 59    board_arg = args.board
 60    if (board_arg is None):
 61        board_arg = DEFAULT_BOARD
 62
 63    board_arg = typing.cast(str, board_arg)
 64
 65    parsed_fen = chessai.escort.parser.parse_escort(board_arg)
 66    return parsed_fen.turn
 67
 68def log_escort_results(results: list[chessai.core.game.GameResult],
 69                       winning_agent_teams: set[chessai.core.types.Color],
 70                       prefix: str = '') -> None:
 71    """
 72    Log the result of running several King Escort games.
 73    """
 74
 75    move_counts: list[int] = [len(result.history) for result in results]
 76    scores: list[float] = [result.score for result in results]
 77
 78    record: list[str] = []
 79    for result in results:
 80        if (result.score > 0):
 81            record.append('Win')
 82        elif (result.score < 0):
 83            record.append('Loss')
 84        else:
 85            record.append('Tie')
 86
 87    average_score: float = (sum(scores)) / len(scores)
 88    logging.info('Average Score: %0.2f', average_score)
 89
 90    # Avoid logging long lists (which can be a bit slow in Python's logging module).
 91    log_lists_to_info: bool = (len(results) < chessai.util.bin.SCORE_LIST_MAX_INFO_LENGTH)
 92    log_lists_to_debug: bool = (logging.getLogger().getEffectiveLevel() <= logging.DEBUG)
 93
 94    joined_scores: str = ''
 95    joined_record: str = ''
 96    joined_move_counts: str = ''
 97
 98    if (log_lists_to_info or log_lists_to_debug):
 99        joined_scores = ', '.join([str(score) for score in scores])
100        joined_record = ', '.join(record)
101        joined_move_counts = ', '.join([str(move_count) for move_count in move_counts])
102
103    if (log_lists_to_info):
104        logging.info('%sScores:        %s', prefix, joined_scores)
105    elif (log_lists_to_debug):
106        logging.debug('%sScores:        %s', prefix, joined_scores)
107
108    if (log_lists_to_info):
109        logging.info('%sRecord:        %s', prefix, joined_record)
110    elif (log_lists_to_debug):
111        logging.debug('%sRecord:        %s', prefix, joined_record)
112
113    logging.info('%sAverage Moves: %s', prefix, sum(move_counts) / float(len(results)))
114
115    if (log_lists_to_info):
116        logging.info('%sMove Counts:   %s', prefix, joined_move_counts)
117    elif (log_lists_to_debug):
118        logging.debug('%sMove Counts:   %s', prefix, joined_move_counts)
119
120def main(argv: list[str] | None = None,
121         ) -> list[chessai.core.game.GameResult]:
122    """
123    Invoke a game of King Escort.
124
125    Will return the results of all of the games.
126    """
127
128    return chessai.util.bin.run_main(
129        description = 'Play a King Escort game.',
130        default_board = DEFAULT_BOARD,
131        game_class = chessai.escort.game.Game,
132        state_class = chessai.escort.gamestate.GameState,
133        custom_set_cli_args = set_cli_args,
134        custom_init_from_args = init_from_args,
135        log_results = log_escort_results,
136        argv = argv,
137    )
138
139if (__name__ == '__main__'):
140    main()
DEFAULT_BOARD: str = 'alcove-demo'
def set_cli_args( parser: argparse.ArgumentParser, **kwargs: Any) -> argparse.ArgumentParser:
16def set_cli_args(parser: argparse.ArgumentParser, **kwargs: typing.Any) -> argparse.ArgumentParser:
17    """
18    Set Escort-specific command-line arguments.
19    """
20
21    parser.add_argument('--agent', dest = 'agent', action = 'store', type = str,
22            default = chessai.util.alias.AGENT_USER_INPUT.short,
23            help = ('Select the Escort agent (default: %(default)s).'
24                    + f' Builtin agents: {chessai.util.alias.AGENT_SHORT_NAMES}.'))
25
26    parser.add_argument('--search-targets', dest = 'search_targets',
27            action = 'store', type = str, default = None,
28            help = ('The target squares for the search problem (default: %(default)s).'
29                    + ' Separate multiple targets with commas (e.g., \'0,42,63\').'))
30
31    return parser

Set Escort-specific command-line arguments.

def init_from_args( args: argparse.Namespace) -> tuple[dict[chessai.core.types.Color, chessai.core.agentinfo.AgentInfo], list[chessai.core.types.Color], dict[str, typing.Any]]:
33def init_from_args(args: argparse.Namespace) -> tuple[dict[chessai.core.types.Color, chessai.core.agentinfo.AgentInfo],
34        list[chessai.core.types.Color], dict[str, typing.Any]]:
35    """
36    Setup agents based on King Escort rules.
37
38    The solver agent is whichever color has the first move according to the board's FEN (i.e., the side-to-move).
39    The guard agent is assigned the opposite color so it can attack the king.
40
41    If the board hasn't been loaded yet (args.board is still a string or None),
42    we parse the side-to-move directly from the FEN/board argument so we can
43    assign colors before the full board object is constructed.
44    """
45
46    solver_color = _detect_solver_color(args)
47
48    base_agent_infos: dict[chessai.core.types.Color, chessai.core.agentinfo.AgentInfo] = {
49        solver_color:            chessai.core.agentinfo.AgentInfo(name = args.agent),
50        solver_color.opposite(): chessai.core.agentinfo.AgentInfo(name = chessai.util.alias.AGENT_GUARD.short),
51    }
52
53    return base_agent_infos, [], {}

Setup agents based on King Escort rules.

The solver agent is whichever color has the first move according to the board's FEN (i.e., the side-to-move). The guard agent is assigned the opposite color so it can attack the king.

If the board hasn't been loaded yet (args.board is still a string or None), we parse the side-to-move directly from the FEN/board argument so we can assign colors before the full board object is constructed.

def log_escort_results( results: list[chessai.core.game.GameResult], winning_agent_teams: set[chessai.core.types.Color], prefix: str = '') -> None:
 69def log_escort_results(results: list[chessai.core.game.GameResult],
 70                       winning_agent_teams: set[chessai.core.types.Color],
 71                       prefix: str = '') -> None:
 72    """
 73    Log the result of running several King Escort games.
 74    """
 75
 76    move_counts: list[int] = [len(result.history) for result in results]
 77    scores: list[float] = [result.score for result in results]
 78
 79    record: list[str] = []
 80    for result in results:
 81        if (result.score > 0):
 82            record.append('Win')
 83        elif (result.score < 0):
 84            record.append('Loss')
 85        else:
 86            record.append('Tie')
 87
 88    average_score: float = (sum(scores)) / len(scores)
 89    logging.info('Average Score: %0.2f', average_score)
 90
 91    # Avoid logging long lists (which can be a bit slow in Python's logging module).
 92    log_lists_to_info: bool = (len(results) < chessai.util.bin.SCORE_LIST_MAX_INFO_LENGTH)
 93    log_lists_to_debug: bool = (logging.getLogger().getEffectiveLevel() <= logging.DEBUG)
 94
 95    joined_scores: str = ''
 96    joined_record: str = ''
 97    joined_move_counts: str = ''
 98
 99    if (log_lists_to_info or log_lists_to_debug):
100        joined_scores = ', '.join([str(score) for score in scores])
101        joined_record = ', '.join(record)
102        joined_move_counts = ', '.join([str(move_count) for move_count in move_counts])
103
104    if (log_lists_to_info):
105        logging.info('%sScores:        %s', prefix, joined_scores)
106    elif (log_lists_to_debug):
107        logging.debug('%sScores:        %s', prefix, joined_scores)
108
109    if (log_lists_to_info):
110        logging.info('%sRecord:        %s', prefix, joined_record)
111    elif (log_lists_to_debug):
112        logging.debug('%sRecord:        %s', prefix, joined_record)
113
114    logging.info('%sAverage Moves: %s', prefix, sum(move_counts) / float(len(results)))
115
116    if (log_lists_to_info):
117        logging.info('%sMove Counts:   %s', prefix, joined_move_counts)
118    elif (log_lists_to_debug):
119        logging.debug('%sMove Counts:   %s', prefix, joined_move_counts)

Log the result of running several King Escort games.

def main(argv: list[str] | None = None) -> list[chessai.core.game.GameResult]:
121def main(argv: list[str] | None = None,
122         ) -> list[chessai.core.game.GameResult]:
123    """
124    Invoke a game of King Escort.
125
126    Will return the results of all of the games.
127    """
128
129    return chessai.util.bin.run_main(
130        description = 'Play a King Escort game.',
131        default_board = DEFAULT_BOARD,
132        game_class = chessai.escort.game.Game,
133        state_class = chessai.escort.gamestate.GameState,
134        custom_set_cli_args = set_cli_args,
135        custom_init_from_args = init_from_args,
136        log_results = log_escort_results,
137        argv = argv,
138    )

Invoke a game of King Escort.

Will return the results of all of the games.