package backend; import java.util.ArrayList; import java.util.Random; public class AutoPlayer { public Move computeBestMove(Board board) { boolean isWhite = board.isTurnWhite(); ArrayList allMoves = new ArrayList<>(); ArrayList pieces = board.getPieces(); for (int i = 0; i < pieces.size(); i++) { Piece piece = pieces.get(i); if (piece.isWhite() == isWhite) { ArrayList moves = board.getValidMoves(piece); for (int j = 0; j < moves.size(); j++) { int[] moveCoords = moves.get(j); int toX = moveCoords[0]; int toY = moveCoords[1]; int fromX = piece.getX(); int fromY = piece.getY(); Piece captured = board.getPieceAt(toX, toY); // Detect en passant if (piece.getType() == PieceType.Pawn && board.isEnPassant() && toX == board.getXCoordinatePawn() && toY == (piece.isWhite() ? board.getYCoordinatePawn() - 1 : board.getYCoordinatePawn() + 1)) { captured = board.getPieceAt(board.getXCoordinatePawn(), board.getYCoordinatePawn()); } // --- Castling detection --- if (piece.getType() == PieceType.King && Math.abs(toX - fromX) == 2 && toY == fromY) { System.out.println("AI considering castling move."); // No need to set captured, just allow the move } Move move = new Move(piece, piece.getX(), piece.getY(), toX, toY, captured); allMoves.add(move); } } } if (allMoves.isEmpty()) { return null; // no legal moves → maybe stalemate or checkmate } // === Basic Evaluation: Prefer capturing higher-value pieces === Move bestMove = allMoves.get(0); int bestScore = evaluateCapture(bestMove.getCaptured()); for (int i = 1; i < allMoves.size(); i++) { Move move = allMoves.get(i); int score = evaluateCapture(move.getCaptured()); if (score > bestScore) { bestMove = move; bestScore = score; } } return bestMove; } // Simple evaluation: return value of captured piece, or 0 if no capture private int evaluateCapture(Piece captured) { if (captured == null) return 0; PieceType type = captured.getType(); if (type == PieceType.Pawn) return 1; if (type == PieceType.Knight || type == PieceType.Bishop) return 3; if (type == PieceType.Rook) return 5; if (type == PieceType.Queen) return 9; return 0; // king shouldn't be captured anyway } }