Workshop › Connect Four › Step 30 of 38
computerMove() picks a column. The first two rules: if the computer can win with a move, play it; if the player could
win next move, block that column. For now, otherwise it takes the first open column.
```js
function computerMove() {
const open = [...Array(COLS).keys()].filter((col) => dropRow(col) !== -1)
// 1. Win if we can. 2. Block the player's win.
for (const who of [2, 1]) {
const col = open.find((c) => winsWith(c, who))
if (col !== undefined) return col
}
return open[0]
}
```[...Array(COLS).keys()] is [0, 1, 2, 3, 4, 5, 6]; filter keeps the columns that are not full.find gives the first column where that player would win.find returns undefined when nothing matches; column 0 is a real answer, so we check !== undefined.Above function colAt( write computerMove, followed by an empty line.
Skills: Game states, Arrays and objects
← Try a move and take it back Don't help the player →