diff --git a/src/backend/AutoPlayer.java b/src/backend/AutoPlayer.java index 3b6c32e..ae1c533 100644 --- a/src/backend/AutoPlayer.java +++ b/src/backend/AutoPlayer.java @@ -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); }