Question

I have a 3x4 table of images that I want to be scrambled like a puzzle. There are a total of 12 separate gifs. Where I need help is, Using strictly javascript, how could I set this up so it randomly scrambles the images every time the page loads? So far, I have loaded all the images into an array like so:

Incomplete JS:

var imgArray = new Array();

imgArray[0] = new Image();
imgArray[0].src = 'pic_01.gif';

imgArray[1] = new Image();
imgArray[1].src = 'pic_02.gif';

imgArray[2] = new Image();
imgArray[2].src = 'pic_03.gif';

imgArray[3] = new Image();
imgArray[3].src = 'pic_04.gif';

etc... pic_05.gif...

My HTML:

<table>
<tr>
    <th> <img src="pic_01.gif" onclick="imageSwap()" alt="" border= height=100           width=100></img> </th>
    <td> <img src="pic_02.gif" alt="" border= height=100 width=100></img></td>
    <td> <img src="pic_03.gif" alt="" border= height=100 width=100></img></td>
</tr>
<tr>
    <td> <img src="pic_04.gif" alt="" border= height=100 width=100></img></td>
    <td> <img src="pic_05.gif" alt="" border= height=100 width=100></img></td>
    <td> <img src="pic_06.gif" alt="" border= height=100 width=100></img></td>
</tr>
<tr>
    <td> <img src="pic_07.gif" alt="" border= height=100 width=100></img></td>
    <td> <img src="pic_08.gif" alt="" border= height=100 width=100></img></td>
    <td> <img src="pic_09.gif" alt="" border= height=100 width=100></img></td>
</tr>
<tr>
    <td> <img src="pic_10.gif" alt="" border= height=100 width=100></img></td>
    <td> <img src="pic_11.gif" alt="" border= height=100 width=100></img></td>
    <td> <img src="pic_12.gif" alt="" border= height=100 width=100></img></td>
</tr>
</table>

What I would ultimately like to do is be able to have a user click one 'randomized' image and swap it with another 'randomized' image, to solve the puzzle. Any input is appreciated! Thanks!

Was it helpful?

Solution

I think your best bet would be to add a class (let's say random) to each img element:

<img src="pic_10.gif" class="random" alt="" height=100 width=100 />

Then we can get all the images with a simple querySelectorAll:

var images = document.querySelectorAll('.random');

Randomize the array of srcs:

var srcs = ['pic_01.gif', 'pic_01.gif', etc, etc];
srcs = srcs.sort(function() { return Math.random() > 0.5; });

Then iterate over the images, applying the new src to each:

for (var i = 0; i < images.length; ++i) {
  images[i].src = srcs[i];
}

The full function being:

var imageSwap = function() {
  var images = document.querySelectorAll('.random');

  var srcs = ['pic_01.gif', 'pic_01.gif', etc, etc];
  srcs = srcs.sort(function() { return Math.random() > 0.5; });


  for (var i = 0; i < images.length; ++i) {
    images[i].src = srcs[i];
  }
};

Example JSFiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top