From 7bdd9fdc836cb918a73eab9b84a56fb0f32c6943 Mon Sep 17 00:00:00 2001 From: Persson-dev Date: Mon, 21 Apr 2025 14:31:58 +0200 Subject: [PATCH] improve ai (sort moves) --- .../java/chess/ai/minimax/AlphaBetaAI.java | 7 ++++--- .../chess/ai/minimax/AlphaBetaThread.java | 20 +++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/chess/ai/minimax/AlphaBetaAI.java b/app/src/main/java/chess/ai/minimax/AlphaBetaAI.java index 092c111..56e987a 100644 --- a/app/src/main/java/chess/ai/minimax/AlphaBetaAI.java +++ b/app/src/main/java/chess/ai/minimax/AlphaBetaAI.java @@ -28,9 +28,8 @@ public class AlphaBetaAI extends AI { public AlphaBetaAI(CommandExecutor commandExecutor, Color color, int searchDepth) { super(commandExecutor, color); this.searchDepth = searchDepth; - int threadCount = Runtime.getRuntime().availableProcessors() - 1; + int threadCount = Runtime.getRuntime().availableProcessors() / 2; this.threadPool = Executors.newFixedThreadPool(threadCount, new AlphaBetaThreadCreator(commandExecutor, color, threadCount)); - System.out.println(); } private Move getBestMove() { @@ -48,7 +47,9 @@ public class AlphaBetaAI extends AI { } for (int i = 0; i < moves.size(); i++) { + System.out.printf("Progress : %.2f %% ", (float) (i) / moves.size() * 100.0f); Move move = moves.get(i); + System.out.print("\r"); float value = MIN_FLOAT; try { value = moveEvaluations.get(i).get(); @@ -61,7 +62,7 @@ public class AlphaBetaAI extends AI { } } - System.out.println("Best move : " + bestMoveValue); + System.out.println("Best move : " + bestMoveValue + " "); return bestMove; } diff --git a/app/src/main/java/chess/ai/minimax/AlphaBetaThread.java b/app/src/main/java/chess/ai/minimax/AlphaBetaThread.java index c5e919c..9f32337 100644 --- a/app/src/main/java/chess/ai/minimax/AlphaBetaThread.java +++ b/app/src/main/java/chess/ai/minimax/AlphaBetaThread.java @@ -1,6 +1,10 @@ package chess.ai.minimax; +import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.Map; +import java.util.Map.Entry; import chess.ai.PieceCost; import chess.ai.PiecePosCost; @@ -76,7 +80,23 @@ public class AlphaBetaThread extends Thread { if (moves.isEmpty()) return getEndGameEvaluation(); + List> movesCost = new ArrayList<>(moves.size()); + for (Move move : moves) { + this.simulation.tryMove(move); + movesCost.add(Map.entry(move, getBoardEvaluation())); + this.simulation.undoMove(); + } + + Collections.sort(movesCost, (first, second) -> { + return Float.compare(first.getValue(), second.getValue()); + }); + + if (depth == 1) + return -movesCost.getFirst().getValue(); + + for (var moveEntry : movesCost) { + Move move = moveEntry.getKey(); this.simulation.tryMove(move); value = Float.max(value, -negaMax(depth - 1, -beta, -alpha)); this.simulation.undoMove();