From ef14d4973d05aa19c4fa81f5896f82ffdd8a7423 Mon Sep 17 00:00:00 2001 From: Jerome Bedier Date: Thu, 22 May 2025 22:38:51 +0200 Subject: [PATCH] autoplayer work but random for the moment --- src/backend/AutoPlayer.java | 43 +++++++++++++++++++++++++------------ src/backend/Board.java | 32 +++++++++++++++++++++++++-- 2 files changed, 59 insertions(+), 16 deletions(-) diff --git a/src/backend/AutoPlayer.java b/src/backend/AutoPlayer.java index a48c0c2..6b6fd6b 100644 --- a/src/backend/AutoPlayer.java +++ b/src/backend/AutoPlayer.java @@ -1,17 +1,32 @@ package backend; +import java.util.ArrayList; +import java.util.Random; + public class AutoPlayer { - - - /** - * returns the best Move to try on provided board for active player - * @param board - * @return - */ - public Move computeBestMove(Board board) { - - return null; - } - - -} + + /** + * Returns a random legal move for the active player. + */ + public Move computeBestMove(Board board) { + ArrayList pieces = board.getPieces(); + ArrayList allMoves = new ArrayList<>(); + boolean isWhite = board.isTurnWhite(); + + // Collect all legal moves for all of the active player's pieces + for (Piece piece : pieces) { + if (piece.isWhite() == isWhite) { + ArrayList moves = board.getLegalMoves(piece); + allMoves.addAll(moves); + } + } + + if (allMoves.isEmpty()) { + return null; // No moves = checkmate or stalemate + } + + // Pick a random move + Random rand = new Random(); + return allMoves.get(rand.nextInt(allMoves.size())); + } +} \ No newline at end of file diff --git a/src/backend/Board.java b/src/backend/Board.java index 5b36502..036af0d 100644 --- a/src/backend/Board.java +++ b/src/backend/Board.java @@ -516,9 +516,37 @@ public class Board { } - public Board(Board board) { - //TODO + public Board(Board original) { + this.width = original.width; + this.height = original.height; + this.turn = original.turn; + this.selectedX = original.selectedX; + this.selectedY = original.selectedY; + this.enPassantCol = original.enPassantCol; + this.enPassantRow = original.enPassantRow; + // Deep copy the board array and pieces + this.board = new Piece[width][height]; + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + Piece p = original.board[x][y]; + if (p != null) { + this.board[x][y] = new Piece(p.isWhite(), p.getType(), x, y); + } else { + this.board[x][y] = null; + } + } + } + // Deep copy highlightedSquares + this.highlightedSquares = new boolean[width][height]; + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + this.highlightedSquares[x][y] = original.highlightedSquares[x][y]; + } + } + + // Undo stack is not copied (empty) + this.undoStack = new Stack<>(); }//test