Workshop › Chess › Step 28 of 48
To know whether a move leaves the king in check, we will try it and then take it back. So the board part of
play becomes makeMove, which also returns an undo object: the move, the piece that moved and whatever was
captured. play calls it and then clears the selection.
```js
// Play a move on the board, and return what is needed to take it back.
function makeMove(m) {
const [fr, fc] = m.from
const [tr, tc] = m.to
const piece = board[fr][fc]
const undo = { m, piece, captured: board[tr][tc] }
board[tr][tc] = m.promo ? piece[0] + m.promo : piece
board[fr][fc] = ''
turn = other(turn)
return undo
}
function play(m) {
makeMove(m)
selected = null
targets = []
}
```{ m, piece, captured: board[tr][tc] } is short for { m: m, piece: piece, captured: ... }; it is saved before
the board changes.makeMove touches only the board and the turn, never the selection, so it is safe to call while "thinking".Rename play to makeMove (with the comment), add the undo and return lines, move the two selection lines into a
new play below it.
Skills: Functions, Refactoring
← Is the king in check? Take a move back →