Here's a code snippet that implements the minimax algorithm for Tic-Tac-Toe in Python:
main.py919 chars31 lines
The minimax
function takes a Tic-Tac-Toe board as input, along with the current depth and whether it is maximizing or minimizing. If the function has reached a terminal state (either a win for X or a win for O, or a tie), it returns the corresponding score of -1, 1, or 0, respectively.
If it is maximizing, it tests each possible move for X and returns the maximum score found. If it is minimizing, it tests each possible move for O and returns the minimum score found. The math.inf
constants are used to initialize the best_score
variables to negative and positive infinity, respectively.
You can then use the minimax
function to make moves in the game. Here is an example game loop:
main.py836 chars34 lines
In this game loop, the program prompts the user to enter a row and column for their move. If the move is valid, it places an "O" on the board. Then, it uses the minimax
function to find the best move for the computer, and places an "X" on the board in that location.
The game ends when either X or O wins or the game is tied. The check_game_over
, print_board
, and check_winner
functions are left as exercises for the reader.
gistlibby LogSnag