last modification making it less dumb
This commit is contained in:
parent
a0033627cc
commit
99c3a5a2e4
|
|
@ -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<Piece> pieces = board.getPieces();
|
||||
boolean isWhite = board.isTurnWhite();
|
||||
|
|
@ -33,19 +30,20 @@ public class AutoPlayer {
|
|||
|
||||
ArrayList<Move> 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;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue