This site requires JavaScript, please enable it in your browser!
Greenfoot back
GeneralBrae
GeneralBrae wrote ...

2011/11/22

Problems generating a game board

GeneralBrae GeneralBrae

2011/11/22

#
Hi again. I am trying to create a version of teh game Mahjong. I have uploaded a basic version of my current project which only goes as far as creating a set pattern of randomly chosen tiles. However, there are gaps in the pattern and I can't see where I went wrong in the code that causes this. The gaps seem to be randomly distributed and the basic shape of the pattern I am trying to get is there, but the overall cover isn't. Any help would be appreciated. As I mentioned the project can be found on my profile. Many Thanks
nccb nccb

2011/11/23

#
The problem is that you pick a random piece to add at each location, but there's nothing stopping you picking the same piece twice. Adding it twice results in moving it around, so you get a gap at the old location. You could keep track of which pieces you have already added and pick a new random number if it's already been added, but this method is very inefficient (you spend a lot of time re-picking numbers, and in fact you can take forever). Another way to do it is to randomly shuffle all the valid 144 piece numbers and use the first 87 as pieces. This prevents duplicates appearing. As a warning, do not try to write your own shuffle code, it's notoriously easy to do it wrong. Here's some code that will do it. First, at the top of your Background class, write:
import java.util.*;
Then adjust CreatePattern to be:
private void CreatePattern()
    {
        CreateClasses();
        
        ArrayList<Integer> pieces = new ArrayList<Integer>();
        for (int j = 0; j < 144; j++)
        {
            pieces.add(j);
        }
        
        Collections.shuffle(pieces);
                                          
        for (int i = 0; i < 87; i++)
        {
            addObject (createClasses[pieces.get(i)], xcoords[i], ycoords[i]);    
        }
    }
I'm using an ArrayList rather than an array because oddly, Java has a supplied method for shuffling collections, but not for shuffling arrays.
GeneralBrae GeneralBrae

2011/12/31

#
Sorry for the long delay in replying. That's brilliant thanks and solves the problem for the scenario I uploaded. Would this still hold true if I were to add more layers which would use up all of the 144 pieces? Naturally I'd have to increase the loop limit etc, but will the general logic work? Thanks a million
You need to login to post a reply.