Workshop › Tic-tac-toe › Step 31 of 33

Look ahead: minimax

What we are doing

For a game still going, score tries every free cell for the player to move, scores each result with itself, undoes the move, and assumes both sides play their best: O takes the highest score, X the lowest. This is minimax.

```js
  if (end === 'draw') return 0
  const scores = []
  for (let index = 0; index < 9; index++) {
    if (cells[index] !== '') continue
    cells[index] = turn
    scores.push(score(cells, turn === 'O' ? 'X' : 'O'))
    cells[index] = ''
  }
  return turn === 'O' ? Math.max(...scores) : Math.min(...scores)
}
```

What it means

Your turn

In score, under if (end === 'draw') return 0, write the new lines, above the function's closing }.

Skills: Functions, Loops

All steps

  1. Get the canvas and the pen
  2. Paint the board
  3. The first grid line
  4. Repeat with a loop
  5. Finish the grid
  6. The board as a list
  7. A function that draws
  8. Write an X
  9. From cell number to position
  10. Draw what the board holds
  11. A color for each mark
  12. Make a move
  13. No playing on a taken cell
  14. Listen for clicks
  15. Which cell was clicked?
  16. Clicks on any screen size
  17. The eight winning lines
  18. Find three in a row
  19. Win, draw or go on
  20. The round ends
  21. Show who won
  22. Light up the winning line
  23. A function for a fresh round
  24. Click to play again
  25. A computer that picks a cell
  26. The computer answers
  27. Rule one: take the center
  28. Rule two: win when you can
  29. Rule three: block the opponent
  30. Score a finished game
  31. Look ahead: minimax
  32. A computer that never loses
  33. Build it yourself: keep score