Question

I'm making one of those games where you have to pick two blocks and if they are the same, they stay open. If you pick different blocks they close and you have to pick another two blocks.

This is my code so far:

public $pictures = ['apple.png', 'cake.png', 'coconut.png', 'guava.png', 
                'guawa.png', 'kiwi.png', 'limewire.png', 'pear.png'];

private function makeGame()
{
    foreach($this->pictures as $picture)
    {
        for($i = 0; $i < 2; $i++)
        {
            $this->mapBoard[] = array('value' => $picture, 'x' => $this->randomPos('x'), 'y' => $this->randomPos('y'));
        }
    }
}

private function randomPos($arg)
{
    $random = mt_rand(1,4);
    if(!empty($this->mapBoard))
    {
        foreach($this->mapBoard as $image)
        {
            if($image[$arg] == $random)
                $this->randomPos($arg);
            else
                return $random;
        }
    }
    else
    {
        return $random;
    }
}

But values for 'x' and 'y' sometimes repeat. Can you tell me where I do something wrong, or another way to generate unique x & y.

Was it helpful?

Solution

One possible solution is to invert the problem. Make a list of positions (i.e. [1.1, 1.2, 1.3, 1.4, 2.1, ...]) and then shuffle this array. Now for the first picture take the first two entries in this shuffled list, for the second picture the next two, and so on.

OTHER TIPS

With mt_rand() having two arguments passed which only have a difference of 3, it is inevitable that you will get repeating patterns, since all the combinations will be used up.

Best thing to do, is loop all map blocks and assign a picture to it.

On each block select a random picture from array, and when it has been used remove it from the array.

Something like this:

$this->images = {"1.jpg","1.jpg","2.jpg","2.jpg","3.jpg","...etc etc."}; //16 images (8 unique)
$this->mapboard = array(); // Gonna be a 2 dimensional

// We are making a 4x 4 map

for($x=0,$x<4;$x++){
    for($y=0,$y<4;$y++){
        shuffle($numbers); /// we randomize array elements by shuffling it (like a deck of cards)
        $this->mapboard[$x][$y] = array_pop($this->images); //we take the last card out of the deck and put it on the map (x,y)
    }
}
//all cards are on board, and all blocks are used.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top