onion123 onion123 - 1 month ago 13
Java Question

Java Chess Protecting the King in Check

Im using Java OOP to making a chess game, I dont' know how to filter a list of possible moves of a piece so that it can protect a king when it is in check.
Could anyone help me on how you would implement it.

possible moves

This is my bishop class, most of my other piece classes are similar

@Override
public ArrayList<Point> getPossibleMoves(Board board) {

ArrayList<Point> possibleMoves = new ArrayList<Point>();
int tempx;
int tempy;

for(int i = -1; i <= 1; i += 2){
for(int j = -1; j <= 1; j += 2){
try{
tempx = this.x + i;
tempy = this.y + j;

while(tempx >=0 || tempx < 8 || tempy >= 0 || tempy < 8){
if(board.getTile(tempx, tempy).isOccupied() == false){
possibleMoves.add(new Point(tempx, tempy));
} else if(board.getTile(tempx, tempy).getPiece().getColour() == this.colour){
break;
} else {
possibleMoves.add(new Point(tempx, tempy));
break;
}
tempx += i;
tempy += j;

}

} catch(Exception e){

}

}
}

return possibleMoves;

}

Answer

I assume that you, for each piece, have a way of getting a list of possible moves; and that you have a way of checking if a boardstate leaves the king in check.

Take the leftmost bishop at position (3,1), the list of his possible moves would be [(4,2), (5,3), (6,4), (7,5), (8,6)]. Add a check to filter the moves, along the lines of

ArrayList<Positions> possibleMoves = getPossibleMoves(...);
if( kingIsInCheck ) {
    removeMovesWhichStillLeavesKingInCheck(possibleMoves);
}

The function removeMovesWhichStillLeavesKingInCheck can be implemented in several ways. One of them is just to check, for every move, if executing it still leaves the king in check.

Going through our list of moves shows that moving to (5,3) is the only possible move that the bishop may make to prevent the king being in check, and thus should be the only thing returned.