DEV Community

Devanshu Biswas
Devanshu Biswas

Posted on

I Built the 15-Puzzle — and Why Half of All Shuffles Are Impossible

The 15-puzzle is a 150-year-old toy with a famous math twist: shuffle it wrong and it's literally impossible to solve. Here's a playable version that never deals an unsolvable board.

🔢 Play it: https://dev48v.infy.uk/game/day19-15-puzzle.html

The board

A 4×4 grid: tiles 1–15 plus one blank. A legal move slides a tile that's adjacent to the blank into the gap (it's really just swapping a tile with the blank). Arrow keys move the neighbouring tile into the blank.

The solvability trap

Here's the gotcha: exactly half of all 16! arrangements are unsolvable. If you scramble by randomly placing tiles, half your boards can never reach 1–15. The clean fix in this build: start from the solved state and make hundreds of random legal moves — any position reachable by legal moves is, by definition, solvable.

(The deeper reason is the inversion-parity theorem: for a 4-wide board, solvability depends on the inversion count plus the blank's row from the bottom — covered on the UNDERSTAND tab.)

The rest

Win when tiles read 1–15 with the gap bottom-right; track moves + time; smooth CSS slide.

🔨 Full build (grid → swap-with-blank → solvable shuffle → win check) on the page: https://dev48v.infy.uk/game/day19-15-puzzle.html

Part of GameFromZero. 🌐 https://dev48v.infy.uk

Top comments (0)