Python chess.WHITE Examples

The following are 30 code examples of chess.WHITE(). 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: 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 #2
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def has_sense(self, turn: Turn) -> bool:
        """
        Checks to see if the game has a sense action for the specified turn. The game may not if it ended because of
        timeout.

        This intended use is to call this before calling :meth:`sense` and :meth:`sense_result`, to verify that there
        is a sense before querying for it.

        Examples:
            >>> history.has_sense(Turn(WHITE, 0))
            True

            >>> history.has_sense(Turn(WHITE, 432))
            False

        :param turn: The :class:`Turn` in question.
        :return: `True` if there is a sense action, `False` otherwise.
        """
        return 0 <= turn.turn_number < len(self._senses[turn.color]) 
Example #3
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def sense(self, turn: Turn) -> Optional[Square]:
        """
        Get the sense action on the given turn.

        Examples:
            >>> history.sense(Turn(WHITE, 0))
            E7

            >>> history.sense(Turn(BLACK, 0))
            E2

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

        :param turn: The :class:`Turn` in question.
        :return: The executed sense action as a :class:`Square`.
        """
        self._validate_turn(turn, self._senses)
        return self._senses[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 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 #5
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def has_move(self, turn: Turn) -> bool:
        """
        Checks to see if the game has a move action for the specified turn. The game may not if it ended because of
        timeout.

        This intended use is to call this before calling :meth:`requested_move`, :meth:`taken_move`,
        :meth:`capture_square`, and :meth:`move_result` to verify that there is a move before querying for it.

        Examples:
            >>> history.has_move(Turn(WHITE, 0))
            True

            >>> history.has_move(Turn(WHITE, 432))
            False

        :param turn: The :class:`Turn` in question.
        :return: `True` if there is a move action, `False` otherwise.
        """
        return 0 <= turn.turn_number < len(self._requested_moves[turn.color]) 
Example #6
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def taken_move(self, turn: Turn) -> Optional[chess.Move]:
        """
        Get the executed move action on the given turn. This may be different than the requested move, as the requested
        move may not be legal.

        Examples:
            >>> history.requested_move(Turn(WHITE, 0))
            Move(E2, D3)
            >>> history.taken_move(Turn(WHITE, 0))
            None

            >>> history.requested_move(Turn(WHITE, 1))
            Move(E2, E4)
            >>> history.taken_move(Turn(WHITE, 1))
            Move(E2, E3)

        :param turn: The :class:`Turn` in question.
        :return: `None` if the player requested to pass or made an illegal move, the executed move action as a
            :class:`chess.Move` otherwise.
        """
        self._validate_turn(turn, self._taken_moves)
        return self._taken_moves[turn.color][turn.turn_number] 
Example #7
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def capture_square(self, turn: Turn) -> Optional[Square]:
        """
        Get the square of the opponent's captured piece on the given turn. A capture may not have occurred, in which
        case `None` will be returned.

        Examples:
            >>> history.capture_square(Turn(WHITE, 0))
            None

            >>> history.capture_square(Turn(WHITE, 4))
            E4

        :param turn: The :class:`Turn` in question.
        :return: If a capture occurred, then the :class:`Square` where it occurred, otherwise `None`.
        """
        self._validate_turn(turn, self._capture_squares)
        return self._capture_squares[turn.color][turn.turn_number] 
Example #8
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 #9
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 #10
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 #11
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 #12
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 #13
Source File: board.py    From chs with MIT License 6 votes vote down vote up
def generate(self, fen, board, engine, game_over=None):
    if board.turn:
      # Print board before generating the score
      board_loading = self._generate(fen, board, game_over, True)
      print(board_loading)
      print('\n{}{}{}┏━━━━━━━━━━━━━━━━━━━━━━━┓ \n{}┗{}{}{}waiting{}'.format(
        Styles.PADDING_SMALL, Colors.WHITE, Colors.BOLD,\
        Styles.PADDING_SMALL, Styles.PADDING_SMALL, Colors.RESET, Colors.GRAY, Colors.RESET)
      )
      # Analyze the score and print the board again when we're done
      new_cp = engine.score(board)
      new_score = engine.normalize(new_cp)
      self._score = new_score if new_score is not None else self._score
      self._cp = new_cp if new_cp is not None else self._cp
      board_loaded = self._generate(fen, board, game_over)
      print(board_loaded)
    else:
      # Print board without generating the score
      board_loading = self._generate(fen, board, game_over)
      print(board_loading) 
Example #14
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 #15
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 #16
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def num_turns(self, color: Color = None) -> int:
        """
        Get the number of turns taken in the game. Optionally specify the color of the player to get the number of turns
        for.

        Examples:
            >>> history.num_turns()
            9

            >>> history.num_turns(WHITE)
            5

            >>> history.num_turns(BLACK)
            4

        :param color: Optional player color indicating which player's number of turns to return.
        :return: The number of turns saved in this object. If `color` is specified, get the number of turns for that
            player.
        """
        return len(list(self.turns(color=color))) 
Example #17
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 #18
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __lt__(self, other):
        if not isinstance(other, Turn):
            return NotImplemented

        if self.turn_number < other.turn_number:
            return True
        elif self.turn_number > other.turn_number:
            return False
        else:
            return self.color == chess.WHITE and other.color == chess.BLACK 
Example #19
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 #20
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_empty(self) -> bool:
        """
        Get whether or not the game had any turns in it.

        Examples:
            >>> history.is_empty()
            False

        :return: `True` if there are no turns to query in this object, `False` otherwise.
        """
        return len(self._senses[chess.WHITE]) == 0 
Example #21
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def previous(self):
        """
        :return: The :class: `Turn` that happens immediately before this, which is the other player's previous turn.
        """
        return Turn(not self.color, self.turn_number - (1 if self.color == chess.WHITE else 0)) 
Example #22
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 #23
Source File: history.py    From reconchess with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def move_result(self, turn: Turn) -> Tuple[Optional[chess.Move], Optional[chess.Move], Optional[Square]]:
        """
        Get the full move result in one function. Calls :meth:`requested_move`, :meth:`taken_move`, and
        :meth:`capture_square`.

        Examples:
            >>> history.move_result(Turn(WHITE, 0))
            (Move(E2, E4), Move(E2, E3), None)

        :param turn: The :class:`Turn` in question.
        :return: The requested move, the executed move, and a capture square if there was one.
        """
        return self.requested_move(turn), self.taken_move(turn), self.capture_square(turn) 
Example #24
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 #25
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 #26
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 #27
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 #28
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 #29
Source File: mcts.py    From fastchess with GNU General Public License v3.0 5 votes vote down vote up
def eval(self, vec, board):
        v = {'1-0': 1, '0-1': -1, '1/2-1/2': 0, '*': None}[board.result()]
        if v is not None:
            return (v if board.turn == chess.WHITE else -v), True
        # Result doesn't check for repetitions unless we add claim_draw=True,
        # but even then it doesn't quite do what we want.
        if board.is_repetition(count=2):
            return 0, True
        return self.args.model.get_eval(vec, board), False 
Example #30
Source File: fastchess.py    From fastchess with GNU General Public License v3.0 5 votes vote down vote up
def prepare_example(board, move, occ=False):
    if board.turn == chess.WHITE:
        string = ' '.join(board_to_words(board, occ=occ))
        uci_move = move.uci()
    else:
        string = ' '.join(board_to_words(board.mirror(), occ=occ))
        uci_move = mirror_move(move).uci()
    return f'{string} __label__{uci_move}'