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

  1. Three possible moves. For each, the opponent has two replies, and these are your scores after them.
  2. The move names, in order.
  3. One value per move: the score you can count on.
  4. "left": the replies give you 3 or 12.
  5. The opponent will pick the reply that is worst for you: 3.
  6. 3 is added to the end of the list that values points to.
  7. move changes from 'left' to 'middle'.
  8. "middle": 8 or 2. The opponent picks 2.
  9. 2 is added to the end of the list that values points to.
  10. move changes from 'middle' to 'right'.
  11. "right" has the biggest prize, 14, but the opponent will reply with 1.
  12. 1 is added to the end of the list that values points to.
  13. Python moves to the next item of the loop: for move in moves.
  14. Your move: the one with the highest guaranteed score (max of the mins).
  15. 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.