Shift-the-images game

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Shift-the-images game

Post 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>");
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post 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.
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post 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
Post Reply