A DOM-Based Sliding Puzzle: Scrambling the Picture
A DOM-Based Sliding Puzzle (7)
Scrambling the Picture
The rule of the sliding puzzle is that you start with a scrambled picture and you try to put the pieces in their correct positions, in a minimum number of moves. Here is the scrambling function:
function randomizePicture() {
for(i = 0; i < 3000; i++) {
newBlank = Math.round(Math.random() * (size - 1));
if (!validClick(oldBlank, newBlank)) continue;
divNode.childNodes[oldBlank].swapNode(divNode.childNodes[newBlank]);
oldBlank = newBlank;
}
}
This function relies on the validClick()
function that we'll explain more in the next page. It accepts two parameters, oldBlank
and newBlank
, which are positions on the puzzle board. The validClick()
function checks whether it is a valid move to swap the oldBlank
position with the newBlank
position.
We scramble the puzzle board by simulating many moves by a player. We chose 3000 as a number that will assure a total randomization of the board. We always keep track of the blank square position, oldBlank
. Then, for each iteration we try a new position for the blank square:
newBlank = Math.round(Math.random() * (size - 1));
The new attempted position newBlank
is a number between 0
and 11
. We check then that swapping oldBlank
with newBlank
is valid:
if (!validClick(oldBlank, newBlank)) continue;
If it is not a valid switch, we immediately go to the next iteration with the continue
keyword. If the swapping is valid, we swap the child nodes of divNode
:
divNode.childNodes[oldBlank].swapNode(divNode.childNodes[newBlank]);
We explained swapping in Column 43. Notice that we swap whole nodes, with all their properties and children. For every successful swapping we need to update the current position of the blank square, oldBlank = newBlank
.
Produced by Yehuda Shiran and Tomer Shiran
Created: August 2, 1999
Revised: August 2, 1999
URL: https://www.webreference.com/js/column45/scramble.html