From 20643dfd752ea29b5b6a0a188fe028da725d8fcc Mon Sep 17 00:00:00 2001 From: PIRANUT_PHLANG Date: Tue, 13 May 2025 12:12:30 +0200 Subject: [PATCH] un-finish AI implementation --- src/Main.java | 12 ++++++++++-- src/backend/AutoPlayer.java | 28 ++++++++++++++++++++++++++-- src/backend/Board.java | 5 +++-- 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/src/Main.java b/src/Main.java index 4a1017a..68b1ad9 100644 --- a/src/Main.java +++ b/src/Main.java @@ -3,8 +3,16 @@ import backend.Move; import backend.Piece; import backend.PieceType; import windowInterface.MyInterface; - - +import backend.Board; +import backend.Move; +import backend.Piece; +import backend.PieceType; +import windowInterface.MyInterface; +import backend.Board; +import backend.Move; +import backend.Piece; +import backend.PieceType; +import windowInterface.MyInterface; public class Main { diff --git a/src/backend/AutoPlayer.java b/src/backend/AutoPlayer.java index a988a22..960d406 100644 --- a/src/backend/AutoPlayer.java +++ b/src/backend/AutoPlayer.java @@ -1,5 +1,8 @@ package backend; +import java.util.ArrayList; +import java.util.Random; + public class AutoPlayer { @@ -8,9 +11,30 @@ public class AutoPlayer { * @param board * @return */ - public Move computeBestMove(Board board) { + public Move computeBestMove(Board board) {ArrayList possibleMoves = new ArrayList<>(); + boolean isWhiteTurn = board.isTurnWhite(); + + // Get all legal moves for all pieces of the current player + for (Piece piece : board.getPieces()) { + if (piece.isWhite() == isWhiteTurn) { + ArrayList legalPositions = board.getLegalMoves(piece); + for (int[] pos : legalPositions) { + Piece target = board.getPieceAt(pos[0], pos[1]); + Move move = new Move(piece, piece.getX(), piece.getY(), pos[0], pos[1], target); + possibleMoves.add(move); + } + } + } + + // If there are no moves available, return null + if (possibleMoves.isEmpty()) { + return null; + } + + // Pick one move randomly + Random rand = new Random(); + return possibleMoves.get(rand.nextInt(possibleMoves.size())); - return null; } diff --git a/src/backend/Board.java b/src/backend/Board.java index 8bddd66..fc7469a 100644 --- a/src/backend/Board.java +++ b/src/backend/Board.java @@ -148,7 +148,7 @@ public class Board { } - private ArrayList getLegalMoves(Piece piece) { + public ArrayList getLegalMoves(Piece piece) { ArrayList moves = new ArrayList<>(); int x = piece.getX(), y = piece.getY(); int dir = piece.isWhite() ? 1 : -1; @@ -266,11 +266,12 @@ public class Board { } public Board(String[] array) { + this.pieces = new ArrayList<>(); //TODO } - private Piece getPieceAt(int x, int y) { + public Piece getPieceAt(int x, int y) { for (Piece piece : pieces) { if (piece.getX() == x && piece.getY() == y) { return piece;