We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi coders!
i want to shuffle the order of PImage-objects in an array. Here's the code:
PImage[] theImages = new PImage[7];
void setup() {
for (int i = 0; i < theImages.length; i++) {
theImages[i] = loadImage(i+".gif");
}
}
void draw() {
// Display The Images
for (int i = 0; i < theImages.length; i++) {
pushMatrix();
translate(width/2, height/2);
scale(random(0.5, 1));
image(theImages[i], 0, 0);
popMatrix();
}
// Shuffle the order of the images
shuffle();
}
I found this in the forum: https://forum.processing.org/two/discussion/3546/how-to-randomize-order-of-array but i did not get it to work.
Would you help me? Thanks alot!
Answers
edit post. remove all the `s, highlight code, press ctrl-o
Make an ArrayList instead of PImage[], and then use Java Collections.shuffle
or Collections.shuffle(Arrays.asList(array)) with PImage[] (haven't tested this)
http://stackoverflow.com/questions/1519736/random-shuffling-of-an-array
https://forum.processing.org/two/discussion/3546/how-to-randomize-order-of-array
or create a simple IntList as an index (if your PImage list is fixed in size) and then shuffle that with the Processing built-in IntList shuffle.
https://processing.org/reference/IntList_shuffle_.html
Question -- are your images transparent or offset? If so, it might make sense to draw all seven of them at once in a (shuffled) stack, every single time draw is called the way that you are doing.
EDIT: removed
import java.util.Collections.*
-- not necessary if using Processing's built-inIntList.shuffle
Otherwise it doesn't make sense -- what you want is to draw one new random image (0-6) each time draw is called -- like dealing cards from a deck -- and then after seven images you want to reshuffle and start again.
If that is the case, and you want to go through the 'deck' of seven each time, you still might need fancy shuffling. Here draw only runs shuffle every seventh frame (frameCount%7==0) -- so you shuffle, draw seven times, then shuffle again....
But if you don't care about getting two in a row that are the same, you could just call random() -- no shuffling required:
Hi koogs, hi jeremy, thanks for your feedback!
@Jeremy: Yes, the images are transparent and shall appear as a stack. That's why your I fixed the problem with your first solution:
It works fine. Thank you guys!
Two small self-corrections -- for your purposes you don't need
import java.util.Collections.*
and you don't need theif(frameCount % 7 == 0)
wrapped around imageIndex.shuffle(). I've updated my first solution.