Workshop › Chess › Step 41 of 48
Now the computer will play black. First it needs to judge a position with a number: count material (pawn 100, knight 320, bishop 330, rook 500, queen 900) and add a little for pieces near the middle, where they control more squares. White's pieces count plus, black's minus.
```js
const VALUES = { P: 100, N: 320, B: 330, R: 500, Q: 900, K: 0 }
// Material, plus a little for pieces near the middle, from white's side: positive is good for white.
function evaluate() {
let score = 0
for (let r = 0; r < 8; r++) {
for (let c = 0; c < 8; c++) {
const piece = board[r][c]
if (!piece) continue
const center = piece[1] === 'K' ? 0 : 6 - Math.abs(3.5 - r) - Math.abs(3.5 - c)
score += (VALUES[piece[1]] + center * 4) * (piece[0] === 'w' ? 1 : -1)
}
}
return score
}
```Math.abs is the distance from zero: Math.abs(-2) is 2. |3.5 - r| + |3.5 - c| is how far the square is from the
center (1 for the four middle squares, 7 for a corner), so center goes from 5 down to -1.center * 4, times 1 for white or -1 for black.DIAGONAL write VALUES.const same = ... write the comment and evaluate, with an empty line after it.Skills: Functions, Game states
← Show the last move Thinking ahead →