I create a game with tic tac toe for fun. I built a minimax algorithm to return the optimal move for the computer, but somehow I get it wrong and get a wierd output like this
TIC TAC TOE V1.0
You can see that the computer chose the lower left corner, and not cut the player. My code is trying to recursively flip the flop between turns in all possible games, summing up the score for every win or loss that the turn may lead, and then returns the move with the maximum score. A printout is an estimate of each turn before it is made (you can see that it chooses the highest), so why don't I turn off the player? How can i fix this? Here is my code.
int compMoveScoreRecursive(state_t **board, int dimension, int row, int col, state_t turn) { board[row][col] = turn; state_t winner = checkWinner(board, dimension); if (winner == COMPUTER) { return 1; } else if (winner == PLAYER) { return -1; } else { int score = 0; state_t nextTurn = turn == COMPUTER ? PLAYER : COMPUTER; for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { if (board[i][j] == NIL) { state_t **boardCopy = copyBoard(board, dimension); score += compMoveScoreRecursive(boardCopy, dimension, i, j, nextTurn); destroyBoard(boardCopy, dimension); } } } return score; } } move_t optimalCompMove(state_t **board, int dimension) { move_t optMove; int optScore = INT_MIN; for (int row = 0; row < dimension; row++) { for (int col = 0; col < dimension; col++) { if (board[row][col] == NIL) { state_t **boardCopy = copyBoard(board, dimension); int score = compMoveScoreRecursive(boardCopy, dimension, row, col, COMPUTER); printf("%d, %d: %d\n", row, col, score); if (score > optScore) { optMove.row = row; optMove.col = col; optScore = score; } destroyBoard(boardCopy, dimension); } } } return optMove; }
shane source share