Search code examples
javascriptsliding-tile-puzzle

JavaScript slider puzzle


Ultimately I'm making a slider puzzle with a table, but at the moment I am generating a new puzzle and shuffling the tiles, but it appears that something in my code is making this work incorrectly. (not all the table cells are populated, etc.) Any idea what could be causing this?

In the program I am writing, I am using body onload to build the puzzle but for some reason that won't work in the Fiddle:

</head>
<body onload="newPuzzle(_r, _c)">
</body>

Fiddle Example


Solution

  • Try changing

    //declare and populate array
     var _array = new Array();
    
     for (var i = 0; i <= r*c; i++)
     {
       _array[i] = i;
     }
    

    to

    //declare and populate array
     var _array = new Array();
    
     for (var i = 1; i < r*c; i++)
     {
       _array[i] = i;
     }
       _array[0] = "";
    

    AND changing this:

    var rand = Math.floor(Math.random() * _array.length) + i;
    

    to this:

    var rand = Math.floor(Math.random() * _array.length);
    

    Just a note, as you're shuffling with a new array, there is not point in the first configuration (0 to 8), that way you can remove two FORs and just set a fixed value when generating it (before shuffle). Like so:

    gridTable[0].rows[i].cells[j].innerHTML = "0";