Exemplo n.º 1
0
    def KQvKP(king_position: int):
        _BLACK_KING_POSITION = chess.H1
        _BLACK_PAWN_POSITION = chess.H2

        board = chess.Board()
        board.clear()

        board.set_piece_at(_BLACK_KING_POSITION, Piece(chess.KING, chess.BLACK))
        board.set_piece_at(_BLACK_PAWN_POSITION, Piece(chess.PAWN, chess.BLACK))
        board.set_piece_at(king_position, Piece(chess.KING, chess.WHITE))

        possible_boards = []

        for square in chess.SQUARES:
            if square in [_BLACK_KING_POSITION, _BLACK_PAWN_POSITION, king_position]:
                continue

            possible_board = board.copy()
            possible_board.set_piece_at(square, Piece(chess.QUEEN, chess.WHITE))

            if not possible_board.is_attacked_by(chess.WHITE, _BLACK_KING_POSITION) and possible_board.is_valid():
                possible_boards.append(possible_board)

        filtered_boards = list(filter(lambda b: Tablebase.check(b) == 2, possible_boards))

        return len(possible_boards) == len(filtered_boards)
Exemplo n.º 2
0
 def parse_piece_list(cls, white, black):
     board = Board()
     board.clear()
     for peice in white.split(" "):
         p = Piece.from_symbol(peice[0])
         board.set_piece_at(
             square(ord(peice[1]) - ord('a'),
                    int(peice[2]) - 1), p)
     for peice in black.lower().split(" "):
         p = Piece.from_symbol(peice[0])
         board.set_piece_at(
             square(ord(peice[1]) - ord('a'),
                    int(peice[2]) - 1), p)
     return board
Exemplo n.º 3
0
def exposed_king(puzzle: Puzzle) -> bool:
    if puzzle.pov:
        pov = puzzle.pov
        board = puzzle.mainline[0].board()
    else:
        pov = not puzzle.pov
        board = puzzle.mainline[0].board().mirror()
    king = board.king(not pov)
    assert king is not None
    if chess.square_rank(king) < 5:
        return False
    squares = SquareSet.from_square(king - 8)
    if chess.square_file(king) > 0:
        squares.add(king - 1)
        squares.add(king - 9)
    if chess.square_file(king) < 7:
        squares.add(king + 1)
        squares.add(king - 7)
    for square in squares:
        if board.piece_at(square) == Piece(PAWN, not pov):
            return False
    for node in puzzle.mainline[1::2][1:-1]:
        if node.board().is_check():
            return True
    return False
Exemplo n.º 4
0
 def pieceFactory(self, piece: chess.Piece, square: int):
     result = ChessPieceWidget(
         self.getTile(square),
         imageDir + imageStyleDir + imageDict[piece.symbol()],
         self.boardWidget)
     addToDictList(self.pieceDict, piece, result)
     self.widgetToAdd.add_widget(result)
Exemplo n.º 5
0
 def from_dict(occupied_squares):
     '''
     Build a BlindBoard from a dictionary with the structure {square: color}
     '''
     board = BlindBoard()
     for square, color in occupied_squares.items():
         board.set_piece_at(square, Piece(PAWN, color))
     return board
Exemplo n.º 6
0
 def test_from_notation(self):
     for row, notation_row in enumerate(self.notation):
         for col, square in enumerate(notation_row):
             board_piece = self.board[row][col]
             if square == "":
                 self.assertEqual(board_piece, None)
             else:
                 self.assertEqual(Position(row, col), board_piece.position)
                 self.assertEqual(Color.from_notation(square[0]), board_piece.color)
                 self.assertEqual(Piece.from_notation(square[1]), type(board_piece))
Exemplo n.º 7
0
 def deep_copy_board_pos(self,board):
     fresh = Bitboard()
     for i in range(0,8):
         for j in range(0,8):
             piece = board.piece_at(j*8+i)
             if(piece):
                 sym = piece.symbol()
                 fresh.set_piece_at(j*8+i,Piece.from_symbol(sym))
             else:
                 fresh.remove_piece_at(j*8+i)
     return fresh
Exemplo n.º 8
0
 def deep_copy_board_pos(self,board):
     fresh = Board()
     for i in range(0,8):
         for j in range(0,8):
             piece = board.piece_at(j*8+i)
             if(piece):
                 sym = piece.symbol()
                 fresh.set_piece_at(j*8+i,Piece.from_symbol(sym))
             else:
                 fresh.remove_piece_at(j*8+i)
     return fresh
Exemplo n.º 9
0
def human_move(src, dest):
    piece = BOARD.remove_piece_at(src)
    if dest > 55:
        BOARD.set_piece_at(dest, Piece(QUEEN, Color(WHITE)))
    else:
        BOARD.set_piece_at(dest, piece)

    jump = play_move(state_board, [src, dest], Turn.WHITE)
    if jump is not None:
        BOARD.remove_piece_at(jump)

    print_board(state_board)
Exemplo n.º 10
0
 def set_piece_at(self, square, piece):
     '''
     In `BaseBoard`, this method expects a square and a Piece object.
     But for BlindBoards, we only need the second argument to be a color
     (we don't need the piece type).
     '''
     if piece in chess.COLORS:
         piece = Piece(PAWN, piece)
     elif not isinstance(piece, Piece):
         raise ValueError("`%s` is neither a `bool` nor a Piece object"
                          % str(piece))
     return BaseBoard.set_piece_at(self, square, piece)
def piece(piece: chess.Piece, size: Optional[int] = None) -> str:
    """
    Renders the given :class:`chess.Piece` as an SVG image.
    >>> import chess
    >>> import chess.svg
    >>>
    >>> chess.svg.piece(chess.Piece.from_symbol("R"))  # doctest: +SKIP
    .. image:: ../docs/wR.svg
    """
    svg = _svg(SQUARE_SIZE, size)
    svg.append(ET.fromstring(PIECES[piece.symbol()]))
    return SvgWrapper(ET.tostring(svg).decode("utf-8"))
Exemplo n.º 12
0
def computer_move(move):
    jump = play_move(state_board, move, Turn.BLACK)

    piece = BOARD.remove_piece_at(move[0])
    if move[1] < 8:
        BOARD.set_piece_at(move[1], Piece(QUEEN, BLACK))
    else:
        BOARD.set_piece_at(move[1], piece)

    if jump is not None:
        BOARD.remove_piece_at(jump)

    print_board(state_board)
Exemplo n.º 13
0
def board_to_blindboard(board):
    '''
    Takes as input a `Board` object and makes it 'blind' by turning all pieces into pawns.
    '''
    assert isinstance(board, Board)
    blindboard = BlindBoard()

    for color in (BLACK, WHITE):
        # occupied_pieces is a set of integers
        occupied_squares = BlindBoard.Diff.get_squares_from_mask(board.occupied_co[color])
        for square in occupied_squares:
            blindboard.set_piece_at(square, Piece(PAWN, color))

    return blindboard
Exemplo n.º 14
0
def piece(piece: chess.Piece):
    """Renders the given :class:`chess.Piece` as HTML escaped unicode.

    >>> import chess
    >>> import chess.html
    >>>
    >>> chess.html.piece(chess.Piece.from_symbol("R"))  # doctest: +SKIP
    '<span class="piece rook white not-check">&#9814;</span>'
    """
    symb = piece.unicode_symbol().encode('ascii', 'xmlcharrefreplace').decode()
    data = {
        'symbol': symb,
        'color': chess.COLOR_NAMES[piece.color],
        'name': chess.PIECE_NAMES[piece.piece_type]
    }
    return HTML_PIECE.format(**data)
Exemplo n.º 15
0
def test_imgage_processor():
    '''Test image processor (multiple tests)'''

    expected_board = BlindBoard.get_starting_board()
    expected_board.remove_piece_at(chess.E2)
    expected_board.set_piece_at(chess.E4, Piece(PAWN, WHITE))

    # retrieve all the images paths and sort
    images = collect_test_images('tests/pictures/game000')
    debug("Calibrating image processor...")
    processor = ImageProcessor(images[0], images[1])

    for img, expected_board in zip(images[2:], expected_boards()):
        debug("Processing `{}`...".format(os.path.basename(img)))
        processor.process(img)
        board = processor.get_blindboard()
        yield compare_blindboards, expected_board, board, img
Exemplo n.º 16
0
    def testPeiceClassMethods(self):

        # test is_valid_xy_position
        p = Piece()
        # Positive Test
        self.assertTrue(p.is_valid_xy_position([1, 1]))
        self.assertTrue(p.is_valid_xy_position([8, 8]))
        # Negative Test
        self.assertFalse(p.is_valid_xy_position([0, 0]))
        self.assertFalse(p.is_valid_xy_position([9, 9]))

        # position_to_xy
        self.assertEqual(p.position_to_xy("A1"), [1, 1])

        # xy_to_position(self, xy)
        self.assertEqual(p.xy_to_position([1, 1]), "A1")
Exemplo n.º 17
0
 def mousePressEvent(self, mouseEvent):
     pos = self.getBoardPosition(mouseEvent.x(), mouseEvent.y())
     if(pos):
         x = pos[0]
         y = pos[1]
         if(x > 7):
             self.selected_xy = (x-8,y)
         else:
             if(self.selected_xy != None):
                 (i,j) = self.selected_xy
                 piece = self.pcs[i][j]
                 square = y*8+x
                 current_piece = self.board.piece_at(square)
                 if(current_piece and current_piece.symbol() == piece):
                     self.board.remove_piece_at(square)
                 else:
                     self.board.set_piece_at(square,Piece.from_symbol(piece))
                 if(self.board.status() == 0):
                     self.parent.enable_ok_button()
                 else:
                     self.parent.disable_ok_button()
     self.update()
Exemplo n.º 18
0
 def mousePressEvent(self, mouseEvent):
     pos = self.getBoardPosition(mouseEvent.x(), mouseEvent.y())
     if(pos):
         x = pos[0]
         y = pos[1]
         if(x > 7):
             self.selected_xy = (x-8,y)
         else:
             if(self.selected_xy != None):
                 (i,j) = self.selected_xy
                 piece = self.pcs[i][j]
                 square = y*8+x
                 current_piece = self.board.piece_at(square)
                 if(current_piece and current_piece.symbol() == piece):
                     self.board.remove_piece_at(square)
                 else:
                     self.board.set_piece_at(square,Piece.from_symbol(piece))
                 if(self.board.status() == 0):
                     self.parent.enable_ok_button()
                 else:
                     self.parent.disable_ok_button()
     self.update()
Exemplo n.º 19
0
def piece_char(piece: chess.Piece):
    if piece is None:
        return chr(0).encode()
    return piece.symbol().encode()
Exemplo n.º 20
0
from chess import PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING, WHITE, BLACK, Piece

W_PAWN, W_KNIGHT, W_BISHOP, W_ROOK, W_QUEEN, W_KING = Piece(
    PAWN, WHITE), Piece(KNIGHT, WHITE), Piece(BISHOP, WHITE), Piece(
        ROOK, WHITE), Piece(QUEEN, WHITE), Piece(KING, WHITE)
B_PAWN, B_KNIGHT, B_BISHOP, B_ROOK, B_QUEEN, B_KING = Piece(
    PAWN, BLACK), Piece(KNIGHT, BLACK), Piece(BISHOP, BLACK), Piece(
        ROOK, BLACK), Piece(QUEEN, BLACK), Piece(KING, BLACK)
semantical_piece_order = [
    W_PAWN, W_KNIGHT, W_BISHOP, W_ROOK, W_QUEEN, W_KING, B_PAWN, B_KNIGHT,
    B_BISHOP, B_ROOK, B_QUEEN, B_KING
]
# Piece Index map is how pieces are defined in Scam,
# see https://github.com/fabianvdW/Scam/blob/81f8f85bc4f52655b852f87be43546c7dfea6c8c/src/types.rs#L72-L84
PIECE_INDEX_MAP = {
    W_PAWN: 1,
    W_KNIGHT: 2,
    W_BISHOP: 3,
    W_ROOK: 4,
    W_QUEEN: 5,
    W_KING: 6,
    B_PAWN: 9,
    B_KNIGHT: 10,
    B_BISHOP: 11,
    B_ROOK: 12,
    B_QUEEN: 13,
    B_KING: 14
}
PIECE_MAX_INDEX = 15
Exemplo n.º 21
0
 def get_available_for_figure(self, figure: str) -> set:
     piece = Piece.from_symbol(
         [k for k, v in UNICODE_PIECE_SYMBOLS.items() if v == figure][0])
     return self.board.get_move_for_figure(piece)
Exemplo n.º 22
0
 def piece_texture(self, piece: chess.Piece):
     return self.atlas[piece.symbol()]