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 "O".

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 0.

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 has_won() and 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 1. If "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 0.



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 False otherwise.


We’ve given you four different boards to test your function. Call game_is_over() on the boards start_board, x_won, o_won, and 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 1 if "X" won, a -1 if "O" won, and a 0 otherwise.


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!

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?