Skip to content Skip to sidebar Skip to footer

Sliding Puzzle For Javascript

I want to create a sliding puzzle with different formats like: 3x3, 3x4, 4x3 and 4x4. When you run my code you can see on the right side a selection box where you can choose the 4

Solution 1:

In shiftPuzzlePieces(el) function, you should first check if el is adjacent to blank piece. If so, then shift it. Here is the jsFiddle

function shiftPuzzlepieces(el) {
var elIndex=0;
var child=el;
while((child=child.previousSibling)!=null) elIndex++;    
//position of el is stored in elIndex

var blankIndex=0;
var blank = document.getElementById("positionblank");
child=blank;
while((child=child.previousSibling)!=null) blankIndex++;
//position of blank is stored in blankIndex

//Now the number of columns is needed to compare between positions of el and blank. 
//I have stored this in global variable cols

//Now check if el and blank are adjacent
if((((elIndex==blankIndex-1) || (elIndex==blankIndex+1) )
   && ((Math.floor(elIndex/cols))==(Math.floor(blankIndex/cols)))
   ) || (elIndex==blankIndex+cols) || (elIndex==blankIndex-cols) ){
 var temp = el.parentNode.insertBefore(document.createElement('a'), el);
el.parentNode.insertBefore(el, blank);
el.parentNode.insertBefore(blank, temp);
el.parentNode.removeChild(temp);
}
}

Post a Comment for "Sliding Puzzle For Javascript"