minimax algorithm for games with alternating turns positive number means player 1 wins negative number means player 2 wins, int minimax(gamestate g, char plyr) if plyr has won return 1 if plyr has lost return -1 if the game has ended in a draw return 0 score = -infinity for every move possible from g candidate = -minimax(g', opponent(plyr)) if (candidate == bestScorePossible) return candidate else if (candidate > score) score = candidate return score this calculates the best move 1 can make on their turn, with the assumption that 2 makes the best moves they can make on their turn (hence we take the negative of the score for minimax(g'), since it's the best score our opponent can get) to prevent duplicate calculations (e.g. where multiple search paths take us to the same game state) we can create a lookup table of game state we have already seen, and the score calculated for each of them - the first thing minimax does is look up g to see if it already has a score for it to further speed up the process, we can store the best result found so far, and terminate exploring a branch if it is already known to be worse than that as an additional speedup, but with loss of accuracy, we can also pass a maximum depth to explore and some scoring heuristics to estimate how well the player is doing at that point