diff --git a/src/Board.java b/src/Board.java index 8d6125f..0c1f5d9 100644 --- a/src/Board.java +++ b/src/Board.java @@ -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; } } } diff --git a/src/ChessAI.java b/src/ChessAI.java index f11128a..c047b01 100644 --- a/src/ChessAI.java +++ b/src/ChessAI.java @@ -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 move(Board board) { + Callable 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 future = new FutureTask<>(callable); + Thread thread = new Thread(future); + thread.start(); + return future; + } + public static Move findBestMove(Board board) { int bestScore = Integer.MIN_VALUE;