public void AIComputation() { // Keep spinning till allowed to compute the next move Debug.Log("Thread " + Thread.CurrentThread.ManagedThreadId + " waiting to compute!"); while (!terminateAllThreads && !this.doComputation) { ; } Debug.Log("Thread " + Thread.CurrentThread.ManagedThreadId + " starting computation."); if (terminateAllThreads) { // When the application is closed, make sure all threads die return; } this.isComputationDone = false; this.bestMove = this.computeBestMove(chessboardStateBeforeAIMove.CurrentMovingSide(), chessboardStateBeforeAIMove, 0); Debug.Log("Thread " + Thread.CurrentThread.ManagedThreadId + " finished computation."); this.isComputationDone = true; this.doComputation = false; this.AIComputation(); }
private Move computeBestMove(Side side, Chessboard chessboard, int presentCumulativeScore) { currentDepth++; // First, get the set of available moves List <Move> moves = new List <Move>(); Move bestMoveForIteration = new Move(null, null); bool isPlayingSide = chessboard.CurrentMovingSide() == side; foreach (AbstractPiece piece in chessboard.getActivePieces()) { if (piece.side == chessboard.CurrentMovingSide()) { foreach (Position movePosition in piece.GetSafeMovesForCurrentPosition().GetPositions()) { Move newMove = MoveEvaluator.EvaluateMove(new Move(piece, movePosition), isPlayingSide); moves = InsertionSortMove(moves, newMove); } } } if (moves.Count > 0) { bestMoveForIteration = moves.ToArray()[0]; if (currentDepth < maxAllowableDepth) { foreach (Move move in moves) { Chessboard copyChessboard = Chessboard.MakeCopyOfChessboard(chessboard); copyChessboard.MoveTo(copyChessboard.GetPieceAtPosition(move.getPiece().GetCurrentPosition()), move.getPosition()); copyChessboard.ChangeMovingSide(); int followUpScore = computeBestMove(side, copyChessboard, presentCumulativeScore + move.getScore()).getScore(); if (move.getScore() + followUpScore > bestMoveForIteration.getScore()) { bestMoveForIteration = move; } } } } currentDepth--; return(bestMoveForIteration); }
private static bool willMoveCheckmateOpponent(Move move) { bool willCheckmateOpponent = false; Chessboard gameStateAfterMove = Chessboard.MakeCopyOfChessboard(move.getPiece().GetChessboard()); AbstractPiece correspondingMovingPiece = gameStateAfterMove.GetPieceAtPosition(move.getPiece().GetCurrentPosition()); gameStateAfterMove.MoveTo(correspondingMovingPiece, move.getPosition()); if (gameStateAfterMove.IsKingInCheckmate(gameStateAfterMove.CurrentMovingSide())) { willCheckmateOpponent = true; } return(willCheckmateOpponent); }