Search code examples
phpooppuzzle

Memory Puzzle - Generating unique positions


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.


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.