Use threading for AI

main
Elnu 2 years ago
parent e08132376a
commit 2c5d9079cd

@ -25,6 +25,7 @@ public class Board {
King whiteKing;
final DrawingPanel panel;
final Graphics graphics;
public boolean aiThinking = false;
// The board is a two-dimensional array of nullable pieces
Piece[][] board;
@ -170,6 +171,7 @@ public class Board {
setup();
return;
}
if (aiThinking) return;
// Get board coordinate of mouse click
BoardCoordinate coordinate = new ScreenCoordinate(x, y).toBoard();
// If there's no piece there, return
@ -199,12 +201,18 @@ public class Board {
move(legalMove);
setLastMovedPieceAsMoved();
checkForCheckmate();
// Clear dragging
dragging = null;
// Redraw without dragging
draw();
if (!isGameOver) {
move(ChessAI.findBestMove(this));
setLastMovedPieceAsMoved();
checkForCheckmate();
try {
ChessAI.move(this);
} catch (Exception e) {
System.out.println(e);
}
return;
}
break;
}
}
}

@ -1,9 +1,32 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
public class ChessAI {
private static final int MAX_DEPTH = 3;
public static FutureTask<Void> move(Board board) {
Callable<Void> callable = new Callable<>() {
@Override
public Void call() throws Exception {
board.aiThinking = true;
Move move = findBestMove(board);
board.move(move);
board.setLastMovedPieceAsMoved();
board.checkForCheckmate();
board.draw();
board.aiThinking = false;
return null;
}
};
FutureTask<Void> future = new FutureTask<>(callable);
Thread thread = new Thread(future);
thread.start();
return future;
}
public static Move findBestMove(Board board) {
int bestScore = Integer.MIN_VALUE;