Python chess.Board() Examples

The following are 30 code examples of chess.Board(). 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: server.py    From picochess with GNU General Public License v3.0 6 votes vote down vote up
def process_console_command(self, raw):
        cmd = raw.lower()

        try:
            # Here starts the simulation of a dgt-board!
            # Let the user send events like the board would do
            if cmd.startswith('fen:'):
                fen = raw.split(':')[1].strip()
                # dgt board only sends the basic fen => be sure it's same no matter what fen the user entered
                fen = fen.split(' ')[0]
                bit_board = chess.Board()  # valid the fen
                bit_board.set_board_fen(fen)
                Observable.fire(Event.KEYBOARD_FEN(fen=fen))
            # end simulation code
            elif cmd.startswith('go'):
                if 'last_dgt_move_msg' in self.shared:
                    fen = self.shared['last_dgt_move_msg']['fen'].split(' ')[0]
                    Observable.fire(Event.KEYBOARD_FEN(fen=fen))
            else:
                # Event.KEYBOARD_MOVE tranfers "move" to "fen" and then continues with "Message.DGT_FEN"
                move = chess.Move.from_uci(cmd)
                Observable.fire(Event.KEYBOARD_MOVE(move=move))
        except (ValueError, IndexError):
            logging.warning('Invalid user input [%s]', raw) 
Example #2
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 #3
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def truth_board_after_move(self, turn: Turn) -> chess.Board:
        """
        Get the truth state of the board as a :class:`chess.Board` after the move was executed on the given turn. Use
        :meth:`truth_fen_after_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_after_move(Turn(WHITE, 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_after_move)
        board = chess.Board(self._fens_after_move[turn.color][turn.turn_number])
        board.turn = turn.color
        return board 
Example #4
Source File: utilities.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def default(self, o):
        if isinstance(o, chess.Piece):
            return {
                'type': 'Piece',
                'value': o.symbol(),
            }
        elif isinstance(o, chess.Move):
            return {
                'type': 'Move',
                'value': o.uci(),
            }
        elif isinstance(o, chess.Board):
            return {
                'type': 'Board',
                'value': o.fen(),
            }
        elif isinstance(o, WinReason):
            return {
                'type': 'WinReason',
                'value': o.name,
            }
        return super().default(o) 
Example #5
Source File: utilities.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pawn_capture_moves_on(board: chess.Board) -> List[chess.Move]:
    """Generates all pawn captures on `board`, even if there is no piece to capture. All promotion moves are included."""
    pawn_capture_moves = []

    no_opponents_board = without_opponent_pieces(board)

    for pawn_square in board.pieces(chess.PAWN, board.turn):
        for attacked_square in board.attacks(pawn_square):
            # skip this square if one of our own pieces are on the square
            if no_opponents_board.piece_at(attacked_square):
                continue

            pawn_capture_moves.append(chess.Move(pawn_square, attacked_square))

            # add in promotion moves
            if attacked_square in chess.SquareSet(chess.BB_BACKRANKS):
                for piece_type in chess.PIECE_TYPES[1:-1]:
                    pawn_capture_moves.append(chess.Move(pawn_square, attacked_square, promotion=piece_type))

    return pawn_capture_moves 
Example #6
Source File: utilities.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def is_illegal_castle(board: chess.Board, move: chess.Move) -> bool:
    if not board.is_castling(move):
        return False

    # illegal without kingside rights
    if board.is_kingside_castling(move) and not board.has_kingside_castling_rights(board.turn):
        return True

    # illegal without queenside rights
    if board.is_queenside_castling(move) and not board.has_queenside_castling_rights(board.turn):
        return True

    # illegal if any pieces are between king & rook
    rook_square = chess.square(7 if board.is_kingside_castling(move) else 0, chess.square_rank(move.from_square))
    between_squares = chess.SquareSet(chess.between(move.from_square, rook_square))
    if any(map(lambda s: board.piece_at(s), between_squares)):
        return True

    # its legal
    return False 
Example #7
Source File: chessbot.py    From python-zulip-api with Apache License 2.0 6 votes vote down vote up
def start(self, message: Dict[str, str], bot_handler: Any) -> None:
        """Starts a game with another user, with the current user as white.
        Replies to the bot handler.

        Parameters:
             - message: The Zulip Bots message object.
             - bot_handler: The Zulip Bots bot handler object.
        """
        new_board = chess.Board()
        bot_handler.send_reply(
            message,
            make_start_reponse(new_board)
        )

        # `bot_handler`'s `storage` only accepts `str` values.
        bot_handler.storage.put('is_with_computer', str(False))

        bot_handler.storage.put('last_fen', new_board.fen()) 
Example #8
Source File: picochess.py    From picochess with GNU General Public License v3.0 6 votes vote down vote up
def book(self, bookreader, game_copy: chess.Board):
        """Get a BookMove or None from game position."""
        try:
            choice = bookreader.weighted_choice(game_copy, self.excludemoves)
        except IndexError:
            return None

        book_move = choice.move()
        self.add(book_move)
        game_copy.push(book_move)
        try:
            choice = bookreader.weighted_choice(game_copy)
            book_ponder = choice.move()
        except IndexError:
            book_ponder = None
        return chess.uci.BestMove(book_move, book_ponder) 
Example #9
Source File: iface.py    From picochess with GNU General Public License v3.0 6 votes vote down vote up
def get_san(self, message, is_xl=False):
        """Create a chess.board plus a text ready to display on clock."""

        def move(text: str, language: str, capital: bool, short: bool):
            """Return move text for clock display."""
            if short:
                directory = {}
                if language == 'de':
                    directory = {'R': 'T', 'N': 'S', 'B': 'L', 'Q': 'D'}
                if language == 'nl':
                    directory = {'R': 'T', 'N': 'P', 'B': 'L', 'Q': 'D'}
                if language == 'fr':
                    directory = {'R': 'T', 'N': 'C', 'B': 'F', 'Q': 'D', 'K': '@'}
                if language == 'es':
                    directory = {'R': 'T', 'N': 'C', 'B': 'A', 'Q': 'D', 'K': '@'}
                if language == 'it':
                    directory = {'R': 'T', 'N': 'C', 'B': 'A', 'Q': 'D', 'K': '@'}
                for i, j in directory.items():
                    text = text.replace(i, j)
                text = text.replace('@', 'R')  # replace the King "@" from fr, es, it languages
            if capital:
                return text.upper()
            else:
                return text

        bit_board = Board(message.fen, message.uci960)
        if bit_board.is_legal(message.move):
            if message.long:
                move_text = message.move.uci()
            else:
                move_text = bit_board.san(message.move)
        else:
            logging.warning('[%s] illegal move %s found - uci960: %s fen: %s', self.get_name(), message.move,
                            message.uci960, message.fen)
            move_text = 'er{}' if is_xl else 'err {}'
            move_text = move_text.format(message.move.uci()[:4])

        if message.side == ClockSide.RIGHT:
            move_text = move_text.rjust(6 if is_xl else 8)
        return bit_board, move(move_text, message.lang, message.capital and not is_xl, not message.long) 
Example #10
Source File: chessbot.py    From python-zulip-api with Apache License 2.0 6 votes vote down vote up
def make_loss_response(board: chess.Board, reason: str) -> str:
    """Makes a response string for a loss (or win).

    Parameters:
         - board: The board object at the end of the game.
         - reason: The reason for the loss, in the form of a predicate, e.g.,
                   'was checkmated'.

    Returns: The loss response string.
    """
    return (
        '*{}* {}. **{}** wins!\n\n'
        '{}'
    ).format(
        'White' if board.turn else 'Black',
        reason,
        'Black' if board.turn else 'White',
        make_str(board, board.turn)
    ) 
Example #11
Source File: chessbot.py    From python-zulip-api with Apache License 2.0 6 votes vote down vote up
def make_not_legal_response(board: chess.Board, move_san: str) -> str:
    """Makes a response string for a not-legal move.

    Parameters:
         - board: The board object before the move.
         - move_san: The SAN of the not-legal move.

    Returns: The not-legal-move response string.
    """
    return (
        'Sorry, the move *{}* isn\'t legal.\n\n'
        '{}'
        '\n\n\n'
        '{}'
    ).format(
        move_san,
        make_str(board, board.turn),
        make_footer()
    ) 
Example #12
Source File: chessbot.py    From python-zulip-api with Apache License 2.0 6 votes vote down vote up
def make_start_reponse(board: chess.Board) -> str:
    """Makes a response string for the first response of a game with another
    user.

    Parameters:
         - board: The board object to start the game with (which most-likely
                  should be general opening chess position).

    Returns: The starting response string.
    """
    return (
        'New game! The board looks like this:\n\n'
        '{}'
        '\n\n\n'
        'Now it\'s **{}**\'s turn.'
        '\n\n\n'
        '{}'
    ).format(
        make_str(board, True),
        'white' if board.turn else 'black',
        make_footer()
    ) 
Example #13
Source File: test_functions.py    From python-chess-annotator with GNU General Public License v3.0 6 votes vote down vote up
def test_eco_json(self):
        ecopath = os.path.join(
            os.path.dirname(__file__), '../annotator/eco/eco.json'
        )
        with open(ecopath, 'r') as ecofile:
            ecodata = json.load(ecofile)

            for row in ecodata:
                fen = "{} {}".format(row["f"], '- 0 1')
                chess.Board(fen=fen)

                classification = annotator.classify_fen(row["f"], ecodata)

                assert classification["code"] == row["c"]
                assert classification["desc"] == row["n"]
                assert classification["path"] == row["m"] 
Example #14
Source File: test_functions.py    From python-chess-annotator with GNU General Public License v3.0 6 votes vote down vote up
def test_long_mating_pv(self):
        """ A long pv that ends the game should not be truncated """

        board = chess.Board('1Q3bk1/5p2/2p3p1/1p1bN2p/4n2P/8/r5PK/8 b - - 1 34')  # noqa E501
        line = [chess.Move.from_uci('g8g7'), chess.Move.from_uci('e5f7'),
                chess.Move.from_uci('d5f7'), chess.Move.from_uci('b8e5'),
                chess.Move.from_uci('e4f6'), chess.Move.from_uci('h2h3'),
                chess.Move.from_uci('b5b4'), chess.Move.from_uci('g2g4'),
                chess.Move.from_uci('f8d6'), chess.Move.from_uci('e5d6'),
                chess.Move.from_uci('h5g4'), chess.Move.from_uci('h3g3'),
                chess.Move.from_uci('f6e4'), chess.Move.from_uci('g3f4'),
                chess.Move.from_uci('e4d6'), chess.Move.from_uci('f4e5'),
                chess.Move.from_uci('b4b3'), chess.Move.from_uci('e5d6'),
                chess.Move.from_uci('b3b2'), chess.Move.from_uci('h4h5'),
                chess.Move.from_uci('g6h5'), chess.Move.from_uci('d6d7'),
                chess.Move.from_uci('b2b1q'), chess.Move.from_uci('d7c7'),
                chess.Move.from_uci('b1b4'), chess.Move.from_uci('c7c6'),
                chess.Move.from_uci('a2c2'), chess.Move.from_uci('c6d7'),
                chess.Move.from_uci('b4b8'), chess.Move.from_uci('d7e7'),
                chess.Move.from_uci('b8c7')]
        result = annotator.truncate_pv(board, line)
        self.assertEqual(result, line) 
Example #15
Source File: test_functions.py    From python-chess-annotator with GNU General Public License v3.0 6 votes vote down vote up
def test_long_non_mating_pv(self):
        """
        A long pv that does not end the game should be truncated to 10 moves
        """

        board = chess.Board('1Q3bk1/5p2/2p3p1/1p1bN2p/4n2P/8/r5PK/8 b - - 1 34')  # noqa E501
        line = [chess.Move.from_uci('g8g7'), chess.Move.from_uci('e5f7'),
                chess.Move.from_uci('d5f7'), chess.Move.from_uci('b8e5'),
                chess.Move.from_uci('e4f6'), chess.Move.from_uci('h2h3'),
                chess.Move.from_uci('b5b4'), chess.Move.from_uci('g2g4'),
                chess.Move.from_uci('f8d6'), chess.Move.from_uci('e5d6'),
                chess.Move.from_uci('h5g4'), chess.Move.from_uci('h3g3'),
                chess.Move.from_uci('f6e4'), chess.Move.from_uci('g3f4'),
                chess.Move.from_uci('e4d6'), chess.Move.from_uci('f4e5'),
                chess.Move.from_uci('b4b3'), chess.Move.from_uci('e5d6'),
                chess.Move.from_uci('b3b2'), chess.Move.from_uci('h4h5'),
                chess.Move.from_uci('g6h5'), chess.Move.from_uci('d6d7'),
                chess.Move.from_uci('b2b1q'), chess.Move.from_uci('d7c7'),
                chess.Move.from_uci('b1b4'), chess.Move.from_uci('c7c6'),
                chess.Move.from_uci('a2c2'), chess.Move.from_uci('c6d7'),
                chess.Move.from_uci('b4b8'), chess.Move.from_uci('d7e7')]
        target = line[:annotator.SHORT_PV_LEN]
        result = annotator.truncate_pv(board, line)
        self.assertEqual(len(result), annotator.SHORT_PV_LEN)
        self.assertEqual(result, target) 
Example #16
Source File: test_functions.py    From python-chess-annotator with GNU General Public License v3.0 6 votes vote down vote up
def test_raises_assertionerror(self):
        """ A line with an illegal move should raise an AssertionError """

        board = chess.Board('1Q3bk1/5p2/2p3p1/1p1bN2p/4n2P/8/r5PK/8 b - - 1 34')  # noqa E501
        line = [chess.Move.from_uci('g8g7'), chess.Move.from_uci('e5f7'),
                chess.Move.from_uci('d5f7'), chess.Move.from_uci('b8e5'),
                chess.Move.from_uci('e4f6'), chess.Move.from_uci('h2h3'),
                chess.Move.from_uci('b5b4'), chess.Move.from_uci('g2g4'),
                chess.Move.from_uci('f8d6'), chess.Move.from_uci('e5d6'),
                chess.Move.from_uci('h5g4'), chess.Move.from_uci('h3g3'),
                chess.Move.from_uci('f6e4'), chess.Move.from_uci('g3f4'),
                chess.Move.from_uci('e4d6'), chess.Move.from_uci('f4e5'),
                chess.Move.from_uci('b4b3'), chess.Move.from_uci('e5d6'),
                chess.Move.from_uci('b3b2'), chess.Move.from_uci('h4h5'),
                chess.Move.from_uci('g6h5'), chess.Move.from_uci('d6c8'),
                chess.Move.from_uci('b2b1q'), chess.Move.from_uci('d7c7'),
                chess.Move.from_uci('b1b4'), chess.Move.from_uci('c7c6'),
                chess.Move.from_uci('a2c2'), chess.Move.from_uci('c6d7'),
                chess.Move.from_uci('b4b8'), chess.Move.from_uci('d7e7'),
                chess.Move.from_uci('b8c7')]
        self.assertRaises(AssertionError, annotator.truncate_pv, board, line) 
Example #17
Source File: chessbot.py    From python-zulip-api with Apache License 2.0 6 votes vote down vote up
def make_str(board: chess.Board, is_white_on_bottom: bool) -> str:
    """Converts a board object into a string to be used in Markdown. Backticks
    are added around the string to preserve formatting.

    Parameters:
         - board: The board object.
         - is_white_on_bottom: Whether or not white should be on the bottom
                               side in the string. If false, black will be on
                               the bottom.

    Returns: The string made from the board.
    """
    default_str = board.__str__()

    replaced_str = replace_with_unicode(default_str)
    replaced_and_guided_str = guide_with_numbers(replaced_str)
    properly_flipped_str = (
        replaced_and_guided_str if is_white_on_bottom
        else replaced_and_guided_str[::-1]
    )
    trimmed_str = trim_whitespace_before_newline(properly_flipped_str)
    monospaced_str = '```\n{}\n```'.format(trimmed_str)

    return monospaced_str 
Example #18
Source File: self_play.py    From Zerofish with MIT License 6 votes vote down vote up
def write_pgn (pgn_dir, name, moves, outcome, winner):
    dirs = pgn_dir
    if not os.path.exists(dirs):
        print('making directories {}'.format(dirs))
        os.makedirs(dirs)

    path = os.path.join(dirs, name) + '.pgn'
    pgn = [chess.Board().variation_san(moves)]

    if outcome:
        if winner == chess.WHITE:
            pgn.append('1-0')
        else:
            pgn.append('0-1')
    else:
        pgn.append('1/2-1/2')

    with open(path, 'w') as out_file:
        print('opened {}'.format(path))
        print(' '.join(pgn), file=out_file)
    print('closed {}'.format(path)) 
Example #19
Source File: lichess-bot.py    From lichess-bot with GNU Affero General Public License v3.0 5 votes vote down vote up
def setup_board(game):
    if game.variant_name.lower() == "chess960":
        board = chess.Board(game.initial_fen, chess960=True)
    elif game.variant_name == "From Position":
        board = chess.Board(game.initial_fen)
    else:
        VariantBoard = find_variant(game.variant_name)
        board = VariantBoard()
    moves = game.state["moves"].split()
    for move in moves:
        board = update_board(board, move)

    return board 
Example #20
Source File: runner.py    From chs with MIT License 5 votes vote down vote up
def __init__(self, level):
    self.ui_board = Board(level)
    self.board = chess.Board()
    self.parser = FenParser(self.board.fen())
    self.engine = Engine(level)  # Engine you're playing against.
    self.hint_engine = Engine(8)  # Engine used to help give you hints.
    self.board.san_move_stack_white = []
    self.board.san_move_stack_black = []
    self.board.help_engine_hint = None 
Example #21
Source File: AnalysedPosition.py    From irwin with GNU Affero General Public License v3.0 5 votes vote down vote up
def fromBoardAndAnalyses(board: Board, analyses: List[Analysis]):
        return AnalysedPosition(
            id=AnalysedPosition.idFromBoard(board),
            analyses=analyses) 
Example #22
Source File: AnalysedPosition.py    From irwin with GNU Affero General Public License v3.0 5 votes vote down vote up
def idFromBoard(board: Board) -> AnalysedPositionID:
        return str(polyglot.zobrist_hash(board)) 
Example #23
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 #24
Source File: AnalysedPosition.py    From irwin with GNU Affero General Public License v3.0 5 votes vote down vote up
def byBoard(self, board: Board) -> Opt[AnalysedPosition]:
        analysedPositionBSON = self.analysedPositionColl.find_one({'_id': AnalysedPosition.idFromBoard(board)})
        return None if analysedPositionBSON is None else AnalysedPositionBSONHandler.reads(analysedPositionBSON) 
Example #25
Source File: test.py    From sunfish with GNU General Public License v3.0 5 votes vote down vote up
def test_uci(python='python3', protocol='uci'):
    def new_engine():
        #python = '/usr/local/bin/python3'
        d = pathlib.Path(__file__).parent
        if protocol ==  'uci':
            args = [python, '-u', str(d / 'uci.py')]
            return chess.engine.SimpleEngine.popen_uci(args, debug=True)
        else:
            args = [python, '-u', str(d / 'xboard.py')]
            return chess.engine.SimpleEngine.popen_xboard(args, debug=True)

    limits = [
        chess.engine.Limit(time=1),
        chess.engine.Limit(nodes=1000),
        chess.engine.Limit(white_clock=1, black_clock=1),
        chess.engine.Limit(
            white_clock=1,
            black_clock=1,
            white_inc=1,
            black_inc=1,
            remaining_moves=2)
    ]

    for limit in limits:
        engine = new_engine()
        board = chess.Board()
        while not board.is_game_over() and len(board.move_stack) < 3:
            result = engine.play(board, limit)
            board.push(result.move)
        engine.quit()


###############################################################################
# Perft test
############################################################################### 
Example #26
Source File: state.py    From twitchchess with MIT License 5 votes vote down vote up
def __init__(self, board=None):
    if board is None:
      self.board = chess.Board()
    else:
      self.board = board 
Example #27
Source File: chessbot.py    From python-zulip-api with Apache License 2.0 5 votes vote down vote up
def start_computer(
        self,
        message: Dict[str, str],
        bot_handler: Any,
        is_white_user: bool
    ) -> None:
        """Starts a game with the computer. Replies to the bot handler.

        Parameters:
             - message: The Zulip Bots message object.
             - bot_handler: The Zulip Bots bot handler object.
             - is_white_user: Whether or not the player wants to be
                                     white. If false, the user is black. If the
                                     user is white, they will get to make the
                                     first move; if they are black the computer
                                     will make the first move.
        """
        new_board = chess.Board()

        if is_white_user:
            bot_handler.send_reply(
                message,
                make_start_computer_reponse(new_board)
            )

            # `bot_handler`'s `storage` only accepts `str` values.
            bot_handler.storage.put('is_with_computer', str(True))

            bot_handler.storage.put('last_fen', new_board.fen())
        else:
            self.move_computer_first(
                message,
                bot_handler,
                new_board.fen(),
            ) 
Example #28
Source File: chessbot.py    From python-zulip-api with Apache License 2.0 5 votes vote down vote up
def make_move_reponse(
    last_board: chess.Board,
    new_board: chess.Board,
    move: chess.Move
) -> str:
    """Makes a response string for after a move is made.

    Parameters:
         - last_board: The board object before the move.
         - new_board: The board object after the move.
         - move: The move object.

    Returns: The move response string.
    """
    return (
        'The board was like this:\n\n'
        '{}'
        '\n\n\n'
        'Then *{}* moved *{}*:\n\n'
        '{}'
        '\n\n\n'
        'Now it\'s **{}**\'s turn.'
        '\n\n\n'
        '{}'
    ).format(
        make_str(last_board, new_board.turn),
        'white' if last_board.turn else 'black',
        last_board.san(move),
        make_str(new_board, new_board.turn),
        'white' if new_board.turn else 'black',
        make_footer()
    ) 
Example #29
Source File: game_state.py    From Zerofish with MIT License 5 votes vote down vote up
def __init__ (self, board=None):
        if board is None:
            self.state = chess.Board()
        else:
            self.state = board.copy()

        self.invalidate() 
Example #30
Source File: chessbot.py    From python-zulip-api with Apache License 2.0 5 votes vote down vote up
def validate_board(
        self,
        message: Dict[str, str],
        bot_handler: Any,
        fen: str
    ) -> Optional[chess.Board]:
        """Validates a board based on its FEN string. Replies to the bot
        handler if there is an error with the board.

        Parameters:
             - message: The Zulip Bots message object.
             - bot_handler: The Zulip Bots bot handler object.
             - fen: The FEN string of the board.

        Returns: `None` if the board didn't pass, or the board object itself
                 if it did.
        """
        try:
            last_board = chess.Board(fen)
        except ValueError:
            bot_handler.send_reply(
                message,
                make_copied_wrong_response()
            )
            return None

        return last_board