I use minimax algorithm and alphabeta pruning to implement the caro (tictactoe) game. Then i use the bestMove function to find the movement for the bot. But the index of bestmove always 0,1,2,3... so what's the wrong with my code.
Here's my minimax function
int game::minimax(int depth, bool maximizingPlayer, int scores[], int h, int board[][12], int alpha, int beta )
{
int count = size * size;
if (depth == h)
return 0;
if (maximizingPlayer)
{
int best = INT_MIN;
for (int i = 0; i < 144; i++)
{
int row = i / 12;
int col = i % 12;
if (board[row][col] == 0)
{
board[row][col] = 1;
count--;
if (win()&&(count%2==1)) {
board[row][col] = 0;
return 10;
}
if (draw()) {
board[row][col] =0;
return 0;
}
best = max(best, minimax(depth + 1, !maximizingPlayer, scores, h, board, alpha, beta));
alpha = max(alpha, best);
board[row][col] = 0;
if (beta <= alpha) {
break;
}
}
}
return best;
}
else
{
int best = INT_MAX;
for (int i = 0; i < 144; i++)
{
int row = i / 12;
int col = i % 12;
if (board[row][col] == 0)
{
board[row][col] = 2;
count--;
if (win()&&(count % 2 == 0)) {
board[row][col] = 0;
return -10;
}
if (draw()) {
board[row][col] = 0;
return 0;
}
best = min(best, minimax(depth + 1, !maximizingPlayer, scores, h, board, alpha, beta));
beta = min(beta, best);
board[row][col] = 0;
if (beta <= alpha) {
break;
}
}
}
return best;
}
}
here is my findMove for bot function
int game::bestMove(int board[][size]) {
int scores[1] = { 0 };
int bestMove = -1;
int bestValue = -1000;
int count = size * size;
for (int i = 0; i < size*size; i++)
{
int row = i / 12;
int col = i % 12;
if (board[row][col] == 0)
{
board[row][col] = 2;
count--;
if (win()&&(count % 2 == 0)) {
board[row][col] = 0;
return i;
}
if (draw()) {
board[row][col] = 0;
return i;
}
int moveValue = minimax(0, false, scores, 2, board, INT_MIN, INT_MAX);
board[row][col] = 0;
if (moveValue > bestValue)
{
bestValue = moveValue;
bestMove = i;
}
}
}
return bestMove;
}
i can't know why the bestMove function always return the value in ordered begin 0,1,2,...
so the move of Bot is alway consecutive row by row, line by line ( O is bot)