Workshop › Tic-tac-toe › Step 28 of 33
Before anything else, the computer should win if it can. It tries O in every free cell on a copy of the board
and asks winningLine whether that completes a line.
```js
// A free cell that would complete a line for `mark`, if there is one.
const completes = (mark) =>
free.find((index) => {
const copy = [...cells]
copy[index] = mark
return winningLine(copy)
})
const random = free[Math.floor(Math.random() * free.length)]
return completes('O') ?? (cells[4] === '' ? 4 : random)
```completes(mark) returns the first free cell that would complete a line for mark, or undefined.[...cells] makes a copy, so the real board is untouched.a ?? b means "use a, unless it is null or undefined, then use b". So: win if possible, otherwise the old
rule.In computerMove, above the random line, write the comment and completes. Then change the return line as
shown.
Skills: Functions, Arrays and objects
← Rule one: take the center Rule three: block the opponent →