I have little experience with any sort of chess AI and am at a complete loss as to why it still takes a couple of seconds to calculate a decent move even at just depth 3. Here is the code:
private void makeAIMove(Piece[,] board)
{
Move bestMove;
int score;
List<Piece[,]> possiblePositions = getAllPossiblePositions(board, Team.Black);
List<Move> possibleMoves = getAllPossibleMoves(board, Team.Black);
bestMove = possibleMoves[0];
score = evaluatePosition(possiblePositions[0], int.MinValue, int.MaxValue, DEPTH, Team.White);
if (numTurns > 0)
{
for (int i = 1; i < possiblePositions.Count; i++)
{
int pos = evaluatePosition(possiblePositions[i], int.MinValue, int.MaxValue, DEPTH, Team.White);
if (pos >= score)
{
bestMove = possibleMoves[i];
score = pos;
}
}
}
else
{
bestMove = possibleMoves[Random.Range(0, possibleMoves.Count)];
}
numTurns += 1;
updateBoard(bestMove);
}
private int evaluatePosition(Piece[,] board, int alpha, int beta, int depth, int team)
{
if (depth == 0)
{
return evaluate(board);
}
if (team == Team.White)
{
List<Move> moves = getAllPossibleMoves(board, team);
int newBeta = beta;
foreach (Move moveName in moves)
{
Piece[,] newBoard = (Piece[,])board.Clone();
newBoard = move(newBoard, newBoard[moveName.start.y, moveName.start.x], moveName.start, moveName.end);
newBeta = Mathf.Min(newBeta, evaluatePosition(newBoard, alpha, beta, depth - 1, oppositeTeam(team)));
if (newBeta <= alpha) break;
}
return newBeta;
}
else
{
List<Move> moves = getAllPossibleMoves(board, team);
int newAlpha = alpha;
foreach (Move moveName in moves)
{
Piece[,] newBoard = (Piece[,])board.Clone();
newBoard = move(newBoard, newBoard[moveName.start.y, moveName.start.x], moveName.start, moveName.end);
newAlpha = Mathf.Max(newAlpha, evaluatePosition(newBoard, alpha, beta, depth - 1, oppositeTeam(team)));
if (beta <= newAlpha) break;
}
return newAlpha;
}
}
int[] scoreTable = new int[]
{
1, 3, 3, 5, 9, 999 // Value of each piece
};
private int evaluate(Piece[,] board)
{
int blackScore = 0;
int whiteScore = 0;
for (int i = 0; i < 8; ++i)
{
for (int j = 0; j < 8; ++j)
{
if (board[i, j].team != Team.None)
{
if (board[i, j].team == Team.White)
{
whiteScore += scoreTable[board[i, j].name];
}
else
{
blackScore += scoreTable[board[i, j].name];
}
}
}
}
return blackScore - whiteScore;
}