Workshop › Chess › Step 25 of 48
The rule that makes chess chess: you may never leave your own king in check. First we need to know whether a square is attacked. Instead of listing all enemy moves, look outwards from the square: a pawn diagonally in front of it? A knight a jump away? A king next to it?
```js
// Is the square (r, c) attacked by a piece of color `by`? Look outwards from the square for each kind of attacker.
function attacked(r, c, by) {
const pawnRow = r + (by === 'w' ? 1 : -1) // a white pawn attacks upwards, so it stands one row below
for (const dc of [-1, 1]) {
if (inside(pawnRow, c + dc) && board[pawnRow][c + dc] === by + 'P') return true
}
for (const [list, kind] of [[KNIGHT, 'N'], [KING, 'K']]) {
for (const [dr, dc] of list) {
if (inside(r + dr, c + dc) && board[r + dr][c + dc] === by + kind) return true
}
}
return false
}
```r + 1); a black one
above.[[KNIGHT, 'N'], [KING, 'K']] pairs each jump list with the piece that uses it; one loop checks both.by + kind builds the piece to look for, like 'bN'. The first attacker found returns true at once.Above function play(m) {, write the comment and attacked, with an empty line after it.
Skills: Functions, Game states
← A pawn becomes a queen Attacks from far away →