Repository navigation
Closed
Labels
Description
Summary
The undo snapshot in makeMove is taken after the board and the en passant target have already been changed, so Undo does not return to the position before the move.
Where
js/game.js:163-164(en passant target reset)js/game.js:173-197(en passant capture and castling rook move)js/game.js:200-209(snapshot taken here)js/game.js:281-290(undoLastMove)js/game.js:386-394(explicit en passant branch)
Details
let previousEnPassantTarget = enPassantTarget;
enPassantTarget = null; // 164: already changed
...
boardState[capturedPawnRow][capturedPawnCol] = null; // 180: e.p. pawn removed
...
boardState[startRow][rookEndCol] = rook; // 192: rook moved
...
const preMoveSnapshot = { // 200: taken too late
boardState: deepClone(boardState),
...
enPassantTarget: enPassantTarget ? { ...enPassantTarget } : null
};Impact
Undo silently produces illegal positions in ordinary play, and the corrupted state is saved to localStorage:
- Castling, then Undo: the king returns but the rook stays on f1/d1 with
hasMovedset, so castling is lost. - En passant, then Undo: the capturing pawn returns but the captured pawn stays deleted.
- Double push, then Undo: the en passant target stays set for the side that just undid. After 1.e4 and Undo, the d2 pawn is offered e3; playing it is recorded as
dxe3 e.p.and removes White's own e2 pawn. - Any move, then Undo: an en passant right that existed before the move is lost.
Steps to reproduce
- New game, play 1.e4, press Undo.
- Select the d2 pawn: e3 is offered. Play it and the e2 pawn disappears.
Or: 1.e4 e5 2.Nf3 Nc6 3.Bc4 Bc5 4.O-O, press Undo: the rook is on f1 and h1 is empty.
Suggested fix
Build the snapshot at the top of makeMove, before any mutation, and store previousEnPassantTarget in it. Make the explicit en passant branch require an enemy pawn on the captured square.
Acceptance criteria
- Undo after castling, en passant, a double push, a promotion and a plain move restores board,
hasMovedflags, king positions and en passant target exactly - Tests cover each of those cases
Getting started
- Relevant files:
js/game.js,tests/unit/game-moves.test.js - How to run tests:
npm install, thennpm testandnpm run lint - Related docs:
docs/ARCHITECTURE.md,.github/CONTRIBUTING.md
Filed by repo-audit/full-audit at 8a2c86c. Severity: high. Effort: S. audit-key: bug|js/game.js|makeMove.preMoveSnapshot
Activity