AI Beyond Language Models ยท Search and Games
Minimax: Thinking One Move Ahead
Game-playing AI assumes the opponent plays well. For each move, find the worst reply you could face, then pick the move whose worst case is best.
minimax.py
# Minimax: choose the move that is best for you, assuming the opponent then replies with what is worst for you.
tree = {"left": [3, 12], "middle": [8, 2], "right": [14, 1]} # your score after each possible reply
moves = list(tree)
values = []
for move in moves:
worst = min(tree[move]) # the opponent picks the reply that is worst for you
values.append(worst)
best = moves[values.index(max(values))]
print("play", best)
Step by step
- Three possible moves. For each, the opponent has two replies, and these are your scores after them.
- The move names, in order.
- One value per move: the score you can count on.
- "left": the replies give you 3 or 12.
- The opponent will pick the reply that is worst for you: 3.
- 3 is added to the end of the list that
values points to. move changes from 'left' to 'middle'.- "middle": 8 or 2. The opponent picks 2.
- 2 is added to the end of the list that
values points to. move changes from 'middle' to 'right'.- "right" has the biggest prize, 14, but the opponent will reply with 1.
- 1 is added to the end of the list that
values points to. - Python moves to the next item of the loop:
for move in moves. - Your move: the one with the highest guaranteed score (max of the mins).
- Play left: you are sure of at least 3. Real game programs run minimax many moves deep, skip branches that cannot matter (alpha-beta pruning), and use a guess of the score where they stop looking.