def move(self, piece: Piece, to_pos: (int, int)): if piece.get_color() != self.__player_turn: raise BadPlayerException('Bad player') if to_pos not in piece.get_possible_moves(self.__board, self.__turn): raise InvalidMove('Cannot move there') self.__board.move(piece, to_pos, self.__turn) self.__next_turn()
def __init__(self, chess_coord, colour, move_direction): if colour is white: Piece.__init__(self, chess_coord, colour, 'P', '♙', [move_direction]) else: Piece.__init__(self, chess_coord, colour, 'P', '♟', [move_direction]) self.en_passant_square = None self.my_direction = self.move_directions[0]
def test_on_board(): from_x = 4 from_y = 0 to_x = 0 to_y = 5 piece = Piece(p1) is_on_board = piece.on_board(from_x, from_y, to_x, to_y) assert is_on_board == True
def line_of_sight_captures(board: Board, piece: Piece, directions: [(int, int)], max_step: int = float('inf')) \ -> set: position = piece.get_position() captures = functools.reduce(lambda x, y: x + [__get_first_seen_in_direction(board, position, y, max_step)], directions, []) captures = filter(lambda x: x.is_just(), captures) captures = list(map(lambda x: x.get(), captures)) return set(filter(lambda x: x.get_color() != piece.get_color(), captures))
def capture(self, piece: Piece, captured_position: (int, int)): if piece.get_color() != self.__player_turn: raise BadPlayerException('Bad player') captured = self.__get_piece_at(captured_position) if captured not in piece.get_possible_captures( self.__board, self.__turn) or captured.get_color() == piece.get_color(): raise InvalidMove('Cannot capture that') self.__board.capture(piece, captured, self.__turn) self.__next_turn()
def add_piece(self, player: Player, piece: Piece, trigger_placement_effects: bool = False, trigger_movement_effects: bool = False) -> None: self.piece_map(player).add_piece(piece) if piece.location: piece.location.remove_pieces_without_side_effects(player, [piece]) piece.update_location(self) if trigger_placement_effects: self.trigger_placement_effects(player, [piece]) if trigger_movement_effects: self.trigger_movement_effects(player, [piece])
def draw_selected_piece(self, selected_piece: Piece): x, y = selected_piece.get_position() gl.glPushMatrix() gl.glTranslatef(*self.__transform) gl.glTranslatef(x * self.__tile_size, y * self.__tile_size, 0) self.__draw_label(selected_piece.get_color(), '▢', self.__half_tile_size, self.__half_tile_size * 1.4, self.__piece_size * 1.25) gl.glPopMatrix()
def get_castling_move_result(self, pieces, move): def get_valid_rook(coord): if coord: rook = select_piece(coord, pieces) if rook and rook.number_of_moves == 0 and rook.letter == 'R': return rook return None def pieces_are_on_squares(squares, pieces): selection_result = select_pieces(squares, pieces) found_pieces = filter(lambda sr: sr is not None, selection_result) return found_pieces != [] castling_inspect_result = CastlingMoveInspectResult(False, False, False, False, None, None) if str(move) in castling_moves_squares_and_rook_coord_dict: castling_squares_and_rook_coord = \ castling_moves_squares_and_rook_coord_dict[str(move)] else: return castling_inspect_result if not (self.chess_coord == ChessCoord('E', '1') or self.chess_coord == ChessCoord('E', '8')): return castling_inspect_result castling_inspect_result.was_castling_attempt = True rook_coord = castling_squares_and_rook_coord['rook_coord'] possible_rook = get_valid_rook(rook_coord) squares_in_between = castling_squares_and_rook_coord['squares_in_between'] grid_squares_in_between = map(chess_coord_to_grid_coord, squares_in_between) self.analyze_threats_on_board_for_new_move(pieces, self.chess_coord) threatened_squares = self.get_all_squares_the_enemy_threatens(pieces) squares_in_between_threatened = True in map(lambda inbetween_square: inbetween_square in threatened_squares, grid_squares_in_between) castling_inspect_result.was_blocked = pieces_are_on_squares( squares_in_between, pieces) has_not_moved = self.number_of_moves == 0 is_in_check = Piece.check_if_own_king_in_check(self, pieces) is_valid_castling = possible_rook is not None and has_not_moved and \ not castling_inspect_result.was_blocked and not \ squares_in_between_threatened and not is_in_check castling_inspect_result.is_valid_move = is_valid_castling castling_inspect_result.castling_rook = possible_rook castling_inspect_result.new_coord_rook = \ castling_squares_and_rook_coord['new_rook_coord'] castling_inspect_result.squares_in_between_threatened = \ squares_in_between_threatened return castling_inspect_result
def get_possible_moves_for(self, piece: Piece) -> set: color = piece.get_color() king = self.__white_king if color == Piece.Color.WHITE else self.__black_king moves = piece.get_possible_moves(self.__board, self.__turn) if king.is_check(self.__board, self.__turn) and piece != king: moves = set( filter(lambda m: self.__can_move_save_king(piece, king, m), moves)) if piece != king: moves = set( filter( lambda m: not king.can_move_cause_check( self.__board, piece, m, self.__turn), moves)) return moves
def get_possible_captures_for(self, piece: Piece) -> set: color = piece.get_color() king = self.__white_king if color == Piece.Color.WHITE else self.__black_king captures = piece.get_possible_captures(self.__board, self.__turn) if piece != king and king.is_check(self.__board, self.__turn): captures = list( filter(lambda c: self.__can_capture_save_king(piece, king, c), captures)) captures = set( filter( lambda c: not king.can_capture_cause_check( self.__board, piece, c, self.__turn), captures)) return set(map(lambda x: x.get_position(), captures))
def __can_capture_there(self, board: Board, captured: Piece, turn: int): b = copy.deepcopy(board) b.set_is_simulation(True) s = copy.deepcopy(self) position = captured.get_position() b.capture(s, b.get_piece_at(position).get(), turn) return not b.is_tile_attacked(s.get_color(), s.get_position(), turn + 1)
def __init__(self, board, turn, boards): self.turn = turn objBoard = [] kings = [] #Define a board filled with piece objects y_Pos = 0 for y in board: x_ObjBoard = [] x_Pos = 0 for x in y: if x != "": piece = Piece( x[0], x[1], (y_Pos, x_Pos), None ) #Why did I define it as (y,x)? I have no idea... But I regret doing so... deeply.... x_ObjBoard.append(piece) if x[1] == "R": movement = Rook(x[0], x[1], (y_Pos, x_Pos), x[2]) elif x[1] == "B": movement = Bishop(x[0], x[1], (y_Pos, x_Pos)) elif x[1] == "Q": movement = Queen(x[0], x[1], (y_Pos, x_Pos)) elif x[1] == "k": movement = Knight(x[0], x[1], (y_Pos, x_Pos)) elif x[1] == "P": movement = Pawn(x[0], x[1], (y_Pos, x_Pos), x[2]) elif x[1] == "K": movement = King(x[0], x[1], (y_Pos, x_Pos), x[2]) kings.append(piece) piece.setMove( movement ) #Append the unique movement code to the piece object else: x_ObjBoard.append("") x_Pos += 1 objBoard.append(x_ObjBoard) y_Pos += 1 self.promote = [False, False] #If a pawn is promoting (White,Black) self.colour = "R" self.boards = boards self.board = objBoard self.kings = kings #King objects stored for checking checks
def check_for_putting_self_in_check(self, pieces, new_coordinates, move_inspect_result): if move_inspect_result.was_castling_attempt and \ move_inspect_result.is_valid_move: rook_old_coord = move_inspect_result.castling_rook.chess_coord new_coord_rook = move_inspect_result.new_coord_rook move_inspect_result.castling_rook.update_coord(new_coord_rook) check_result = Piece.check_for_putting_self_in_check(self, pieces, new_coordinates, move_inspect_result) move_inspect_result.castling_rook.update_coord(rook_old_coord) return check_result else: return Piece.check_for_putting_self_in_check(self, pieces, new_coordinates, move_inspect_result)
def check_all_directions(self, pieces, move_to): move_check_results = Piece.check_all_directions(self, pieces, move_to) for mir in move_check_results: if len(mir.squares) > 1: mir.is_valid_move = False mir.possible_piece = None return move_check_results
def draw_moves(self, piece: Piece, moves: (int, int)): color = piece.get_color() for m in moves: x, y = m gl.glPushMatrix() gl.glTranslatef(*self.__transform) gl.glTranslatef(x * self.__tile_size, y * self.__tile_size, 0) self.__draw_label(color, 'M', self.__half_tile_size, self.__half_tile_size, self.__piece_size) gl.glPopMatrix()
def draw_captures(self, piece: Piece, captures: (int, int)): color = piece.get_color() for c in captures: x, y = c gl.glPushMatrix() gl.glTranslatef(*self.__transform) gl.glTranslatef(x * self.__tile_size, y * self.__tile_size, 0) self.__draw_label(color, 'C', self.__half_tile_size, self.__half_tile_size, self.__piece_size) gl.glPopMatrix()
def __setitem__(self, pos: Union[Tuple[int, int], str], piece: Piece): """ Sets the Piece at pos. """ i, j = Board.translate_pos(pos) if isinstance(piece, Piece): print("Changing", piece, "position from", piece.position, "to", (i, j)) piece.position = (i, j) self.__board[i, j] = piece else: raise TypeError("value must be a Piece")
def __init__(self, tk: Tk, x: int, y: int): self._tk = tk self.piece: Optional[Piece] = Piece(self) self.X = x self.Y = y self.button = Button(self._tk, font=self.FONT, height=self.SIZE, width=self.SIZE, command=self._pressed) self.button.grid(row=y, column=x) self.button.configure(image=PhotoImage(file=self.IMAGE))
def create_imaginary_board(self, piece: Piece, field: Field) -> Tuple[Any, Optional[Piece]]: """ Creates imaginary board onto which pieces and fields from original board are copied.\n Imaginary board is a chessboard used to move selected piece and check various cases of mates. :param piece: piece which changes its location :param field: field with which piece changed its location :return: Imaginary Chessboard and piece taken on imaginary chessboard or None if no piece was taken. """ imaginary = Chessboard() imaginary.chessboard = self.__copy_chessboard() imaginary.chessboard[field.location[0]].remove(field) imaginary.chessboard[piece.location[0]].remove(piece) deleted_piece = None if isinstance(field, Piece): new_field = Field(field.location[0], field.location[1]) tmp = copy(new_field.location) new_field.location = copy(piece.location) piece.location = tmp imaginary.chessboard[new_field.location[0]].insert( new_field.location[1], new_field) deleted_piece = field else: tmp = copy(field.location) field.location = copy(piece.location) piece.location = tmp imaginary.chessboard[field.location[0]].insert( field.location[1], field) imaginary.chessboard[piece.location[0]].insert(piece.location[1], piece) return imaginary, deleted_piece
def setUp(self): self.directions = [go_west, go_east, go_north, go_north_east] self.black_piece = Piece(ChessCoord('H', '6'), black, 'P', 'P', self.directions) self.other_piece_B4 = Piece(ChessCoord('B', '4'), white, 'P', 'P', self.directions) self.other_piece_C6 = Piece(ChessCoord('C', '6'), black, 'P', 'P', self.directions) self.other_piece_G3 = Piece(ChessCoord('G', '3'), white, 'P', 'P', self.directions) self.other_piece_D7 = Piece(ChessCoord('D', '7'), white, 'P', 'P', self.directions) self.some_pieces = [ Piece(ChessCoord('A', '1'), black, 'P', 'P', self.directions), self.other_piece_B4, self.other_piece_C6, self.other_piece_G3, self.other_piece_D7 ]
def inspect_move(self, pieces, move): grid_move = bps.chess_coord_to_grid_coord(move) move_direction = get_direction(self.grid_coord, grid_move) if is_diagonal_move(move_direction): return self.inspect_taking_move(pieces, grid_move, move_direction) move_inspect_result = Piece.inspect_move(self, pieces, move) ok_num_of_steps = self.ok_number_steps(move_inspect_result.squares) move_inspect_result.is_valid_move = ok_num_of_steps and move_inspect_result.is_valid_move if move_inspect_result.possible_piece: move_inspect_result.is_valid_move = False move_inspect_result.was_blocked = True move_inspect_result.will_put_self_in_check = \ self.check_for_putting_self_in_check(pieces, move, move_inspect_result) move_inspect_result.is_valid_move = move_inspect_result.is_valid_move and \ not move_inspect_result.will_put_self_in_check return move_inspect_result
def toString(self): return self.side + self.piece + Piece.convertBoolToString( self.firstMove)
def update_coord(self, chess_coord): self.register_possible_en_passant(chess_coord) Piece.update_coord(self, chess_coord)
class PieceTests(unittest.TestCase): def setUp(self): self.directions = [go_west, go_east, go_north, go_north_east] self.black_piece = Piece(ChessCoord('H', '6'), black, 'P', 'P', self.directions) self.other_piece_B4 = Piece(ChessCoord('B', '4'), white, 'P', 'P', self.directions) self.other_piece_C6 = Piece(ChessCoord('C', '6'), black, 'P', 'P', self.directions) self.other_piece_G3 = Piece(ChessCoord('G', '3'), white, 'P', 'P', self.directions) self.other_piece_D7 = Piece(ChessCoord('D', '7'), white, 'P', 'P', self.directions) self.some_pieces = [ Piece(ChessCoord('A', '1'), black, 'P', 'P', self.directions), self.other_piece_B4, self.other_piece_C6, self.other_piece_G3, self.other_piece_D7 ] def test_constructor(self): self.failUnless(self.black_piece.letter is 'P') self.failUnless(self.black_piece.colour is black) self.failUnless(self.black_piece.move_directions == self.directions) self.failUnless(self.black_piece.chess_coord == ChessCoord('H', '6')) self.failUnless(self.black_piece.grid_coord == GridCoord(7, 5)) def test_is_valid_move_returns_move_result_no_pieces(self): move_inspect_result = self.black_piece.inspect_move([], ChessCoord('F', '6')) self.failUnless(move_inspect_result == MoveInspectResult(True, False, [ GridCoord(6, 5), GridCoord(5, 5)], None)) def test_is_valid_move_returns_move_result_with_pieces(self): move_inspect_result = self.black_piece.inspect_move(self.some_pieces, ChessCoord('F', '6')) self.failUnless(move_inspect_result == MoveInspectResult(True, False, [ GridCoord(6, 5), GridCoord(5, 5)], None)) def test_is_invalid_move_returns_move_result_with_own_blocking_piece_end_square(self): self.black_piece.update_coord(ChessCoord('A', '4')) move_inspect_result = self.black_piece.inspect_move(self.some_pieces, ChessCoord('C', '6')) self.failUnless(move_inspect_result == MoveInspectResult(False, True, [], self.other_piece_B4)) def test_is_valid_move_returns_move_result_with_enemy_piece_end_square(self): self.black_piece.update_coord(ChessCoord('G', '1')) move_inspect_result = self.black_piece.inspect_move(self.some_pieces, ChessCoord('G', '3')) self.failUnless(move_inspect_result == MoveInspectResult(True, False, [GridCoord(6, 1), GridCoord(6, 2)], self.other_piece_G3) ) def test_is_invalid_move_result_with_enemy_piece_blocking(self): self.black_piece.update_coord(ChessCoord('B', '5')) move_inspect_result = self.black_piece.inspect_move(self.some_pieces, ChessCoord('E', '8')) self.failUnless(move_inspect_result == MoveInspectResult(False, True, [], self.other_piece_C6) ) def test_is_invalid_move_result_with_friendly_piece_blocking(self): self.black_piece.update_coord(ChessCoord('D', '4')) move_inspect_result = self.black_piece.inspect_move(self.some_pieces, ChessCoord('A', '4')) self.failUnless(move_inspect_result == MoveInspectResult(False, True, [GridCoord(2, 3)], self.other_piece_B4) )
def inspect_move(self, pieces, move): castling_move_result = self.get_castling_move_result(pieces, move) if castling_move_result.was_castling_attempt: return castling_move_result else: return Piece.inspect_move(self, pieces, move)
def capture_piece(self, piece: Piece): position = piece.get_position() self.remove_piece_at(position)
def __init__(self, colour, position, board): Piece.__init__(self, "king", colour, position, board) self.directions = [(x, y) for x in [-1, 0, 1] for y in [-1, 0, 1]]
def __init__(self, colour, position, board): Piece.__init__(self, "pawn", colour, position, board)
def __init__(self, chess_coord, colour): if colour is white: Piece.__init__(self, chess_coord, white, 'Q', '♕', move_directions_queen()) else: Piece.__init__(self, chess_coord, black, 'Q', '♛', move_directions_queen())
def capture(self, piece: Piece, captured: Piece, turn: int): piece.capture(self, captured, turn)
def __init__(self, colour, position, board): Piece.__init__(self, "knight", colour, position, board)
def __init__(self, chess_coord, colour): if colour is white: Piece.__init__(self, chess_coord, white, 'B', '♗', move_directions_bishop()) else: Piece.__init__(self, chess_coord, black, 'B', '♝', move_directions_bishop())
def toString(self): return self.side+self.piece+Piece.convertBoolToString(self.castle)
def set_piece_at(self, position: (int, int), piece: Piece): self.__set_at(position, Maybe.just(piece)) piece.set_pos(position)
def __init__(self, alliance, position): Piece.__init__(self, alliance) self.alliance = alliance self.position = position
def move(self, piece: Piece, to_position: (int, int), turn: int): piece.move(self, to_position, turn)
def __init__(self, alliance, position): Piece.__init__(self, alliance) self.alliance = alliance self.position = position self.original_square = position
def __init__(self, color): Piece.__init__(self, color) self.name = color + '_' + 'N'
def __init__(self, color): Piece.__init__(self, color) self.name = color + '_' + 'P' self.count = 0
def setup(self): """ Sets the board in its initial position. :return: """ # Set up white pieces num_file = 1 num_rank = 1 while num_file < 9: file = chr(96 + num_file) if file == 'a' or file == 'h': self.board['{0}{1}'.format(file, num_rank)]['piece'] = Piece( colour='White', piece_type='rook', file=file, rank=num_rank) elif file == 'b' or file == 'g': self.board['{0}{1}'.format(file, num_rank)]['piece'] = Piece( colour='White', piece_type='knight', file=file, rank=num_rank) elif file == 'c' or file == 'f': self.board['{0}{1}'.format(file, num_rank)]['piece'] = Piece( colour='White', piece_type='bishop', file=file, rank=num_rank) elif file == 'd': self.board['{0}{1}'.format(file, num_rank)]['piece'] = Piece( colour='White', piece_type='queen', file=file, rank=num_rank) elif file == 'e': self.board['{0}{1}'.format(file, num_rank)]['piece'] = Piece( colour='White', piece_type='king', file=file, rank=num_rank) num_file += 1 num_rank = 2 num_file = 1 while num_file < 9: file = chr(96 + num_file) self.board['{0}{1}'.format(file, num_rank)]['piece'] = Piece( colour='White', piece_type='pawn', file=file, rank=num_rank) num_file += 1 # Set up black pieces num_rank = 7 num_file = 1 while num_file < 9: file = chr(96 + num_file) self.board['{0}{1}'.format(file, num_rank)]['piece'] = Piece( colour='Black', piece_type='pawn', file=file, rank=num_rank) num_file += 1 num_file = 1 num_rank = 8 while num_file < 9: file = chr(96 + num_file) if file == 'a' or file == 'h': self.board['{0}{1}'.format(file, num_rank)]['piece'] = Piece( colour='Black', piece_type='rook', file=file, rank=num_rank) elif file == 'b' or file == 'g': self.board['{0}{1}'.format(file, num_rank)]['piece'] = Piece( colour='Black', piece_type='knight', file=file, rank=num_rank) elif file == 'c' or file == 'f': self.board['{0}{1}'.format(file, num_rank)]['piece'] = Piece( colour='Black', piece_type='bishop', file=file, rank=num_rank) elif file == 'd': self.board['{0}{1}'.format(file, num_rank)]['piece'] = Piece( colour='Black', piece_type='queen', file=file, rank=num_rank) elif file == 'e': self.board['{0}{1}'.format(file, num_rank)]['piece'] = Piece( colour='Black', piece_type='king', file=file, rank=num_rank) num_file += 1
def __init__(self, chess_coord, colour): if colour is white: Piece.__init__(self, chess_coord, white, 'R', '♖', move_directions_rook()) else: Piece.__init__(self, chess_coord, black, 'R', '♜', move_directions_rook())