I am doing a chess game. I am looking for the best algorithm of checking king's threat in every direction after every move. I made a very basic algorithm like this:
public boolean inDanger(Board board) {
for (int i = this.column + 1; i < 8; i++) {
if (board.findPiece(this.row, i) instanceof Rook ||
board.findPiece(this.row, i) instanceof Queen) {
System.out.println("Check from right side");
return true;
}
}
}
And I am doing this for every direction, so I want to ask if there is a better solution for this.
Instead of doing the whole instance of
thing... create an abstract class Piece
and make Queen
and Rook
subclasses. Create an abstract method like...I don't know evaluateMove()
and let each subclass have its own implementation of evaluateMove()
.
Then after a piece makes it's move, evaluateMove()
stores all available moves this piece can make in a 2D array. Like @Cray said in the comment above, each of these pieces are stored in an array. The abstract class Piece
is going to help you with storing every piece in the same array.
If the King happens to be occupying a square that is an available move, then you know he is in check, or at worst check-mate. You need to update the entire array of Piece
s list of potential moves after every single move since moving pieces in and out of the way can change whether or not the King is actually in danger.
Good luck