Workshop › Chess › Step 44 of 48

Alpha-beta: skip what cannot matter

What we are doing

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
```

What it means

Your turn

Change search as shown (its comment, its header, the loop and the last line), and pass -Infinity, Infinity in computerMove.

Skills: Functions

All steps

  1. A dark table
  2. One row of squares
  3. All 64 squares
  4. The starting position as text
  5. Color and kind
  6. Draw the pieces
  7. An outline for white
  8. Draw again and again
  9. The knight's jumps as data
  10. A list of moves
  11. The king steps too
  12. Which square was clicked?
  13. Light up the selected square
  14. Whose turn is it?
  15. Where can it go?
  16. Show the targets
  17. Play a move
  18. Click a dot to move
  19. Say whose turn it is
  20. The rook slides
  21. Bishops and queens
  22. Pawns step forward
  23. Pawns capture diagonally
  24. A pawn becomes a queen
  25. Is a square attacked?
  26. Attacks from far away
  27. Is the king in check?
  28. A move that remembers
  29. Take a move back
  30. Only legal moves
  31. Castling moves
  32. The rook jumps over
  33. Losing the right to castle
  34. No castling through check
  35. Remember the double step
  36. En passant
  37. Checkmate and stalemate
  38. Check! and the result
  39. Click to play again
  40. Show the last move
  41. A score for a position
  42. Thinking ahead
  43. Pick the best move
  44. Alpha-beta: skip what cannot matter
  45. Try the best-looking moves first
  46. The computer plays black
  47. You are white
  48. Build it yourself: the fifty-move rule