Game-Playing AI: Minimax
Game AIs look ahead and assume the opponent plays their best — choosing the move that is safest against it.
What you will learn
- Explain minimax in plain words
- Score positions with a simple evaluation
- See why looking ahead beats greedy moves
Thinking ahead in games
How does a computer play tic-tac-toe or chess? It imagines future moves: my move, then your best reply, then my best reply… and picks the move that works out best assuming you play perfectly.
That assumption gives the method its name. You (the AI) try to maximise your score; the opponent tries to minimise it — so it is called minimax.
Scoring an end position
First we need a number for how good a finished game is, from the AI’s point of view:
def score(board):
if wins(board, 'AI'): return +1 # AI won
if wins(board, 'Human'): return -1 # AI lost
return 0 # draw
# AI prefers +1, avoids -1, accepts 0 if that is the best it can forceNote: Output: (No output — score() turns a finished board into a number minimax can compare.)
The minimax idea
- On the AI’s turn, try every move and pick the one with the highest resulting score.
- On the opponent’s turn, assume they pick the move with the lowest score (worst for the AI).
- Repeat down the tree of possibilities to the end of the game, then bubble the scores back up.
def minimax(board, ai_turn):
if game_over(board):
return score(board)
results = [minimax(make_move(board, m), not ai_turn)
for m in legal_moves(board)]
return max(results) if ai_turn else min(results)Note: Output: (For an empty tic-tac-toe board the AI’s best score is 0 — with perfect play tic-tac-toe is always a draw. That is why you can never beat a good tic-tac-toe AI.)
Watch out: Minimax explores every future move, so the tree explodes for big games. Chess engines add tricks (pruning, depth limits, smarter scoring) so they do not have to look at every possibility.
Tip: Looking ahead beats being greedy. A greedy player grabs the move that looks best right now; minimax picks the move that is best after the opponent replies — which is why it does not fall for traps.
Q. Why is the algorithm called “minimax”?
✍️ Practice
- Write the
score()values for three finished tic-tac-toe boards (AI win, loss, draw). - Explain why minimax never loses at tic-tac-toe.
🏠 Homework
- In words, describe what changes are needed to use minimax for Connect-4 instead of tic-tac-toe.