unfinished version of check

This commit is contained in:
Jérôme BEDIER 2025-05-16 10:20:31 +02:00
parent 6f8846e3ea
commit ea68d319f1
1 changed files with 76 additions and 1 deletions

View File

@ -128,10 +128,11 @@ public class Board {
// No piece selected yet
if (selectedX == -1 && selectedY == -1) {
if (clickedPiece != null && clickedPiece.isWhite() == isTurnWhite()) {
if (clickedPiece != null && clickedPiece.isWhite() == isTurnWhite() && canSelectPieceWhenInCheck(x, y)){
selectedX = x;
selectedY = y;
calculateValidMoves(clickedPiece);
filterMovesForCheck();
}
} else {
// Clicked the same piece again : unselect
@ -482,4 +483,78 @@ public class Board {
highlightedSquares[blackKing.getX()][blackKing.getY()] = true;
}
} // check
public boolean canSelectPieceWhenInCheck(int x, int y) {
Piece piece = board[x][y];
// If no piece at this position or wrong color, can't select
if (piece == null || piece.isWhite() != isTurnWhite()) {
return false;
}
// If king is not in check, any piece can be selected
if (!isKingInCheck(isTurnWhite())) {
return true;
}
// When king is in check, check if this piece can make any legal move
// that would get the king out of check
ArrayList<Move> legalMoves = getLegalMoves(piece);
for (Move move : legalMoves) {
// Temporarily make the move
Piece capturedPiece = board[move.getToX()][move.getToY()];
board[move.getToX()][move.getToY()] = piece;
board[move.getFromX()][move.getFromY()] = null;
// Check if king is still in check after this move
boolean stillInCheck = isKingInCheck(isTurnWhite());
// Undo the move
board[move.getFromX()][move.getFromY()] = piece;
board[move.getToX()][move.getToY()] = capturedPiece;
// If this move gets king out of check, piece can be selected
if (!stillInCheck) {
return true;
}
}
// No legal moves that get king out of check
return false;
}
private void filterMovesForCheck() {
if (!isKingInCheck(isTurnWhite())) {
return; // No filtering needed if not in check
}
Piece selectedPiece = board[selectedX][selectedY];
boolean[][] newHighlights = new boolean[width][height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (highlightedSquares[x][y]) {
// Temporarily make the move
Piece capturedPiece = board[x][y];
board[x][y] = selectedPiece;
board[selectedX][selectedY] = null;
// Check if king is still in check
boolean stillInCheck = isKingInCheck(isTurnWhite());
// Undo the move
board[selectedX][selectedY] = selectedPiece;
board[x][y] = capturedPiece;
// Only keep highlights for moves that get out of check
if (!stillInCheck) {
newHighlights[x][y] = true;
}
}
}
}
// Replace highlights with filtered version
highlightedSquares = newHighlights;
}
}