Page 1 of 1

Shift-the-images game

Posted: Thu Apr 07, 2005 1:05 pm
by Skara
You know those games where you move the blocks around to try and put them in the right order to get the correct image? That's what I'm trying to do.
I want to have it start out with a random configuration each time, though. Unfortunetly, I'm having trouble... Not only does the following take forever to load, it doesn't do anything. ^^;

Code: Select all

function imagelist() {
  $absent = rand(0,8);
  $images = array();
  for ($i=0; $i<9; $i++) {
    if ($i == $absent) {
      $images[] = '<!-- blank -->';
    } else {
      $right = 0;
      while (!$right) {
        $val = rand(0,8);
        $foo = 0;
        foreach ($images as $img) {
          if ($val != $img) { $foo++; }
        }
        if ($foo == count($images)-1) {
          $right = 1;
          $images[] = "<img src='eit_{$val}.jpg' alt='' />";
        }
      }
    }
  }
  return $images;
}
$default = imagelist();
print("<table cellspacing='0' cellpadding='0'>
       <tr><td>{$default[0]}</td><td>{$default[1]}</td><td>{$default[2]}</td></tr>
       <tr><td>{$default[3]}</td><td>{$default[4]}</td><td>{$default[5]}</td></tr>
       <tr><td>{$default[6]}</td><td>{$default[7]}</td><td>{$default[8]}</td></tr></table>");

Posted: Thu Apr 07, 2005 2:18 pm
by onion2k
I gave up trying to figure out your code. All I can say is that you're trying way too hard with foreach loops and stuff.

All you need to do is create an array of the images and swap the values a few times in the same way that the user will be able to. So you start of with an array from 0 through 8, then swap positions 1 and 2, 3 and 6, 2 and 3, and so on. Obviously you'll need to write the code to do the swaps randomly, but it's not too hard. Don't try to put the images in completely randomly .. you'll end up making some impossible puzzles if you do.

Posted: Thu Apr 07, 2005 2:35 pm
by Skara
Your post was helpful in that it made me think about a function to move array bits around rather than use temp vars to switch them. Instead, I found I can simply do this!!

Code: Select all

$images = range(0,8);
shuffle($images);
XD