Compare commits
3 Commits
722cd9cb41
...
c68c72757c
| Author | SHA1 | Date |
|---|---|---|
|
|
c68c72757c | |
|
|
d8374c2061 | |
|
|
7879b2a08b |
|
|
@ -154,9 +154,11 @@ public class Board {
|
|||
selectedY = -1; // Unselect
|
||||
|
||||
clearHighlights();
|
||||
highlightKingInCheck();
|
||||
System.out.println(toString()); // Work but not sure ?
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public boolean isSelected(int x, int y) {
|
||||
|
|
@ -395,5 +397,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;
|
||||
}
|
||||
} // check
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue