From 99c3a5a2e418b6b51db4a82482d23e2ca9533ad0 Mon Sep 17 00:00:00 2001 From: Jerome Bedier Date: Thu, 22 May 2025 23:37:08 +0200 Subject: [PATCH] last modification making it less dumb --- src/backend/AutoPlayer.java | 36 +++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/src/backend/AutoPlayer.java b/src/backend/AutoPlayer.java index 98da544..ae1e91b 100644 --- a/src/backend/AutoPlayer.java +++ b/src/backend/AutoPlayer.java @@ -5,17 +5,14 @@ import java.util.List; import java.util.Random; public class AutoPlayer { - private Integer lastMovedPieceHash = null; // Use piece's position and color for tracking + private Integer lastMovedPieceHash = null; // Track the last moved piece public Move computeBestMove(Board board) { - // Stop if only one king is left + // Count kings int kingCount = 0; for (Piece piece : board.getPieces()) { if (piece.getType() == PieceType.King) kingCount++; } - if (kingCount <= 1) { - return null; - } ArrayList pieces = board.getPieces(); boolean isWhite = board.isTurnWhite(); @@ -33,19 +30,20 @@ public class AutoPlayer { ArrayList moves = board.getLegalMoves(piece); for (Move move : moves) { + // Prevent king captures: simulate move and skip if enemy king would be removed Board copy = new Board(board); copy.playMove(move); - Piece enemyKing = copy.findKing(!isWhite); - if (enemyKing == null) { - // Move that captures the king (not standard chess, but per your requirements) - // Remember which piece makes this move - bestMoves.clear(); - bestMoves.add(move); - movePieceHashes.clear(); - movePieceHashes.add(pieceHash); - bestPriority = Integer.MAX_VALUE; - break; + int kingsAfterMove = 0; + for (Piece p : copy.getPieces()) { + if (p.getType() == PieceType.King) kingsAfterMove++; } + if (kingsAfterMove < 2) { + // This move would remove a king, so stop AI completely + System.out.println("Game Over! Attempted king capture. AutoPlayer will stop."); + 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; @@ -68,7 +66,11 @@ public class AutoPlayer { } } } - if (bestMoves.isEmpty()) return null; + 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()); @@ -77,7 +79,7 @@ public class AutoPlayer { return bestMoves.get(idx); } - // Optional: Call this after a human move to reset tracking + // Call this after a human move to reset tracking public void resetLastMovedPiece() { lastMovedPieceHash = null; }