Workshop › Tic-tac-toe › Step 32 of 33
computerMove no longer needs rules. For every free cell it places O, asks score how that ends with perfect play,
undoes it, and keeps the best cell.
```js
function computerMove(cells) {
let best = -1
let bestScore = -Infinity
for (let index = 0; index < 9; index++) {
if (cells[index] !== '') continue
cells[index] = 'O'
const value = score(cells, 'X')
cells[index] = ''
if (value > bestScore) {
bestScore = value
best = index
}
}
return best
}
```best is the best cell so far, bestScore its score. -Infinity is smaller than any number, so the first cell
tried always becomes the best so far.value > bestScore keeps the cell only if it is better than every one before.Delete the whole old computerMove (from its first line to its closing }) and write the new one in its place.
The click listener stays the same.
Skills: Functions
← Look ahead: minimax Build it yourself: keep score →