check if mate
This commit is contained in:
parent
f2fdeac92e
commit
7879b2a08b
|
|
@ -152,9 +152,11 @@ public class Board {
|
|||
selectedY = -1; // Unselect
|
||||
|
||||
clearHighlights();
|
||||
highlightKingInCheck();
|
||||
System.out.println(toString()); // Work but not sure ?
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public boolean isSelected(int x, int y) {
|
||||
|
|
@ -353,5 +355,69 @@ public class Board {
|
|||
piece.y = move.getToY();
|
||||
turn++;
|
||||
}
|
||||
|
||||
|
||||
//Finds the position of the king of a given color.
|
||||
public Piece findKing(boolean isWhite) {
|
||||
for (int x = 0; x < width; x++) {
|
||||
for (int y = 0; y < height; y++) {
|
||||
Piece piece = board[x][y];
|
||||
if (piece != null && piece.getType() == PieceType.King && piece.isWhite() == isWhite) {
|
||||
return piece;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null; // King not found (should not happen in normal chess)
|
||||
}
|
||||
|
||||
// check king check based on a given color
|
||||
public boolean isKingInCheck(boolean isWhite) {
|
||||
// First, find the king's position
|
||||
Piece king = findKing(isWhite);
|
||||
|
||||
if (king == null) {
|
||||
// If king not found (shouldn't happen in a valid chess game)
|
||||
return false;
|
||||
}
|
||||
|
||||
int kingX = king.getX();
|
||||
int kingY = king.getY();
|
||||
|
||||
// Check if any enemy piece can attack the king
|
||||
for (int y = 0; y < height; y++) {
|
||||
for (int x = 0; x < width; x++) {
|
||||
Piece piece = board[x][y];
|
||||
|
||||
// Skip empty squares and pieces of the same color as the king
|
||||
if (piece == null || piece.isWhite() == isWhite) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get all legal moves for this enemy piece
|
||||
ArrayList<Move> moves = getLegalMoves(piece);
|
||||
|
||||
// Check if any move can capture the king
|
||||
for (Move move : moves) {
|
||||
if (move.getToX() == kingX && move.getToY() == kingY) {
|
||||
return true; // King is in check
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false; // King is not in check
|
||||
}
|
||||
|
||||
private void highlightKingInCheck() {
|
||||
// Check if white king is in check
|
||||
Piece whiteKing = findKing(true);
|
||||
if (whiteKing != null && isKingInCheck(true)) {
|
||||
highlightedSquares[whiteKing.getX()][whiteKing.getY()] = true;
|
||||
}
|
||||
|
||||
// Check if black king is in check
|
||||
Piece blackKing = findKing(false);
|
||||
if (blackKing != null && isKingInCheck(false)) {
|
||||
highlightedSquares[blackKing.getX()][blackKing.getY()] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue