Learn
Minimax
Copying Boards

One of the central ideas behind the minimax algorithm is the idea of exploring future hypothetical board states. Essentially, we’re saying if we were to make this move, what would happen. As a result, as we’re implementing this algorithm in our code, we don’t want to actually make our move on the board. We want to make a copy of the board and make the move on that one.

Let’s look at how copying works in Python. Let’s say we have a board that looks like this

my_board = [ ["X", "2", "3"], ["O", "O", "6"], ["X", "8", "9"] ]

If we want to create a copy of our board our first instinct might be to do something like this

new_board = my_board

This won’t work the way we want it to! Python objects are saved in memory, and variables point to a location in memory. In this case, new_board, and my_board are two variables that point to the same object in memory. If you change a value in one, it will change in the other because they’re both pointing to the same object.

One way to solve this problem is to use the deepcopy() function from Python’s copy library.

new_board = deepcopy(my_board)

new_board is now a copy of my_board in a different place in memory. When we change a value in new_board, the values in my_board will stay the same!

Instructions

1.

Let’s begin by failing to create a deep copy of my_board. Create a variable named new_board and set it equal to my_board.

2.

Call the select_space() function using new_board as a parameter to put an "O" in the center of the board. Print out both new_board and my_board using print_board() to see if making a move on the new board affected the old board.

3.

Change how you create new_board. Set it equal to deepcopy(my_board). What happens when you call select_space() now?

Folder Icon

Sign up to start coding

Already have an account?