89 lines
2.4 KiB
Java
89 lines
2.4 KiB
Java
package chess.ai.minimax;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.util.concurrent.ExecutionException;
|
|
import java.util.concurrent.ExecutorService;
|
|
import java.util.concurrent.Executors;
|
|
import java.util.concurrent.Future;
|
|
|
|
import chess.ai.AI;
|
|
import chess.controller.CommandExecutor;
|
|
import chess.controller.commands.MoveCommand;
|
|
import chess.controller.commands.PromoteCommand;
|
|
import chess.controller.commands.PromoteCommand.PromoteType;
|
|
import chess.model.Color;
|
|
import chess.model.Coordinate;
|
|
import chess.model.Move;
|
|
|
|
public class AlphaBetaAI extends AI {
|
|
|
|
private final int searchDepth;
|
|
|
|
private static final float MAX_FLOAT = Float.MAX_VALUE;
|
|
private static final float MIN_FLOAT = -MAX_FLOAT;
|
|
|
|
private final ExecutorService threadPool;
|
|
|
|
public AlphaBetaAI(CommandExecutor commandExecutor, Color color, int searchDepth) {
|
|
super(commandExecutor, color);
|
|
this.searchDepth = searchDepth;
|
|
int threadCount = Runtime.getRuntime().availableProcessors() - 1;
|
|
this.threadPool = Executors.newFixedThreadPool(threadCount, new AlphaBetaThreadCreator(commandExecutor, color, threadCount));
|
|
System.out.println();
|
|
}
|
|
|
|
private Move getBestMove() {
|
|
List<Move> moves = getAllowedMoves();
|
|
List<Future<Float>> moveEvaluations = new ArrayList<>(50);
|
|
float bestMoveValue = MIN_FLOAT;
|
|
Move bestMove = null;
|
|
|
|
System.out.println("Evaluating " + moves.size() + " moves ...");
|
|
|
|
for (Move move : moves) {
|
|
moveEvaluations.add(this.threadPool.submit(() -> {
|
|
return AlphaBetaThreadCreator.getMoveValue(move, this.searchDepth);
|
|
}));
|
|
}
|
|
|
|
for (int i = 0; i < moves.size(); i++) {
|
|
Move move = moves.get(i);
|
|
float value = MIN_FLOAT;
|
|
try {
|
|
value = moveEvaluations.get(i).get();
|
|
} catch (InterruptedException | ExecutionException e) {
|
|
e.printStackTrace();
|
|
}
|
|
if (value > bestMoveValue) {
|
|
bestMoveValue = value;
|
|
bestMove = move;
|
|
}
|
|
}
|
|
|
|
System.out.println("Best move : " + bestMoveValue);
|
|
|
|
return bestMove;
|
|
}
|
|
|
|
@Override
|
|
public void onGameEnd() {
|
|
this.threadPool.close();
|
|
}
|
|
|
|
@Override
|
|
protected void play() {
|
|
long current = System.currentTimeMillis();
|
|
Move move = getBestMove();
|
|
long elapsed = System.currentTimeMillis() - current;
|
|
System.out.println("Took " + elapsed + "ms");
|
|
sendCommand(new MoveCommand(move));
|
|
}
|
|
|
|
@Override
|
|
protected void promote(Coordinate pawnCoords) {
|
|
sendCommand(new PromoteCommand(PromoteType.Queen));
|
|
}
|
|
|
|
}
|