Exemplo n.º 1
0
def make_a_move_in_software(source, destination):
    global board_picture
    print(source, "=>", destination)
    #print (coordinates_dictionary[source])
    #print (coordinates_dictionary[destination])
    source_letter = list(source.lower())[0]  #example: A1 become a
    source_number = list(source)[1]  #example:A1 become  1
    source_cell_index = chess.square(
        chess.FILE_NAMES.index(source_letter),
        chess.RANK_NAMES.index(
            source_number))  #example: A1 is cell index = 0 (out of 63)

    destination_letter = list(destination.lower())[0]
    destination_number = list(destination)[1]
    dest_cell_index = chess.square(chess.FILE_NAMES.index(destination_letter),
                                   chess.RANK_NAMES.index(destination_number))

    try:
        board_picture = chess.svg.board(
            board, arrows=[(source_cell_index, dest_cell_index)
                           ])  #show arrow representing current move
        make_a_move_in_hardware(source, destination)
        board.push_uci(source.lower() + destination.lower())
        board_picture = chess.svg.board(
            board)  #show chess board after the move
    except ValueError:
        print("move is invalid or illegal in the current position")
Exemplo n.º 2
0
    def on_capture(self, x: int, y: int):
        """
        When selected piece is placed on MISSING square

        Remove victim piece and the rest is same as on_move
        """
        assert self.select != None and self.turn != None
        to_x, to_y = x, y
        from_x, from_y = self.select
        move = chess.Move(chess.square(from_x, from_y),
                          chess.square(to_x, to_y))
        killer = self.board.piece_at(chess.square(from_x, from_y))
        victim = self.board.piece_at(chess.square(to_x, to_y))
        logger.debug(f"Capture: {move.uci()} ({killer} -> {victim})")

        self.errors -= 1  # Missing -> Killed
        self.warnLED.off(to_x, to_y)
        self.states[to_y][to_x] = GROUND

        self.on_unselect()
        self.lifted[self.turn].remove((from_x, from_y))
        self.states[from_y][from_x] = EMPTY

        self.board.push(move)
        self.switch_turn()
Exemplo n.º 3
0
def is_backward_white(square, board):
    square_file = chess.square_file(square)
    square_rank = chess.square_rank(square)
    if square_rank == 7:
        return False

    current_square = chess.square(square_file, square_rank + 1)
    piece = board.piece_at(current_square)
    if piece is not None and (piece.symbol() == "p" or piece.symbol() == "P"):
        return False

    if not board.is_attacked_by(chess.BLACK, current_square):
        return False

    if square_file == 0:
        file_range = [1]
    elif square_file == 7:
        file_range = [-1]
    else:
        file_range = [-1, 1]

    has_pawn_ahead = False
    for file in file_range:
        for rank in range(8):
            current_square = chess.square(square_file + file, rank)
            piece = board.piece_at(current_square)
            if piece is None or piece.symbol() != "P":
                continue
            if rank < square_rank:
                return False
            else:
                has_pawn_ahead = True
    if has_pawn_ahead:
        return True
    return False
Exemplo n.º 4
0
    def evaluateFenString(fen, player, turn):
        penalty = 0
        #checking for mates and giving penaltys
        if chess.Board(fen).is_checkmate():
            if (player == 1 and turn == 1) or (player == -1 and turn == 0):
                penalty = 10_000
            if (player == 1 and turn == 0) or (player == -1 and turn == 1):
                penalty = -10_000
        #cleaning the fen
        fen = fen.split(" ")[0]

        fenWithoutSpaces = ""
        for letter in fen.replace("/", ""):
            if not letter.isdigit():
                fenWithoutSpaces = fenWithoutSpaces + letter
        #summing all pieces together
        whiteSumm = 0
        blackSumm = 0
        for piece in fenWithoutSpaces:
            if piece.isupper():
                whiteSumm += VALUES[PIECES.index(piece.lower())]
            else:
                blackSumm += VALUES[PIECES.index(piece.lower())]

        #adding the controlled squares:
        b = chess.Board(fen)
        for x in range(8):
            for y in range(8):
                if b.is_attacked_by(chess.WHITE, chess.square(x, y)):
                    whiteSumm += 1
                if b.is_attacked_by(chess.BLACK, chess.square(x, y)):
                    blackSumm += 1

        # summe zwischen weiß und schwarz abhängig von player input
        return (whiteSumm * player + blackSumm * (-1 * player)) + penalty
    def test__hw_play_move_opponent_move_normal(self):
        """ Test normal input move """
        self.hc._input_playResult = engine.PlayResult(
            chess.Move(chess.square(0, 1), chess.square(0, 3)),
            None)  # New move pawn a4

        # Configure occupancy for first and second call
        set_occupancy(self.hwi_mock, self.hc._board)
        occ1 = deepcopy(self.hwi_mock.get_occupancy.return_value)
        occ2 = deepcopy(self.hwi_mock.get_occupancy.return_value)
        occ2[0][1] = False
        occ2[0][3] = True
        self.hwi_mock.get_occupancy.side_effect = [occ1, occ2]

        # Play move itr 1 no move, itr 2 move made, itr 3 terminate
        with patch.object(HardwareClient.HardwareClient,
                          'game_is_over') as game_over_mock:
            game_over_mock.side_effect = [False, False, True]
            self.hc._hw_play_move_opponent()

        self.assertIsNone(self.hc._input_playResult,
                          "Input move has not been processed correctly")

        # Check that in first iteration a2 and a4 are marked and next iteration no squares are marked
        marking2 = [[False] * 8 for _ in range(8)]
        marking1 = deepcopy(marking2)
        marking1[0][1] = True
        marking1[0][3] = True
        self.hwi_mock.mark_squares.assert_has_calls(
            [call(marking1), call(marking2)],
            "Incorrect squares have been marked")
    def test__hw_detect_move_player_promote(self):
        """ Test detect promotion """
        # Set up board
        self.hc._board.set_fen(
            "4k3/P7/8/8/8/8/8/4K3 w - - 0 1")  # Lone pawn a7
        # Configure occupancy
        set_occupancy(self.hwi_mock, self.hc._board)
        self.hwi_mock.get_occupancy.return_value[0][6] = False
        self.hwi_mock.get_occupancy.return_value[0][7] = True
        self.hwi_mock.promotion_piece.return_value = chess.QUEEN

        # Play move itr 1, itr 2 terminate
        with patch.object(HardwareClient.HardwareClient,
                          'game_is_over') as game_over_mock:
            game_over_mock.side_effect = [False, True]
            self.hc._hw_detect_move_player()

        self.assertIsNotNone(self.hc._output_playResult,
                             "Output move has not been processed")
        self.assertEqual(self.hc._output_playResult.move.from_square,
                         chess.square(0, 6), "Detected from square was not b7")
        self.assertEqual(self.hc._output_playResult.move.to_square,
                         chess.square(0, 7), "Detected to square was not a8")
        self.assertEqual(self.hc._output_playResult.move.promotion,
                         chess.QUEEN,
                         "Detected promotion piece move was not a queen")
    def test__hw_play_move_opponent_move_castle(self):
        """ Test castle input move """
        self.hc._board.set_fen("4k3/8/8/8/8/8/8/4K2R w K - 0 1")
        self.hc._input_playResult = engine.PlayResult(
            chess.Move(chess.square(4, 0), chess.square(6, 0)),
            None)  # New move O-O

        # Configure occupancy for first, second and third call
        set_occupancy(self.hwi_mock, self.hc._board)
        occ1 = deepcopy(self.hwi_mock.get_occupancy.return_value)
        occ2 = deepcopy(self.hwi_mock.get_occupancy.return_value)
        occ2[4][0] = False
        occ2[6][0] = True
        self.hwi_mock.get_occupancy.side_effect = [occ1, occ2]

        # Itr 1 no move, itr 2 move, itr 4 terminate
        with patch.object(HardwareClient.HardwareClient,
                          'game_is_over') as game_over_mock:
            game_over_mock.side_effect = [False, False, True]
            self.hc._hw_play_move_opponent()

        self.assertIsNone(self.hc._input_playResult,
                          "Input move has not been processed correctly")

        # Check that in first iteration e1 and g1 are marked and next iteration f1 and h1 are marked
        marking1 = [[False] * 8 for _ in range(8)]
        marking2 = deepcopy(marking1)
        marking1[4][0] = True
        marking1[6][0] = True
        marking2[7][
            0] = True  # Rook move still needs to be played but king move is sufficient to finish method
        marking2[5][0] = True
        self.hwi_mock.mark_squares.assert_has_calls(
            [call(marking1), call(marking2)],
            "Incorrect squares have been marked")
Exemplo n.º 8
0
def gen_labels(valid, board, next_move, extended=False):
    if not extended:
        return [int(valid), int(not valid)]

    uci = str(next_move)
    from_pos, to_pos = uci[:2], uci[2:]

    from_square = chess.square(ord(from_pos[0]) - ord('a'), int(from_pos[1])-1)
    to_square = chess.square(ord(to_pos[0]) - ord('a'), int(to_pos[1])-1)

    distance = chess.square_distance(from_square, to_square)
    distance_vec = [0] * 8
    distance_vec[distance-1] = 1

    symbol = board.piece_at(from_square).symbol()
    is_black, is_white = int(symbol.islower()), int(symbol.isupper())

    symbol_vec = [0] * len(PIECE_TO_INT)
    symbol_vec[PIECE_TO_INT[symbol.lower()]] = 1

    labels = []
    labels.extend([int(valid), int(not valid)]) # is valid or not valid
    labels.extend(distance_vec) # what distance
    labels.extend([is_black, is_white]) # is black or white
    labels.extend(symbol_vec) # which symbol
    return labels
    def test__hw_play_move_opponent_move_promote(self):
        """ Test promotion move """
        self.hc._board.set_fen(
            "4k3/P7/8/8/8/8/8/4K3 w - - 0 1")  # Lone pawn a7
        self.hc._input_playResult = engine.PlayResult(
            chess.Move(chess.square(0, 6), chess.square(0, 7), chess.QUEEN),
            None)  # New move a8Q

        # Configure occupancy for first, second and third call
        set_occupancy(self.hwi_mock, self.hc._board)
        occ1 = deepcopy(self.hwi_mock.get_occupancy.return_value)
        occ2 = deepcopy(self.hwi_mock.get_occupancy.return_value)

        occ2[0][6] = False
        occ2[0][7] = True
        self.hwi_mock.get_occupancy.side_effect = [occ1, occ2]

        # Itr 1 no move, itr 2 promoted piece, itr 3 terminate
        with patch.object(HardwareClient.HardwareClient,
                          'game_is_over') as game_over_mock:
            game_over_mock.side_effect = [False, False, True]
            self.hc._hw_play_move_opponent()

        self.assertIsNone(self.hc._input_playResult,
                          "Input move has not been processed correctly")

        # Check that in first iterations a7 and a8 are marked
        marking2 = [[False] * 8 for _ in range(8)]
        marking1 = deepcopy(marking2)
        marking1[0][6] = True
        marking1[0][7] = True
        self.hwi_mock.mark_squares.assert_has_calls(
            [call(marking1), call(marking2)],
            "Incorrect squares have been marked")
Exemplo n.º 10
0
def evaluateFenStringControll(fen, player, turn):
    penalty = 0
    #checking for checkmate and giving penaltys based on it
    if chess.Board(fen).is_checkmate():
        if (player == 1 and turn == 1) or (player == -1 and turn == 0):
            penalty = 10_000
        if (player == 1 and turn == 0) or (player == -1 and turn == 1):
            penalty = -10_000
    #cleaning the fenString
    fen = fen.split(" ")[0]

    fenWithoutSpaces = ""
    for letter in fen.replace("/", ""):
        if not letter.isdigit():
            fenWithoutSpaces = fenWithoutSpaces + letter
    #initzializing summs and checking for the pieces
    whiteSumm = 0
    blackSumm = 0
    for piece in fenWithoutSpaces:
        if piece.isupper():
            whiteSumm += VALUES[PIECES.index(piece.lower())]
        else:
            blackSumm += VALUES[PIECES.index(piece.lower())]
    b = chess.Board(fen)
    #checking which squares are attacked by whom and adding it to the evaluation
    for i in range(0, 8):
        for x in range(0, 8):
            if b.is_attacked_by(chess.WHITE, chess.square(i, x)):
                whiteSumm += 1
            if b.is_attacked_by(chess.BLACK, chess.square(i, x)):
                blackSumm += 1

    # summe zwischen weiß und schwarz abhängig von player input
    return (whiteSumm * player + blackSumm * (-1 * player)) + penalty
Exemplo n.º 11
0
def az_index_to_move(index):
    if index == -1:
        return chess.Move(None, None)
    move_coordinates = inflate_1d_coords_3d(index, AZ_SHAPE)
    from_file = move_coordinates[0]
    from_rank = move_coordinates[1]
    move_type = move_coordinates[2]
    promotion_piece = None

    if move_type >= 64:  # Treat under-promotions as 3 x 3 array of [type of file movement, piece promoted to]
        underpromotion_type = inflate_1d_coords_2d(move_type - 64, UNDERPROMOTIONS_SHAPE)  # Get under-promotion coords

        file_modifier = underpromotion_type[0] - 1  # shift from range 0,..2 to -1,..1
        promotion_piece = underpromotion_type[1] + PROMOTION_PIECE_MODIFIER  # Restore to python-chesspiece numbers

        to_file = from_file + file_modifier
        to_rank = 7 if from_rank == 6 else 0  # Under-promotions always move a rank ahead (player-relative)
    elif move_type >= 56:
        knight_delta = decode_knight_move_delta(move_type - 56)

        to_file = from_file + knight_delta[0]
        to_rank = from_rank + knight_delta[1]
    else:
        #its a queen move
        queen_delta = decode_queen_delta(move_type)
        to_file = from_file + queen_delta[0]
        to_rank = from_rank + queen_delta[1]

    return chess.Move(chess.square(from_file, from_rank), chess.square(to_file, to_rank), promotion_piece)
Exemplo n.º 12
0
def pack(from_rank: int, from_file: int, to_rank: int,
         to_file: int) -> chess.Move:
    """Converts move coordinates into a chess.Move instance."""

    from_square = chess.square(from_file, from_rank)
    to_square = chess.square(to_file, to_rank)

    return chess.Move(from_square, to_square)
 def choose_sense(self, possible_sense, possible_moves, turn, player_board):
     if sum(self.scout_history) == 0:
         if self.color:
             self.next_scout = chess.square(4, 5)
         else:
             self.next_scout = chess.square(4, 2)
     self.update_scout_history(self.next_scout, player_board)
     return self.next_scout
Exemplo n.º 14
0
 def GetClickedSquare(self, mouseX, mouseY):
     # test function
     print "User clicked screen position x =", mouseX, "y =", mouseY
     row, col = self.ConvertToChessCoords((mouseX, mouseY))
     if col < 8 and col >= 0 and row < 8 and row >= 0:
         print "  Chess board units row =", row, "col =", col
         print "Square Number", chess.square(row, col)
         return chess.square(row, col)
Exemplo n.º 15
0
def main():
    global move_array
    game = True
    engine = uci.popen_engine('./Engine/stockfish_8_x64')
    engine.uci()

    while game:

        SCREEN.blit(BACKGROUND, (0, 512))
        button("Reset", 50, 520, 100, 30, BUTTON_BACK, BUTTON_BACK, resetBoard)
        button("<<", 200, 520, 50, 30, BUTTON_BACK, BUTTON_BACK, toBeginning)
        button("<", 270, 520, 50, 30, BUTTON_BACK, BUTTON_BACK, oneBack)
        button(">", 340, 520, 50, 30, BUTTON_BACK, BUTTON_BACK, pushOne)
        button(">>", 410, 520, 50, 30, BUTTON_BACK, BUTTON_BACK, toEnd)

        for row in range(8):
            for column in range(8):
                if (row, column) not in move_array:
                    if (row + column) % 2 == 0:
                        SCREEN.blit(SQUARE_DARK, (row * 64, column * 64))
                    else:
                        SCREEN.blit(SQUARE_LIGHT, (row * 64, column * 64))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game = False
            if event.type == pygame.MOUSEBUTTONUP:
                pos = pygame.mouse.get_pos()
                x_val, y_val = int(pos[0] / 64), 7 - (int(pos[1] / 64))
                if y_val >= 0:
                    move_array.append((x_val, y_val))

        if len(move_array) == 1:
            SCREEN.blit(SQUARE_CLICKED,
                        (move_array[0][0] * 64, (7 - move_array[0][1]) * 64))

        if len(move_array) == 2:
            square_x = chess.square(move_array[0][0], move_array[0][1])
            square_y = chess.square(move_array[1][0], move_array[1][1])

            if (str(BOARD.piece_at(square_x)) == 'P' or str(BOARD.piece_at(square_x)) == 'p') \
            and chess.file_index(square_x) != chess.file_index(square_y) and \
            (chess.rank_index(square_y) == 0 or chess.rank_index(square_y) == 7):
                cur_move = chess.Move(square_x, square_y, promotion=5)
            else:
                cur_move = chess.Move(square_x, square_y)

            if cur_move in BOARD.legal_moves:
                BOARD.push(cur_move)
                engine_position = engine.position(BOARD)
                engine_moves = engine.go()
                BOARD.push(engine_moves[0])
            else:
                move_array = []

        updateBoard()
        pygame.display.flip()
        CLOCK.tick(30)
 def test_get_move(self):
     """ Test get_move method"""
     play_result = engine.PlayResult(
         chess.Move(chess.square(0, 1), chess.square(0, 3)), None)
     self.hc._output_playResult = play_result
     self.assertEqual(self.hc.get_move(), play_result,
                      "Output move not returned")
     self.assertEqual(self.hc._output_playResult, None,
                      "Internal output field not cleared")
Exemplo n.º 17
0
def bishop_mobility(tablero, casilla_alfil):
    turno = tablero.turn
    fila_origen = chess.square_rank(casilla_alfil)
    columna_origen = chess.square_file(casilla_alfil)

    ur = 0
    ul = 0
    dr = 0
    dl = 0

    for i in range(1, 8):
        fila = fila_origen - i
        columna = columna_origen + i
        # print(f"down right fila {fila} columna: {columna}")
        if fila >= 0 and columna < 8:
            if tablero.piece_type_at(chess.square(columna, fila)) != None:
                # print(tablero.piece_type_at(chess.square(columna, fila)))
                break
            dr += 1
        else:
            break

    for i in range(1, 8):
        fila = fila_origen + i
        columna = columna_origen + i

        if fila < 8 and columna < 8:
            if tablero.piece_type_at(chess.square(columna, fila)) != None:
                break
            ur += 1
        else:
            break

    for i in range(1, 8):
        fila = fila_origen - i
        columna = columna_origen - i
        # print(f"down left fila {fila} columna: {columna} tipo pieza: {tablero.piece_type_at(chess.square(columna, fila))}")
        if fila >= 0 and columna >= 0:
            if tablero.piece_type_at(chess.square(columna, fila)) != None:
                break
            dl += 1
        else:
            break

    for i in range(1, 8):
        fila = fila_origen + i
        columna = columna_origen - i

        if fila < 8 and columna >= 0:
            if tablero.piece_type_at(chess.square(columna, fila)) != None:
                break
            ul += 1
        else:
            break

    # print(f"ur = {ur} ul = {ul} dl = {dl} dr = {dr}")
    return ul + ur + dl + dr
Exemplo n.º 18
0
    def _init_weight(self):
        """Return a square value dictionary"""

        self.value_piece = {
            chess.PAWN:   1.0,
            chess.KNIGHT: 2.95,
            chess.BISHOP: 3.05,
            chess.ROOK:   5.0,
            chess.QUEEN:  9.0,
            chess.KING:   0.0
        }
        
        # Position weight
        wp = [[1,1,1,1,1,1,1,1],
              [1,2,2,2,2,2,2,1],
              [1,2,3,3,3,3,2,1],
              [1,2,3,5,5,3,2,1],
              [1,2,3,5,5,3,2,1],
              [1,2,3,3,3,3,2,1],
              [1,2,2,2,2,2,2,1],
              [1,1,1,1,1,1,1,1]]
        WP = sum(map(sum, wp))
        
        # Attack weight (for black)
        wa0 = [[3,4,4,4,4,4,4,3],
               [3,4,4,4,4,4,4,3],
               [2,3,3,3,3,3,3,2],
               [2,3,3,3,3,3,3,2],
               [1,2,2,2,2,2,2,1],
               [1,2,2,2,2,2,2,1],
               [1,1,1,1,1,1,1,1],
               [1,1,1,1,1,1,1,1]]
        WA = sum(map(sum, wa0))
        wa = {}
        wa[chess.WHITE] = wa0[::-1]
        wa[chess.BLACK] = wa0
        
        
        square_weight = {
            'pos': {},
            'atk': {
                chess.WHITE: {},
                chess.BLACK: {}
            }
        }

        for i in xrange(8):
            for j in xrange(8):
                square_weight['pos'][chess.square(j,i)] = wp[i][j]/float(WP)
                square_weight['atk'][chess.WHITE][chess.square(j,i)] = wa[chess.WHITE][i][j]/float(WA)
                square_weight['atk'][chess.BLACK][chess.square(j,i)] = wa[chess.BLACK][i][j]/float(WA)

        self.square_weight = square_weight

        pass
Exemplo n.º 19
0
 def evaluation(self):
     eval = 0
     for i in range(0, 64):
         if (self.board.piece_at(
                 chess.square(i - (8 * math.floor(i / 8)),
                              7 - math.floor(i / 8))) != None):
             eval = eval + self.getPieceValue(
                 self.board.piece_at(
                     chess.square(i - (8 * math.floor(i / 8)),
                                  7 - math.floor(i / 8))))
     return eval
 def test__diff_occupancy_board_diff(self):
     """ Assert _diff_occupancy_board does not detect a diff if occupancy has expected value """
     set_occupancy(self.hwi_mock, self.hc._board)
     self.hc._board.push(chess.Move(chess.square(0, 1),
                                    chess.square(0, 3)))  # Move pawn a4
     diff = self.hc._diff_occupancy_board(
         self.hwi_mock.get_occupancy.return_value)
     expected = [[False] * 8 for _ in range(8)]
     expected[0][1] = True
     expected[0][3] = True
     self.assertEqual(diff, expected,
                      "Incorrectly detected change in expected occupancy")
Exemplo n.º 21
0
 def press_confirm(self, source_coords, target_coords):
     print("press confirm:", source_coords, target_coords)
     # from_file, from_rank = source_coords
     # to_file, to_rank = target_coords
     from_rank, from_file = source_coords
     to_rank, to_file = target_coords
     square = chess.square(from_file, from_rank)
     next_attack = chess.square(to_file, to_rank)
     if next_attack in self.get_moves(square):
         self.play_move(chess.Move(square, next_attack))
         return True
     else:
         return False
Exemplo n.º 22
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.º 23
0
def multi_pawn_file(cur_board, color, number): # given the number check if and which file/s has that number of pawns of color. Example number = 2 then find files of doubled pawns
	pawn = 'p' # pawn symbol if color is black
	if(color == 1):
		pawn = 'P'
	pawn_files = [] 
	for files in range(8):
		pawns_in_file = 0
		for ranks in range(8):
			if(cur_board.piece_at(chess.square(files, ranks)) != None and cur_board.piece_at(chess.square(files, ranks)).symbol() == pawn): # if pawn found then increase counter
				pawns_in_file = pawns_in_file + 1
		if(pawns_in_file == number): # if there are number pawns of the given color on that file then add it to result
			pawn_files.append(files)
	
	return(pawn_files)
 def test__hw_control_case_3(self):
     """ Test _hw_control wait for opponent move to be played on hardware"""
     self.hc._board.turn = chess.BLACK
     self.hc.color = chess.WHITE
     self.hc._input_playResult = engine.PlayResult(
         chess.Move(chess.square(0, 1), chess.square(0, 3)), None)
     with patch.object(HardwareClient.HardwareClient,
                       'game_is_over') as game_over_mock:
         game_over_mock.side_effect = [False, True]
         with patch.object(HardwareClient.HardwareClient,
                           '_hw_play_move_opponent') as target_mock:
             self.hc._hw_control()
             self.assertTrue(target_mock.called,
                             "Expected method was not called")
    def test_set_move(self):
        """ Test set_move method """
        input_pr = engine.PlayResult(
            chess.Move(chess.square(0, 1), chess.square(0, 3)), None)
        self.hc.set_move(input_pr)
        internal_pr = self.hc._input_playResult
        self.assertNotEqual(
            internal_pr, input_pr,
            "HC should not reuse input object for threadsafety")

        #  Move overrides __eq__ check if move is a new object
        input_pr.move.to_square = chess.square(0, 2)
        self.assertNotEqual(
            internal_pr.move, input_pr.move,
            "HC should not reuse input object for threadsafety")
Exemplo n.º 26
0
    def castling(self, move, direction, isKingSideCastling):
        # locate rook rank and file (0 based)
        fromFile, toFile = (5, 7) if isKingSideCastling else (3, 0)
        rank = chess.square_rank(move.to_square)

        if direction == 'forward':
            kingFromSq, kingToSq = move.from_square, move.to_square
            rookFromSq, rookToSq = chess.square(toFile, rank), chess.square(
                fromFile, rank)
        else:
            kingFromSq, kingToSq = move.to_square, move.from_square
            rookFromSq, rookToSq = chess.square(fromFile, rank), chess.square(
                toFile, rank)
        self.moveCanvasPiece(kingFromSq, kingToSq)  # move king
        self.moveCanvasPiece(rookFromSq, rookToSq)  # move rook
Exemplo n.º 27
0
 def check_if_right_color(self, src):
     src_square = chess_engine.square(convert_letter_to_number(src[0]),
                                      int(src[1]) - 1)
     color_moved = self.board.color_at(src_square)
     if color_moved != self.board.turn:
         return False
     return True
Exemplo n.º 28
0
    def handle_sense(self, square):
        """
        This function takes the sense square and returns the true state of the 3x3 section
        
        :param square: chess.SQUARES -- the square the agent wants to senese around
        :return: A list of tuples, where each tuple contains a :class:`Square` in the sense, and if there
                 was a piece on the square, then the corresponding :class:`chess.Piece`, otherwise `None`.
        """
        if square not in list(chess.SQUARES):
            return []

        rank, file = chess.square_rank(square), chess.square_file(square)
        sense_result = []
        for delta_rank in [1, 0, -1]:
            for delta_file in [-1, 0, 1]:
                if 0 <= rank + delta_rank <= 7 and 0 <= file + delta_file <= 7:
                    sense_square = chess.square(file + delta_file,
                                                rank + delta_rank)
                    sense_result.append(
                        (sense_square,
                         self.board_is_real.piece_at(sense_square)))

        #update sense result for each respective color board
        if self.turn == chess.WHITE:
            for square, piece in sense_result:
                self.white_board.set_piece_at(square, piece)
        else:
            for square, piece in sense_result:
                self.black_board.set_piece_at(square, piece)

        return sense_result
Exemplo n.º 29
0
 def coords_to_square(self, x, y):
     file = (x // self.square_size)
     if self.perspective == chess.WHITE:
         rank = ((self.height - y) // self.square_size)
     else:
         rank = (y // self.square_size)
     return chess.square(file, rank)
Exemplo n.º 30
0
 def mousePressEvent(self, event):
     """
     Handles the left mouse click and enables moving the chess pieces by first clicking on the chess
     piece and then on the target square. 
     """
     if not self.board.is_game_over():
         if event.x() <= self.boardSize and event.y() <= self.boardSize:
             if self.margin<event.x()<self.boardSize-self.margin and self.margin<event.y()<self.boardSize-self.margin:
                 if event.buttons()==Qt.LeftButton:
                     file = int((event.x() - self.margin) / self.squareSize)
                     rank = 7 - int((event.y() - self.margin) / self.squareSize)
                     square = chess.square(file, rank)
                     piece = self.board.piece_at(square)
                     coordinates = "{}{}".format(chr(file + 97), str(rank + 1))
                     if self.pieceToMove[0] is not None:
                         move = chess.Move.from_uci("{}{}".format(self.pieceToMove[1], coordinates))
                         if move in self.board.legal_moves:
                             self.board.push(move)
                             s.board.push(move)
                         self.lastmove = str(self.pieceToMove[1]) + str(coordinates)
                         print('Last Move: ',self.lastmove)
                         piece = None
                         coordinates = None
                         with open('rnd.pickle','rb') as rnd:
                             i = pickle.load(rnd)
                             i = 1 + i
                         with open('rnd.pickle','wb') as rnd:
                             pickle.dump(i,rnd)
                         print(colored("move: " + str(i),'yellow'))
                     self.pieceToMove = [piece, coordinates]
                     self.drawBoard()
                     go = self.make_move()
                     if go == 'gameover':
                         print(colored(Style.BRIGHT + "********************* GAME IS OVER *********************",'red'))
                         self.post()
Exemplo n.º 31
0
    def _is_illegal_castle(self, board, move):
        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.BB_BETWEEN[move.from_square][rook_square])
        if any(map(lambda s: board.piece_at(s), between_squares)):
            return True

        # its legal
        return False
Exemplo n.º 32
0
    def get_blindboard(self):
        """
        Converts the numpy array `_blindboard_matrix` into a BlindBoard object
        """
        if self._blindboard_matrix is None:
            raise ImageProcessorException(
                "The `.process` method has not been called on this object yet")
        occupied_squares = {}
        for (i, j), entry in np.ndenumerate(self._blindboard_matrix):
            col = j ; row = 7-i
            if entry is not None:
                occupied_squares[chess.square(col, row)] = bool(entry)

        return BlindBoard.from_dict(occupied_squares)
def generate_starting_board(_=None):
    while True:
        brd = chess.Board(None)
        wking = get_random_square()
        bking = chess.square(4, 4)
        brd.set_piece_at(wking, chess.Piece.from_symbol("K"))
        brd.set_piece_at(bking, chess.Piece.from_symbol("k"))

        for _ in range(random.randint(1, 16)):
            square = get_random_square()
            piece = get_random_piece()
            if not brd.piece_at(square):
              brd.set_piece_at(square, piece)

        if verify_board(brd):
            return brd
def blend_boards(brd1, brd2, p=0.5):
    res = chess.Board(None)
    for r, f in itertools.product(*[range(8)]*2):
        square = chess.square(r, f)
        if random.random() > p:
          res.set_piece_at(square, brd1.piece_at(square))
        else:
          res.set_piece_at(square, brd2.piece_at(square))

    wkings = res.pieces(chess.KING, chess.WHITE)
    bkings = res.pieces(chess.KING, chess.BLACK)
    if len(wkings) == 0:
        if random.random() > p:
            wking = brd1.pieces(chess.KING, chess.WHITE)
        else:
            wking = brd2.pieces(chess.KING, chess.WHITE)
        for square in wking:
          res.set_piece_at(square, chess.Piece.from_symbol("K"))

    elif len(wkings) > 1:
        kept = random.choice(list(wkings))
        for square in wkings:
            if square != kept:
                res.remove_piece_at(square)

    if len(bkings) == 0:
        if random.random() > p:
            bking = brd1.pieces(chess.KING, chess.BLACK)
        else:
            bking = brd2.pieces(chess.KING, chess.BLACK)
        for square in bking:
            res.set_piece_at(square, chess.Piece.from_symbol("k"))

    elif len(bkings) > 1:
        kept = random.choice(list(bkings))
        for square in bkings:
            if square != kept:
                res.remove_piece_at(square)

    return res
Exemplo n.º 35
0
 def imageCoordsToSquareIndex(self, x, y):
     rank_ind = int((512 - y) / 64)
     file_ind = int(x / 64)
     return chess.square(file_ind, rank_ind)
Exemplo n.º 36
0
def alejandro_moved(command, player_pos):
    return command.from_square == chess.square(player_pos[0], player_pos[1])
def get_random_square():
   return chess.square(random.randint(0, 7), random.randint(0, 7))