private void BestMove()
{
_functionCalls = 0;
_maxDepth = 0;
int bestScore = int.MinValue;
int moveX = -1;
int moveY = -1;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (_board[i][j] == PlayerType.None)
{
_board[i][j] = PlayerType.Computer;
int score = Minimax(0, false,int.MinValue,int.MaxValue);
_board[i][j] = PlayerType.None;
if (score > bestScore)
{
bestScore = score;
moveX = i;
moveY = j;
}
}
}
}
Debug.Log("Minimax Function Calls: " + _functionCalls);
Debug.Log("Max Depth: " + _maxDepth);
if(moveX != -1 && moveY != -1)
{
_board[moveX][moveY] = PlayerType.Computer;
StartCoroutine(PrintEnemyMove(moveX, moveY));
}
}
int Minimax(int depth, bool isMaximizing,int alpha, int beta)
{
_maxDepth = Mathf.Max(_maxDepth, depth);
_functionCalls++;
if (Winning(PlayerType.Human))
{
return -10;
}
else if (Winning(PlayerType.Computer))
{
return 10;
}
else if (IsItATie())
{
return 0;
}
int bestScore = -1;
if (isMaximizing)
{
bestScore = int.MinValue;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (_board[i][j] == PlayerType.None)
{
_board[i][j] = PlayerType.Computer;
int score = Minimax(depth + 1, false,alpha,beta);
bestScore = Mathf.Max(bestScore, score);
_board[i][j] = PlayerType.None;
alpha = Mathf.Max(alpha, bestScore);
if (beta <= alpha)
{
break;
}
}
}
}
return bestScore;
}
else
{
bestScore = int.MaxValue;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (_board[i][j] == PlayerType.None)
{
_board[i][j] = PlayerType.Human;
int score = Minimax(depth + 1, true, alpha, beta);
bestScore = Mathf.Min(bestScore, score);
_board[i][j] = PlayerType.None;
beta = Mathf.Min(beta, bestScore);
if (beta <= alpha)
{
break;
}
}
}
}
return bestScore;
}
}