Find the best tic-tac-toe move with depth-aware minimax

Why it matters Depth-aware game-tree search is the baseline every game-playing RL agent is tested against.

Plain minimax treats every win the same. A good agent should win as fast as possible and lose as slowly as possible.

Write best_move(board). board is a 9-character string of "X", "O" and "." (row by row). X moves first, so it is X's turn if the counts are equal, else O's turn. The board is not finished and has at least one empty square. Score from the point of view of the player to move: if perfect play leads to a win on the k-th move from now (counting this move as 1), the score is 11 - k; a loss on the k-th move scores -(11 - k); a draw scores 0. Both sides play perfectly under this scoring. Return (index of the best move, its score), choosing the lowest index on ties. Memoise so the empty board is fast.

Signaturedef best_move(board)

Example

best_move("XOO....X.") gives (6, 8).

Understand the idea

Minimax assumes both players play perfectly: you pick the move that is best for you, knowing the opponent will then pick what is worst for you. Negamax writes this with one rule: my score for a move is minus the opponent's best score afterwards.

If all wins score the same, the search cannot tell "win now" from "win in three moves", and may dawdle. Adding depth fixes it: a win on the k-th move scores 11 - k, so winning now (k = 1) scores 10 and winning on your next turn (k = 3) scores 8.

Example: on board "XOO....X." the X player can set up a double threat at square 6; the opponent replies, and X wins on move 3, score 8.

Rule: v(move) = 10 if it wins, 0 if the board fills, else -best(child) moved 1 toward 0.

The same depth trick is used in chess engines as "mate in n" scoring.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplebest_move('XOO....X.')
  • Sample 2: immediate winbest_move('XOO.X....')