I am trying to create a simple chess AI in C# and have so far been successful to an extent using the minimax algorithm with alpha-beta pruning. However, with the code below it literally takes around 5 seconds for it to evaluate a move at depth 3 and I would like it to be faster if possible. I have been tinkering with it for hours and any change I make to it seems to just break the ai. Any help is greatly appreciated!
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[,] board1, int alpha, int beta, int depth, int team)
{
Piece[,] board = (Piece[,])board1.Clone();
if (depth == 0)
{
return evaluate(board);
}
if (team == Team.White)
{
List<Move> moves = getAllPossibleMoves(board, team);
int newBeta = beta;
foreach (Move moveName in moves)
{
fastMove(board, board[moveName.start.y, moveName.start.x], moveName);
newBeta = Mathf.Min(newBeta, evaluatePosition(board, 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)
{
fastMove(board, board[moveName.start.y, moveName.start.x], moveName);
newAlpha = Mathf.Max(newAlpha, evaluatePosition(board, alpha, beta, depth - 1, oppositeTeam(team)));
if (beta <= newAlpha) break;
}
return newAlpha;
}
}