Workshop › Chess › Step 42 of 48
To choose a move, look ahead: try every move, every answer to it, and so on, assuming both sides play their best. In negamax, a score is always from the side to move, and what is good for me is bad for you: the score of a move is minus the best score the opponent can get after it. The function calls itself with one move less to go.
```js
// Negamax: the best score the side to move can force, looking `depth` moves ahead.
function search(depth) {
const moves = legalMoves()
if (moves.length === 0) return inCheck(turn) ? -100000 - depth : 0
if (depth === 0) return evaluate() * (turn === 'w' ? 1 : -1)
let best = -Infinity
for (const m of moves) {
const undo = makeMove(m)
const score = -search(depth - 1)
undoMove(undo)
if (score > best) best = score
}
return best
}
```- depth), stalemate is 0.evaluate() is turned to the mover's side: times -1 when black is to move.-Infinity is smaller than every number, so the first score always replaces it.-search(depth - 1) is the recursion: the opponent's best, seen from our side.Above const same = ... write the comment and search, with an empty line after it.
Skills: Functions
← A score for a position Pick the best move →