Workshop › Chess › Step 30 of 48
Now the rule itself: a move is legal only if the mover's king is not in check after it. legalMoves tries each
pattern move, looks at the king, takes it back, and keeps the safe ones. The board then shows only legal moves.
```js
// The moves the side to play can really make: try each one, and keep it if its own king is not left in check.
function legalMoves() {
const color = turn
return pseudoMoves(color).filter((m) => {
const undo = makeMove(m)
const safe = !inCheck(color)
undoMove(undo)
return safe
})
}
targets = legalMoves().filter((m) => same(m.from, selected))
```color is saved first: makeMove switches turn, but we must check the mover's king.filter function plays, checks and undoes each move; return safe keeps it or drops it.clickSquare now asks legalMoves() instead of pseudoMoves(turn).function play(m) { write the comment and legalMoves.clickSquare, replace pseudoMoves(turn) with legalMoves().Skills: Game states, Functions
← Take a move back Castling moves →