chessai.puzzle.bin

The main executable for running a game of puzzle.

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

Set Puzzle-specific CLI arguments. This is a sibling to init_from_args(), as the arguments set here can be interpreted there.

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]]:
42def init_from_args(args: argparse.Namespace) -> tuple[dict[chessai.core.types.Color, chessai.core.agentinfo.AgentInfo],
43        list[chessai.core.types.Color], dict[str, typing.Any]]:
44    """
45    Setup agents based on Puzzle rules.
46
47    The solver agent is whichever color has the first move according to the board's FEN (i.e., the side-to-move).
48    The dummy agent is assigned the opposite color so it can supply scripted responses.
49
50    If the board hasn't been loaded yet (args.board is still a string or None),
51    we parse the side-to-move directly from the FEN/board argument so we can
52    assign colors before the full board object is constructed.
53    """
54
55    solver_color = _detect_solver_color(args)
56
57    base_agent_infos: dict[chessai.core.types.Color, chessai.core.agentinfo.AgentInfo] = {
58        solver_color:            chessai.core.agentinfo.AgentInfo(name = args.agent),
59        solver_color.opposite(): chessai.core.agentinfo.AgentInfo(name = chessai.util.alias.AGENT_MULTI_SCRIPTED.short),
60    }
61
62    return base_agent_infos, [], {}

Setup agents based on Puzzle rules.

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

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

Log the result of running several Puzzle games.

def main(argv: list[str] | None = None) -> list[chessai.core.game.GameResult]:
128def main(argv: list[str] | None = None,
129         ) -> list[chessai.core.game.GameResult]:
130    """
131    Invoke a game of Puzzle.
132
133    Will return the results of any training games followed by the results of any non-training games.
134    """
135
136    return chessai.util.bin.run_main(
137        description = "Play a game of Puzzle.",
138        default_board = DEFAULT_BOARD,
139        game_class = chessai.puzzle.game.Game,
140        state_class = chessai.puzzle.gamestate.GameState,
141        custom_set_cli_args = set_cli_args,
142        custom_init_from_args = init_from_args,
143        log_results = log_puzzle_results,
144        argv = argv,
145    )

Invoke a game of Puzzle.

Will return the results of any training games followed by the results of any non-training games.