Use threading for AI

main
Elnu 2 years ago
parent e08132376a
commit 2c5d9079cd

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

@ -1,9 +1,32 @@
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
public class ChessAI { public class ChessAI {
private static final int MAX_DEPTH = 3; 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) { public static Move findBestMove(Board board) {
int bestScore = Integer.MIN_VALUE; int bestScore = Integer.MIN_VALUE;