fixed playMove for AutoPlayer

This commit is contained in:
Valentine GIRAL 2025-05-14 15:04:42 +02:00
parent 8016b91f97
commit d4ca88ca54
2 changed files with 33 additions and 79 deletions

View File

@ -2,86 +2,33 @@ package backend;
import java.util.ArrayList;
import java.util.Random;
public class AutoPlayer {
private Random rand = new Random();
/**
* returns the best Move to try on provided board for active player
* @param board
* @return
*/
public Move computeBestMove(Board board) {
ArrayList<Move> allMoves = new ArrayList<>();
Move bestMove = null;
int bestScore = Integer.MIN_VALUE;
//Detect Ai's color
boolean aiIsWhite = board.isTurnWhite();
//Go through all pieces on the board
for(Piece piece : board.getPieces()) {
//only choose the active color's piece
if(piece.isWhite() == board.isTurnWhite()) {
//Get valid moves for this piece
ArrayList<int[]> validMoves = board.getValidMoves(piece);
//convert each position into a move object
for (int[] dest : validMoves) {
Board simulatedBoard = new Board(board);//copy the board first
Piece simpiece = simulatedBoard.board[piece.getY()][piece.getX()]; //get matching piece in the copied board
Move move = new Move(piece, dest[0], dest[1]);
simulatedBoard.playMove(move);
allMoves.add(move);
}
}
}
//Pick a random move from the list
if (!allMoves.isEmpty()) {
return allMoves.get(rand.nextInt(allMoves.size()));
int score = evaluate(simulatedBoard, aiIsWhite);
}
return null;
if (score > bestScore) {
bestScore = score;
bestMove = new Move(piece, dest[0], dest[1]);//use original piece for
}
}
}
}
return bestMove;
}
//Helper method to score a board state
private int evaluate(Board board, boolean aiIsWhite) {
int score = 0;
for (Piece p : board.getPieces()) {
int value = 0;
switch (p.getType()) {
case Pawn:
value = 1;
break;
case Knight:
case Bishop:
value = 3;
break;
case Rook:
value = 5;
break;
case Queen:
value = 9;
break;
case King:
value = 1000;
break;
}
//Add value if iit's current turnn's color, subtract if opponent
if (p.isWhite() == aiIsWhite) {
score += value;
}
else {
score -= value;
}
}
return score;
}
}
}

View File

@ -430,13 +430,20 @@ public class Board {
//get current piece coordinate
int fromX = move.piece.getX();
int fromY = move.piece.getY();
int toX = move.toX;
int toY = move.toY;
Piece movingPiece = move.piece;
Piece capturedPiece = board[toY][toX]; // capture if any
moveHistory.add(new MoveRecord(movingPiece, capturedPiece, fromX, fromY, toX, toY,turnNumber, turnWhite));
//Remove the piece from the original position
board[fromX][fromY] = null;
board[fromY][fromX] = null;
//Update the internal position of the piece
move.piece.setX(move.toX);
move.piece.setY(move.toY);
move.piece.setX(toX);
move.piece.setY(toY);
//place the piece at the new position
board[move.toY][move.toX] = move.piece;
board[toY][toX] = move.piece;
//end turn logic
this.turnWhite = !this.turnWhite;