We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello,
I have to make a memory game and as I am new to programming, I am stuck. I have a code which loads the images and add them random on a board, but he uses all the images and none of them is the same. If I change the numbers of cards, I will get 3 of the same cards. How do I always gets couples?
int vlakGrootte=100;
int posX= 10;
int marge = 15;
int kaartBreedte = 100;
PImage []kaart = new PImage[32];
int kolom = 8;
int rij = 3;
void setup () {
//size (600, 600);
fullScreen();
for (int i = 0; i <kaart.length; i++) {
for (int j = 0; j<=rij; j++) {
// rect(width/3 + (vlakGrootte +marge)*i, (vlakGrootte+ marge) * j, vlakGrootte, vlakGrootte);
kaart[i] = loadImage("kaart" + i + ".png");
}
}
for (int i = 0; i< kolom; i++) {
for ( int j = 0; j< rij; j++) {
image(kaart[(int) random(32)],width/3 + (vlakGrootte +marge)*i, (vlakGrootte+ marge) * j+50, vlakGrootte, vlakGrootte);
}
}
}
void draw() {
}
Answers
Don't pick them at random, start with a set that contains the cards you want and then shuffle them.
So I have to copy them in a new array and then shuffle?
well, you already have an array of PImages, you could shuffle that. or add a new array of indexes (32 ints, 16 pairs) and shuffle that.
actually, do you have 32 cards or 64? and how many separate images?
thx, can I do this without import the java thing?
https://Processing.org/reference/IntList.html
https://Processing.org/reference/IntList_shuffle_.html
can I use the IntList in an existing array? Like in this one? (part of the code)
something like this. use the nth element of the shuffled intlist to get the index of the image to print at this location
Tjess, if you wanna stick w/ Java's regular arrays[], you can use the custom shuffle() utility function from this old forum post: B-)
https://Forum.Processing.org/two/discussion/20529/retrieving-elements-from-a-list-randomly#Item_5
Simply replace all of datatype
char
used there w/ the 1 you need; for example theint
datatype. ;)