try to put checkmate ?

This commit is contained in:
Jérôme BEDIER 2025-05-23 08:40:27 +02:00
parent ae3be7abb1
commit 03c3c5998b
1 changed files with 13 additions and 3 deletions

View File

@ -68,8 +68,20 @@ public class AutoPlayer {
return null;
}
// Prevent AI from moving into check or checkmate
if (copy.isKingInCheck(isWhite) || copy.isCheckmate(isWhite)) {
continue; // Skip moves that leave AI in check or checkmate
}
// Check if move results in checkmate for the opponent
if (copy.isCheckmate(!isWhite)) {
System.out.println("Checkmate! AutoPlayer has won.");
// Optionally, return this move instead of null:
// return move;
return null;
}
Piece enemyKing = copy.findKing(!isWhite);
// Manhattan distance from this piece (after move) to enemy king
int dist = Math.abs(move.getToX() - enemyKing.getX()) + Math.abs(move.getToY() - enemyKing.getY());
int priority = -dist;
@ -93,13 +105,11 @@ public class AutoPlayer {
}
if (bestMoves.isEmpty()) {
System.out.println("Game Over! No legal moves for autoplayer.");
// Optionally: call a game over method on the board or game object here
return null;
}
// Randomly pick among best moves
Random rand = new Random();
int idx = rand.nextInt(bestMoves.size());
// Set last moved piece hash for next time
lastMovedPieceHash = movePieceHashes.get(idx);
return bestMoves.get(idx);
}