65 lines
2.0 KiB
Java
65 lines
2.0 KiB
Java
package backend;
|
||
|
||
import java.util.HashSet;
|
||
import java.util.Set;
|
||
|
||
public class CheckKing {
|
||
|
||
// 1. Check if the king of the given color is under attack
|
||
public static boolean isKingInCheck(Board board, boolean white) {
|
||
Piece[][] grid = board.getBoardMatrix();
|
||
Piece king = null;
|
||
|
||
// Find the king
|
||
for (int y = 0; y < board.getHeight(); y++) {
|
||
for (int x = 0; x < board.getWidth(); x++) {
|
||
Piece piece = grid[y][x];
|
||
if (piece != null && piece.isWhite() == white && piece.getType() == PieceType.King) {
|
||
king = piece;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
if (king == null) return false;
|
||
|
||
int kingX = king.getX();
|
||
int kingY = king.getY();
|
||
|
||
// Check if any opposing piece can move to the king’s square
|
||
for (Piece[] row : grid) {
|
||
for (Piece p : row) {
|
||
if (p != null && p.isWhite() != white) {
|
||
Set<String> moves = board.getValidMoves(p, true); // skip validation
|
||
if (moves.contains(kingX + "," + kingY)) {
|
||
return true;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
// 2. Filter out any moves that would leave the king in check
|
||
public static Set<String> filterLegalMoves(Board board, Piece piece, Set<String> candidateMoves) {
|
||
Set<String> legalMoves = new HashSet<>();
|
||
|
||
for (String move : candidateMoves) {
|
||
String[] parts = move.split(",");
|
||
int toX = Integer.parseInt(parts[0]);
|
||
int toY = Integer.parseInt(parts[1]);
|
||
|
||
// Create a simulated board to test the move
|
||
Board copy = new Board(board);
|
||
copy.movePiece(piece.getX(), piece.getY(), toX, toY);
|
||
|
||
if (!isKingInCheck(copy, piece.isWhite())) {
|
||
legalMoves.add(move);
|
||
}
|
||
}
|
||
|
||
return legalMoves;
|
||
}
|
||
}
|