View the code for this blog post.

Introduction

Last week, I wrote about figuring out how to implement the minimax algorithm in Python for my tic-tac-toe solver. I hadn’t yet dug too deeply into the different ways that I could optimize yet, so this week I ran a couple of experiments to get an idea of how things could improve.

My goal was really to find out the factor by which this optimization improves the minimax algorithm.

Alpha-Beta Pruning

Alpha-beta pruning is an optimization technique built upon the minimax algorithm which allows for faster decision making and analysis. Whereas minimax itself answers the question: “Given the state of the game, possible moves, and each player’s objective, what is the value of the current board to the current player?”

Alpha-beta pruning asks during the search and evaluation of these possible moves: “Given what we know about our opponent’s best options across what we’ve seen so far, is it even worth checking out the rest of the possibilities from this particular game state?”

For instance, imagine if from a particular game state, you had five possible moves. But you knew that in order to get there, your opponent will have had to chosen suboptimally (i.e. choosing a path that doesn’t give them the best chance of success/score). You can stop at a certain point and say, alright - looking at what has to happen for me to get these (potentially good) possibilities, my opponent would have to basically let me win. It’s not worth investigating all the results of scenarios that they’re never going to let happen.

Here’s a look at my minimax algorithm without pruning:

def _minimax(self, curr_board : 'Board', available: list[tuple[int]], used: list[int], player: str) -> int:
    """Implemented as a backtracking postorder algorithm traversing the implicit tree of choices given an initial board state.
    """
    if curr_board.is_finished():
        winner = curr_board.game_winner()
        if winner == 'X':
            return 1
        elif winner == 'O':
            return -1
        else:
            return 0
    
    # check whether to maximize value (X) or minimize value (O)
    optimal = maxsize * -1 if player == 'X' else maxsize
    
    for i in range(len(available)):
        if not used[i]:
            spot = available[i]
            used[i] = 1
            #mark the board
            curr_board.mark(spot, player)

            # return and store the value of the marked board, associate it with the position
            next_player = 'O' if player == 'X' else 'X'
            value = self._minimax(curr_board, available, used, next_player)
            if player == 'X':
                optimal = max(optimal, value)
            else:
                optimal = min(optimal, value)

            # unmark the board & restore availability
            curr_board._unmark(spot)
            used[i] = 0

    return optimal

And here it is with pruning:

def _minimax_ab(self, curr_board : 'Board', available: list[tuple[int]], used: list[int], alpha: int, beta: int, player: str) -> int:
    """Implemented as a backtracking postorder algorithm traversing the implicit tree of choices given an initial board state.
    """
    if curr_board.is_finished():
        winner = curr_board.game_winner()
        if winner == 'X':
            return 1
        elif winner == 'O':
            return -1
        else:
            return 0
    
    # check whether to maximize value (X) or minimize value (O)
    optimal = maxsize * -1 if player == 'X' else maxsize
    
    for i in range(len(available)):
        if not used[i]:
            spot = available[i]
            used[i] = 1
            #mark the board
            curr_board.mark(spot, player)

            # return and store the value of the marked board, associate it with the position
            next_player = 'O' if player == 'X' else 'X'
            value = self._minimax_ab(curr_board, available, used, alpha, beta, next_player)
            if player == 'X':
                optimal = max(optimal, value)
                alpha = max(alpha, value)
            else:
                optimal = min(optimal, value)
                beta = min(beta, value)

            # unmark the board & restore availability
            curr_board._unmark(spot)
            used[i] = 0
            if beta <= alpha:
                break

    return optimal

Was it worth implementing? Well, I benchmarked the data on my 2021 M1 Macbook Pro with 16GB of memory.

Computer Plays First, No Optimization:

Time Elapsed (ms)
Round #Game #1Game #2Game #3Game #4Average
1643.1366641.2870634.3617667.2151646.5001
219.492120.566519.932119.599019.8974
30.51150.97450.72890.59600.7027
40.07600.12300.11380.07730.0975
50.02130.02240.01730.03800.02475

Computer Plays Second, No Optimization:

Time Elapsed (ms)
Round #Game #1Game #2Game #3Game #4Average
190.467989.688590.124989.707989.9973
23.49583.52443.49793.51253.50765
30.22450.19890.17560.26170.215175
40.07480.02440.10540.12100.0814

Computer Plays First, Alpha-Beta Optimization:

Time Elapsed (ms)
Round #Game #1Game #2Game #3Game #4Average
142.002242.855441.397542.287242.135575
22.96193.15673.93821.70982.94165
30.27370.37290.20370.38250.3082
40.06270.06850.06440.02640.0555
50.02540.02410.01940.02270.0229

Computer Plays Second, Alpha-Beta Optimization:

Time Elapsed (ms)
Round #Game #1Game #2Game #3Game #4Average
18.26278.00577.98948.58668.2111
21.21421.03541.63001.22721.2767
30.13670.15120.19060.18630.1662
40.04230.04220.01900.04560.037275

Wow! To focus on the most dramatic difference, check out that first move where the computer has analyze the best move from the empty game tree.

From an average decision time of 646.5001 ms to 42.1356 ms - that’s a speed up of 15.3433 times! So those data speak for themselves here; alpha-beta pruning is really an incredible optimization technique. Even playing the game myself, the difference was immediately noticeable.

Setbacks

You may have noticed that my code for the standard minimax algorithm looks a little bit different from my previous blog post. It turns out, I ran into a similar issue after attempting to implement alpha-beta pruning as I did when I was using a set to track available positions! That is, my AI was suddenly making suboptimal and predictable moves, seemingly not properly taking into account what I was doing.

My hypothesis: While a queue that functioned like a round-robin scheduler worked for the suboptimal implementation of the problem, it was likely only so because each evaluated spot was popped and re-appended in order AND able to complete a full cycle. The list of available positions was basically able to go “around” like it was supposed to.

But with alpha-beta pruning, the “cycle” was (by design!) not being completed (or at least, it’s not guaranteed to be). By not exploring all of the next possible states from a given position/game state, we were only “turning” the scheduler part-way, replicating a similar error as the set produced in my original for loop implementation.

Thankfully, I realized that the issue was less of an understanding of minimax/alpha-beta pruning itself, and much closer to my understanding of backtracking and how to keep track of valid choices. This video (which was once kind of hard for me to grok!) helped me to see that I was, again, over complicating my data structures! By maintaining a boolean array used where each index corresponded to whether or not a position had be “picked”/used already, I was able to apply and revert changes to my game state without an insane amount of extra logic or overhead. I also really appreciate that it doesn’t ask for too much extra memory (at most for a 3x3 board it will have 9 spaces) and feels a bit more idiomatic.

The extra time spent building the array at the start of choice evaluation also seemed minimal for the ease of use/further optimization that it provided!

Conclusion

Studying minimax and alpha-beta pruning really helped me to solidify my understanding of backtracking, and learn a little bit more about game trees and how computers make decisions. I’d like to come back to this project in the future and keep experimenting even more - maybe with larger tic-tac-toe games, or different games with variations on evaluation functions.

Slowing down and trying to think of things plainly - while also giving myself room to make imperfect decisions - is really, really helpful in honing my ability to use the right data structures. Not only that but it helps my confidence too - I’m super excited to try out boolean arrays in other backtracking problems now!

My main goal for this sector of the project was to find out the factor by which alpha-beta pruning improved the minimax algorithm. And I was really shocked at how dramatic the difference felt! Tweaking the original algorithm was a worthwhile exercise in testing how much I understood the rationale behind the code, and making it more robust means that it’ll (hopefully) be easier to return to in the future.

Next steps would probably be getting a more solid understanding of fail-hard vs. fail-soft alpha-beta pruning, and other algorithms like Monte-Carlo.

I’m still learning about the topics above, and if there are any errors, tips, or comments you’d like to share with me regarding anything I’ve discussed, I’d love to hear from you! Get in touch: mailto:reachout@nicholasboyce.dev