← All games

Sliding Puzzle

My sliding puzzle, originally written in Python with Tkinter. For this page I ported the same game logic to TypeScript and the Canvas API: the picture is cut into tiles, shuffled, and checked so that every shuffle can actually be solved.

Pick a picture and a size, then press Start. Click or tap a tile next to the empty square to slide it, or use the arrow keys. The timer starts when you press Start.

Moves
0
Time
00:00
Best
–

Size

Picture

Why not every shuffle can be solved

If you shuffle the tiles at random, exactly half of the boards can never be solved, however long you try. I did not know this when I wrote the first version. After reading about it, I wrote a check myself instead of hard-coding a few safe starting boards: shuffle, check, and shuffle again until the board can be solved.

The check counts inversions. Read the tiles row by row, skip the empty square, and count every pair where a larger number comes before a smaller one. The solved board has 0 inversions.

Sliding a tile sideways does not change this order at all. Sliding it up or down moves it past the tiles in between, and on a 3×3 or 5×5 board that is always an even number of tiles. So the count can go up or down, but whether it is even or odd never changes. A board with an odd number of inversions can never get back to 0.

On boards with an even width, like 4×4, a vertical move does switch the count between even and odd, but it also moves the empty square one row. Taken together, the row of the empty square and the number of inversions still follow a fixed rule, and that is the rule the game checks before every start.