An essential step in the minimax function is evaluating the strength of a leaf. If the game gets to a certain leaf, we want to know if that was a better outcome for player
"X" or for player
Here’s one potential evaluation function:
a leaf where player
"X" wins evaluates to a
1, a leaf where player
"O" wins evaluates to a
-1, and a leaf that is a tie evaluates to
Let’s write this evaluation function for our game of Tic-Tac-Toe.
First, we need to detect whether a board is a leaf — we need know if the game is over. A game of Tic-Tac-Toe is over if either player has won, or if there are no more open spaces. We can write a function that uses
available_moves() to check to see if the game is over.
If the game is over, we now want to evaluate the state of the board. If
"X" won, the board should have a value of
"O" won, the board should have a value of
-1. If neither player won, it was a tie, and the board should have a value of
At the bottom of
script.py, create a function called
game_is_over() that takes a
board as a parameter. The function should return
True if the game is over and
We’ve given you four different boards to test your function. Call
game_is_over() on the boards
tie. Print the result of each.
Let’s write another function called
evaluate_board() that takes
board as a parameter. This function will only ever be called if we’ve detected the game is over. The function should return a
"X" won, a
"O" won, and a
Test your function on the four different boards! For each board, write an if statement checking if the game is over. If it is, evaluate the board and print the result. You just wrote the base case of the minimax algorithm!