Workshop › Chess › Step 44 of 48
Three moves deep is about 30 × 30 × 30 positions. Alpha-beta skips most of them. alpha is the score we are
already sure of, beta the most the opponent will allow. As soon as a move scores beta or more, the opponent would
never let us reach this position, so the rest of our moves here need not be looked at.
```js
// Negamax with alpha-beta: the best score the side to move can force, looking `depth` moves ahead.
function search(depth, alpha, beta) {
const moves = legalMoves()
if (moves.length === 0) return inCheck(turn) ? -100000 - depth : 0
if (depth === 0) return evaluate() * (turn === 'w' ? 1 : -1)
for (const m of moves) {
const undo = makeMove(m)
const score = -search(depth - 1, -beta, -alpha)
undoMove(undo)
if (score >= beta) return beta
if (score > alpha) alpha = score
}
return alpha
}
const score = -search(DEPTH - 1, -Infinity, Infinity) + Math.random() // a tiny random tie-break
```alpha replaces best: it starts at what the caller already guarantees and grows with each better move.-beta, -alpha, just like the score flips with -.score >= beta returns at once (a cut). The result is the same move choice with far fewer positions.computerMove starts with the widest window: -Infinity, Infinity.Change search as shown (its comment, its header, the loop and the last line), and pass -Infinity, Infinity in
computerMove.
Skills: Functions
← Pick the best move Try the best-looking moves first →