Workshop › Tic-tac-toe › Step 31 of 33
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)
}
```continue skips taken ones.score(...) calls itself with the other player to move: a function that calls itself is recursive. It stops
at finished games (the three returns above), and each call fills one more cell, so it always gets there.cells[index] = '' undoes the move (backtracking), so the board is left as it was.Math.max(...scores) is the largest score, Math.min the smallest.In score, under if (end === 'draw') return 0, write the new lines, above the function's closing }.
Skills: Functions, Loops
← Score a finished game A computer that never loses →