Workshop › Chess › Step 43 of 48
computerMove does what search does at the top level, but remembers which move gave the best score. DEPTH = 3:
its move, your answer, its answer. A random fraction below 1 breaks ties, so the computer does not always play the
same game.
```js
const DEPTH = 3 // how many moves ahead the computer looks
function computerMove() {
let best = null
let bestScore = -Infinity
for (const m of legalMoves()) {
const undo = makeMove(m)
const score = -search(DEPTH - 1) + Math.random() // a tiny random tie-break
undoMove(undo)
if (score > bestScore) {
best = m
bestScore = score
}
}
return best
}
```search's loop, but it keeps the move with the best score in best.DEPTH - 1: one move is played here, the rest is looked at by search.Math.random() is below 1, too small to change which move is really better (a pawn is 100).VALUES write DEPTH.const same = ... write computerMove, with an empty line after it.Skills: Functions
← Thinking ahead Alpha-beta: skip what cannot matter →