Python chess.BLACK Examples

The following are 30 code examples of chess.BLACK(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module chess , or try the search function .
Example #1
Source File: tensorsketch.py    From fastchess with GNU General Public License v3.0 6 votes vote down vote up
def find_move(self, board, debug=False):
        # Should we flip the board to make sure it always gets it from white?
        vec_board = board_to_vec(
            board if board.turn == chess.WHITE else board.mirror())
        vec_board = tensor_sketch(vec_board, self.sketches)
        probs = self.move_clf.predict_proba([vec_board])[0]
        score = self.score_clf.predict([vec_board])[0]
        for n, (mp, from_to) in enumerate(sorted((-p, ft) for ft, p in enumerate(probs))):
            to_square, from_square = divmod(from_to, 64)
            if board.turn == chess.BLACK:
                from_square = chess.square_mirror(from_square)
                to_square = chess.square_mirror(to_square)
            move = chess.Move(from_square, to_square)
            if move in board.legal_moves:
                print(f'Choice move {n}, p={-mp}')
                return move, score 
Example #2
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def first_turn(self, color: Color = None) -> Turn:
        """
        Gets the first turn of the game.

        Examples:
            >>> history.first_turn()
            Turn(WHITE, 0)

            >>> history.first_turn(WHITE)
            Turn(WHITE, 0)

            >>> history.first_turn(BLACK)
            Turn(BLACK, 0)

        :param color: Optional color indicating which player's first turn to return.
        :return: The :class:`Turn` that is the first turn in the game.
        """
        if self.is_empty():
            raise ValueError('GameHistory is empty')

        return Turn(color if color is not None else chess.WHITE, 0) 
Example #3
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def sense_result(self, turn: Turn) -> List[Tuple[Square, Optional[chess.Piece]]]:
        """
        Get the result of the sense action on the given turn.

        Examples:
            >>> history.sense(Turn(WHITE, 0))
            B7
            >>> history.sense_result(Turn(WHITE, 0))
            [
                (A8, Piece(ROOK, BLACK)), (B8, Piece(KNIGHT, BLACK)), (C8, Piece(BISHOP, BLACK)),
                (A7, Piece(PAWN, BLACK)), (B7, Piece(PAWN, BLACK)), (C7, Piece(PAWN, BLACK)),
                (A6, None), (B6, None), (C8, None)
            ]
            >>> history.sense(Turn(BLACK, 0))
            None
            >>> history.sense_result(Turn(BLACK, 0))
            []

        :param turn: The :class:`Turn` in question.
        :return: The result of the executed sense action.
        """
        self._validate_turn(turn, self._sense_results)
        return self._sense_results[turn.color][turn.turn_number] 
Example #4
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def requested_move(self, turn: Turn) -> Optional[chess.Move]:
        """
        Get the requested move action on the given turn.

        Examples:
            >>> history.requested_move(Turn(WHITE, 0))
            Move(E2, E4)

            >>> history.requested_move(Turn(BLACK, 0))
            Move(E7, E5)

            >>> history.requested_move(Turn(WHITE, 1))
            None

        :param turn: The :class:`Turn` in question.
        :return: If the player requested to move, then the requested move action as a :class:`chess.Move`, otherwise
            `None` if the player requested to pass.
        """
        self._validate_turn(turn, self._requested_moves)
        return self._requested_moves[turn.color][turn.turn_number] 
Example #5
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def truth_fen_before_move(self, turn: Turn) -> str:
        """
        Get the truth state of the board as a fen string before the move was executed on the given turn. Use
        :meth:`truth_board_before_move` if you want the truth board as a :class:`chess.Board` object.

        Examples:
            >>> history.truth_fen_before_move(Turn(WHITE, 0))
            "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -"
            >>> history.taken_move(Turn(WHITE, 0))
            Move(E2, E4)
            >>> history.truth_fen_before_move(Turn(BLACK, 0))
            "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq -"

        :param turn: The :class:`Turn` in question.
        :return: The fen of the truth board.
        """
        self._validate_turn(turn, self._fens_before_move)
        return self._fens_before_move[turn.color][turn.turn_number] 
Example #6
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def truth_board_before_move(self, turn: Turn) -> chess.Board:
        """
        Get the truth state of the board as a :class:`chess.Board` before the move was executed on the given turn. Use
        :meth:`truth_fen_before_move` if you want the truth board as a fen string.

        Examples:
            >>> history.truth_board_before_move(Turn(WHITE, 0))
            Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -")
            >>> history.taken_move(Turn(WHITE, 0))
            Move(E2, E4)
            >>> history.truth_fen_before_move(Turn(BLACK, 0))
            Board("rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq -")

        :param turn: The :class:`Turn` in question.
        :return: A :class:`chess.Board` object.
        """
        self._validate_turn(turn, self._fens_before_move)
        board = chess.Board(self._fens_before_move[turn.color][turn.turn_number])
        board.turn = turn.color
        return board 
Example #7
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def collect(self, get_turn_data_fn: Callable[[Turn], T], turns: Iterable[Turn]) -> Iterable[T]:
        """
        Collect data from multiple turns using any of :meth:`sense`, :meth:`sense_result`, :meth:`requested_move`,
        :meth:`taken_move`, :meth:`capture_square`, :meth:`move_result`, :meth:`truth_fen_before_move`,
        :meth:`truth_board_before_move`, :meth:`truth_fen_after_move`, or :meth:`truth_board_after_move`.

        Examples:
            >>> history.collect(history.sense, [Turn(WHITE, 0), Turn(BLACK, 0)])
            [E7, E2]

            >>> history.collect(history.requested_move, history.turns(WHITE))
            [Move(E2, E4), Move(D1, H5), ...]

        :param get_turn_data_fn: One of the getter functions of the history object.
        :param turns: The turns in question.
        :return: A list of the data, where each element is the value of the getter function on the corresponding turn.
        """
        if get_turn_data_fn not in [self.sense, self.sense_result, self.requested_move, self.taken_move,
                                    self.capture_square, self.move_result, self.truth_board_before_move,
                                    self.truth_board_after_move, self.truth_fen_before_move, self.truth_fen_after_move]:
            raise ValueError('get_turn_data_fn must be one of the history getter functions')
        for turn in turns:
            yield get_turn_data_fn(turn) 
Example #8
Source File: timecontrol.py    From picochess with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, mode=TimeMode.FIXED, fixed=0, blitz=0, fischer=0, internal_time=None):
        super(TimeControl, self).__init__()
        self.mode = mode
        self.move_time = fixed
        self.game_time = blitz
        self.fisch_inc = fischer
        self.internal_time = internal_time

        self.clock_time = {chess.WHITE: 0, chess.BLACK: 0}  # saves the sended clock time for white/black
        self.timer = None
        self.run_color = None
        self.active_color = None
        self.start_time = None

        if internal_time:  # preset the clock (received) time already
            self.clock_time[chess.WHITE] = int(internal_time[chess.WHITE])
            self.clock_time[chess.BLACK] = int(internal_time[chess.BLACK])
        else:
            self.reset() 
Example #9
Source File: proc.py    From fastchess with GNU General Public License v3.0 6 votes vote down vote up
def binary_encode(board):
    """ Returns the board as a binary vector, for eval prediction purposes. """
    rows = []
    for color in [chess.WHITE, chess.BLACK]:
        for ptype in range(chess.PAWN, chess.KING + 1):
            mask = board.pieces_mask(ptype, color)
            rows.append(list(map(int, bin(mask)[2:].zfill(64))))
    ep = [0] * 64
    if board.ep_square:
        ep[board.ep_square] = 1
    rows.append(ep)
    rows.append([
        int(board.turn),
        int(bool(board.castling_rights & chess.BB_A1)),
        int(bool(board.castling_rights & chess.BB_H1)),
        int(bool(board.castling_rights & chess.BB_A8)),
        int(bool(board.castling_rights & chess.BB_H8)),
        int(board.is_check())
    ])
    return np.concatenate(rows) 
Example #10
Source File: board.py    From chs with MIT License 5 votes vote down vote up
def get_title_from_move(self, turn):
    player = '{} to move'.format('Black' if turn == 'b' else 'White')
    colors = '{}'.format(\
      Colors.Backgrounds.BLACK + Colors.LIGHT if turn == 'b' else\
      Colors.Backgrounds.WHITE + Colors.DARK)
    return '\n\n {}{}  {}  {}'\
      .format(Styles.PADDING_MEDIUM, colors, player, Colors.RESET) 
Example #11
Source File: play.py    From twitchchess with MIT License 5 votes vote down vote up
def value(self, s):
    b = s.board
    # game over values
    if b.is_game_over():
      if b.result() == "1-0":
        return MAXVAL
      elif b.result() == "0-1":
        return -MAXVAL
      else:
        return 0

    val = 0.0
    # piece values
    pm = s.board.piece_map()
    for x in pm:
      tval = self.values[pm[x].piece_type]
      if pm[x].color == chess.WHITE:
        val += tval
      else:
        val -= tval

    # add a number of legal moves term
    bak = b.turn
    b.turn = chess.WHITE
    val += 0.1 * b.legal_moves.count()
    b.turn = chess.BLACK
    val -= 0.1 * b.legal_moves.count()
    b.turn = bak

    return val 
Example #12
Source File: pgn_to_records.py    From Zerofish with MIT License 5 votes vote down vote up
def run_game (game):
    # Initialize memory
    actions = []
    policies = []
    indices = []

    # Run through game
    node = game
    board = chess.Board()
    while not node.is_end():
        next_node = node.variation(0)
        move = next_node.move

        # Get action taken and action list
        action = adapter.move_to_label_flat(move)
        legal_actions = map(adapter.move_to_label_flat, board.legal_moves)

        # Create one-hot probability vector
        index = legal_actions.index(action)
        probs = util.one_hot(index, len(legal_actions))

        assert board.is_legal(move)

        # TODO: Look at the validity of this in case of underpromotion
        board.push(move)
        node = next_node

        # Update memory
        actions.append(action)
        policies.append(probs)
        indices.append(legal_actions)

    # Get game winner
    winner, outcome = {
        '1/2-1/2' : (chess.WHITE, 0.0),
        '1-0' : (chess.WHITE, 1.0),
        '0-1' : (chess.BLACK, 1.0)
    }.get(game.headers['Result'], None)

    return actions, policies, indices, outcome, winner 
Example #13
Source File: leastsq.py    From fastchess with GNU General Public License v3.0 5 votes vote down vote up
def print_tables(w):
    for i, color in enumerate([chess.WHITE, chess.BLACK]):
        for j, ptype in enumerate(range(chess.PAWN, chess.KING + 1)):
            table = w[j * 64 + i * 64 * 6:(j + 1) * 64 + i * 64 * 6].reshape(8, 8)
            print(chess.Piece(ptype, color))
            if add_counts:
                print('Val:', w[12 * 64 + 6 * i + j])
            print(table.round(2)) 
Example #14
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def last_turn(self, color: Color = None) -> Turn:
        """
        Gets the last turn of the game.

        Examples:
            >>> history.last_turn()
            Turn(WHITE, 24)

            >>> history.first_turn(WHITE)
            Turn(WHITE, 24)

            >>> history.first_turn(BLACK)
            Turn(BLACK, 23)

        :param color: Optional color indicating which player's last turn to return.
        :return: The :class:`Turn` that is the last turn in the game.
        """
        if self.is_empty():
            raise ValueError('GameHistory is empty')

        if color is not None:
            return Turn(color, len(self._senses[color]) - 1)
        else:
            num_white_turns = len(self._senses[chess.WHITE])
            num_black_turns = len(self._senses[chess.BLACK])
            if num_white_turns > num_black_turns:
                return Turn(chess.WHITE, num_white_turns - 1)
            else:
                return Turn(chess.BLACK, num_black_turns - 1) 
Example #15
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_last_turn(self, turn: Turn):
        """
        Checks whether `turn` is the last turn of the game.

        Examples:
            >>> history.is_last_turn(Turn(BLACK, 23))
            False

            >>> history.is_last_turn(Turn(WHITE, 24))
            True

        :param turn: the :class:`Turn` in question.
        :return: `True` if `turn` is the last turn in the game, `False` otherwise.
        """
        return turn == self.last_turn() 
Example #16
Source File: adapter.py    From Zerofish with MIT License 5 votes vote down vote up
def position_to_chw (position):
    """Returns all model input feature planes from position in chw format."""
    # Piece boards
    occupancies = [
        position.pawns,   position.knights,
        position.bishops, position.rooks,
        position.queens,  position.kings
    ]

    # Full piece boards for each color
    occupancies = map(chess.SquareSet, occupancies)
    colors = map(chess.SquareSet, position.occupied_co)

    # Color specific piece boards
    occupancies_black = map(lambda bb : bb & colors[chess.BLACK], occupancies)
    occupancies_white = map(lambda bb : bb & colors[chess.WHITE], occupancies)

    squaresets = (
        occupancies +
        colors +
        occupancies_black +
        occupancies_white
    )

    squares = map(list, squaresets)
    bbs = map(squares_to_bb, squares)
    bbs = np.array(bbs, dtype=np.byte)

    bool_bbs = position_to_bool_bbs(position)

    bbs_chw = np.concatenate (
        [
            bbs,
            bool_bbs
        ],
        axis = 0
    )

    return bbs_chw 
Example #17
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_first_turn(self, turn: Turn):
        """
        Checks whether `turn` is the first turn of the game.

        Examples:
            >>> history.is_first_turn(Turn(BLACK, 0))
            False

            >>> history.is_first_turn(Turn(WHITE, 0))
            True

        :param turn: the :class:`Turn` in question.
        :return: `True` if `turn` is the first turn in the game, `False` otherwise.
        """
        return turn == self.first_turn() 
Example #18
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        self._white_name = None
        self._black_name = None
        self._senses = {chess.WHITE: [], chess.BLACK: []}
        self._sense_results = {chess.WHITE: [], chess.BLACK: []}
        self._requested_moves = {chess.WHITE: [], chess.BLACK: []}
        self._taken_moves = {chess.WHITE: [], chess.BLACK: []}
        self._capture_squares = {chess.WHITE: [], chess.BLACK: []}
        self._fens_before_move = {chess.WHITE: [], chess.BLACK: []}
        self._fens_after_move = {chess.WHITE: [], chess.BLACK: []}
        self._winner_color = None
        self._win_reason = None 
Example #19
Source File: rc_playback.py    From reconchess with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('game_history_path', help='Path to game history JSON file.')
    parser.add_argument('bot_path', help='The path to bot source file or module.')
    parser.add_argument('color', default='random', choices=['white', 'black'],
                        help='The color of the player to playback.')
    args = parser.parse_args()

    game_history = GameHistory.from_file(args.game_history_path)
    white_bot_name, white_player_cls = load_player(args.bot_path)
    color = chess.WHITE if args.color == 'white' else chess.BLACK

    playback(game_history, white_player_cls(), color) 
Example #20
Source File: rc_play_on_server.py    From reconchess with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--color', default='random', choices=['white', 'black', 'random'],
                        help='The color you want to play as.')
    parser.add_argument('--server-url', default='https://rbc.jhuapl.edu', help='URL of the server.')
    args = parser.parse_args()

    auth = ask_for_auth()

    server = RBCServer(args.server_url, auth)

    usernames = server.get_active_users()

    if auth[0] in usernames:
        usernames.remove(auth[0])

    if len(usernames) == 0:
        print('No active users.')
        quit()

    for i, username in enumerate(usernames):
        print('[{}] {}'.format(i, username))
    i = int(input('Choose opponent: '))

    color = chess.WHITE
    if args.color == 'black' or (args.color == 'random' and random.uniform(0, 1) < 0.5):
        color = chess.BLACK

    game_id = server.send_invitation(usernames[i], color)

    winner_color, win_reason, game_history = play_remote_game(args.server_url, game_id, auth, UIPlayer())

    winner = 'Draw' if winner_color is None else chess.COLOR_NAMES[winner_color]
    timestamp = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
    game_history.save('{}_{}_{}.json'.format(timestamp, game_id, winner)) 
Example #21
Source File: play.py    From reconchess with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def play_local_game(white_player: Player, black_player: Player, game: LocalGame = None,
                    seconds_per_player: float = 900) -> Tuple[Optional[Color], Optional[WinReason], GameHistory]:
    """
    Plays a game between the two players passed in. Uses :class:`LocalGame` to run the game, and just calls
    :func:`play_turn` until the game is over: ::

        while not game.is_over():
            play_turn(game, player)

    :param white_player: The white :class:`Player`.
    :param black_player: The black :class:`Player`.
    :param game: The :class:`LocalGame` object to use.
    :param seconds_per_player: The time each player has to play. Only used if `game` is not passed in.
    :return: The results of the game, also passed to each player via :meth:`Player.handle_game_end`.
    """
    players = [black_player, white_player]

    if game is None:
        game = LocalGame(seconds_per_player=seconds_per_player)

    white_name = white_player.__class__.__name__
    black_name = black_player.__class__.__name__
    game.store_players(white_name, black_name)

    white_player.handle_game_start(chess.WHITE, game.board.copy(), black_name)
    black_player.handle_game_start(chess.BLACK, game.board.copy(), white_name)
    game.start()

    while not game.is_over():
        play_turn(game, players[game.turn], end_turn_last=True)

    game.end()
    winner_color = game.get_winner_color()
    win_reason = game.get_win_reason()
    game_history = game.get_game_history()

    white_player.handle_game_end(winner_color, win_reason, game_history)
    black_player.handle_game_end(winner_color, win_reason, game_history)

    return winner_color, win_reason, game_history 
Example #22
Source File: player.py    From reconchess with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def handle_game_start(self, color: Color, board: chess.Board, opponent_name: str):
        """
        Provides a place to initialize game wide structures like boards, and initialize data that depends on what
        color you are playing as.

        Called when the game starts.

        The board is provided to allow starting a game from different board positions.

        :param color: The color that you are playing as. Either :data:`chess.WHITE` or :data:`chess.BLACK`.
        :param board: The initial board of the game. See :class:`chess.Board`.
        :param opponent_name: The name of your opponent.
        """
        pass 
Example #23
Source File: display.py    From picochess with GNU General Public License v3.0 5 votes vote down vote up
def _process_new_score(self, message):
        if message.mate is None:
            score = int(message.score)
            if message.turn == chess.BLACK:
                score *= -1
            text = self.dgttranslate.text('N10_score', score)
        else:
            text = self.dgttranslate.text('N10_mate', str(message.mate))
        self.score = text
        if message.mode == Mode.KIBITZ and not self._inside_main_menu():
            text = self._combine_depth_and_score()
            text.wait = True
            DispatchDgt.fire(text) 
Example #24
Source File: timecontrol.py    From picochess with GNU General Public License v3.0 5 votes vote down vote up
def uci(self):
        """Return remaining time for both players in an UCI dict."""
        uci_dict = {}
        if self.mode in (TimeMode.BLITZ, TimeMode.FISCHER):
            uci_dict['wtime'] = str(int(self.internal_time[chess.WHITE] * 1000))
            uci_dict['btime'] = str(int(self.internal_time[chess.BLACK] * 1000))

            if self.mode == TimeMode.FISCHER:
                uci_dict['winc'] = str(self.fisch_inc * 1000)
                uci_dict['binc'] = str(self.fisch_inc * 1000)
        elif self.mode == TimeMode.FIXED:
            uci_dict['movetime'] = str(self.move_time * 1000)

        return uci_dict 
Example #25
Source File: timecontrol.py    From picochess with GNU General Public License v3.0 5 votes vote down vote up
def _out_of_time(self, time_start):
        """Fire an OUT_OF_TIME event."""
        self.run_color = None
        if self.mode == TimeMode.FIXED:
            logging.debug('timeout - but in "MoveTime" mode, dont fire event')
        elif self.active_color is not None:
            display_color = 'WHITE' if self.active_color == chess.WHITE else 'BLACK'
            txt = 'current clock time (before subtracting) is %f and color is %s, out of time event started from %f'
            logging.debug(txt, self.internal_time[self.active_color], display_color, time_start)
            Observable.fire(Event.OUT_OF_TIME(color=self.active_color)) 
Example #26
Source File: timecontrol.py    From picochess with GNU General Public License v3.0 5 votes vote down vote up
def set_clock_times(self, white_time: int, black_time: int):
        """Set the times send from the clock."""
        logging.info('set clock times w:%s b:%s', hms_time(white_time), hms_time(black_time))
        self.clock_time[chess.WHITE] = white_time
        self.clock_time[chess.BLACK] = black_time 
Example #27
Source File: timecontrol.py    From picochess with GNU General Public License v3.0 5 votes vote down vote up
def get_internal_time(self, flip_board=False):
        """Return the startup time for setting the clock at beginning."""
        i_time = copy.copy(self.internal_time)
        if flip_board:
            i_time[chess.WHITE], i_time[chess.BLACK] = i_time[chess.BLACK], i_time[chess.WHITE]
        return int(i_time[chess.WHITE]), int(i_time[chess.BLACK]) 
Example #28
Source File: timecontrol.py    From picochess with GNU General Public License v3.0 5 votes vote down vote up
def reset(self):
        """Reset the clock's times for both players."""
        if self.mode == TimeMode.BLITZ:
            self.clock_time[chess.WHITE] = self.clock_time[chess.BLACK] = self.game_time * 60

        elif self.mode == TimeMode.FISCHER:
            self.clock_time[chess.WHITE] = self.clock_time[chess.BLACK] = self.game_time * 60 + self.fisch_inc

        elif self.mode == TimeMode.FIXED:
            self.clock_time[chess.WHITE] = self.clock_time[chess.BLACK] = self.move_time

        self.internal_time = {chess.WHITE: float(self.clock_time[chess.WHITE]),
                              chess.BLACK: float(self.clock_time[chess.BLACK])}
        self.active_color = None 
Example #29
Source File: arena.py    From fastchess with GNU General Public License v3.0 5 votes vote down vote up
def run_games(self, book, game_id=0, games_played=2):
        score = 0
        games = []
        assert games_played % 2 == 0
        for r in range(games_played//2):
            init_board = random.choice(book)
            for color in [WHITE, BLACK]:
                white, black = (self.enginea, self.engineb) if color == WHITE \
                    else (self.engineb, self.enginea)
                game_round = games_played * game_id + color + 2*r
                game = chess.pgn.Game({
                    'Event': 'Tune.py',
                    'White': white.id['name'],
                    'WhiteArgs': repr(white.id['args']),
                    'Black': black.id['name'],
                    'BlackArgs': repr(black.id['args']),
                    'Round': game_round
                })
                games.append(game)
                # Add book moves
                game.setup(init_board.root())
                node = game
                for move in init_board.move_stack:
                    node = node.add_variation(move, comment='book')
                # Run engines
                async for _play, er in self.play_game(node, game_round, white, black):
                    # If an error occoured, return as much as we got
                    if er is not None:
                        return games, score, er
                result = game.headers["Result"]
                if result == '1-0' and color == WHITE or result == '0-1' and color == BLACK:
                    score += 1
                if result == '1-0' and color == BLACK or result == '0-1' and color == WHITE:
                    score -= 1
        return games, score/games_played, None 
Example #30
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def turns(self, color: Color = None, start=0, stop=math.inf) -> Iterable[Turn]:
        """
        Get all the turns that happened in the game in order. Optionally specify a single player to get only that
        player's turns.

        Examples:
            >>> list(history.turns())
            [Turn(WHITE, 0), Turn(BLACK, 0), Turn(WHITE, 1), ..., Turn(BLACK, 23)]

            >>> list(history.turns(WHITE))
            [Turn(WHITE, 0), Turn(WHITE, 1), ..., Turn(WHITE, 22)]

            >>> list(history.turns(BLACK))
            [Turn(BLACK, 0), Turn(BLACK, 1), ..., Turn(BLACK, 23)]

            >>> list(history.turns(start=1))
            [Turn(WHITE, 1), Turn(BLACK, 1), Turn(WHITE, 2), ..., Turn(BLACK, 23)]

            >>> list(history.turns(stop=2))
            [Turn(WHITE, 0), Turn(BLACK, 0), Turn(WHITE, 1), Turn(BLACK, 1)]

            >>> list(history.turns(WHITE, stop=2))
            [Turn(WHITE, 0), Turn(WHITE, 1)]

            >>> list(history.turns(start=1, stop=2))
            [Turn(WHITE, 1), Turn(BLACK, 1)]

        :param color: Optional player color indicating which player's turns to return.
        :param start: Optional starting turn number.
        :param stop: Optional stopping turn number.
        :return: An iterable of :class:`Turn` objects that are in the same order as they occurred in the game. If
            `color` is specified, gets the turns only for that player.
        """
        if self.is_empty():
            return

        turn = Turn(color if color is not None else chess.WHITE, start)
        stop_turn = Turn(color if color is not None else chess.WHITE, stop)
        last_turn = self.last_turn()
        while turn <= last_turn and turn < stop_turn:
            if color is None or turn.color == color:
                yield turn
            turn = turn.next