Complete newbie to processing so any help is appreciated and apologies for my lack of language knowledge.
I am trying to make a grid of 9 images that, when keyPressed, randomises the order of the images. I have used an image array to load the images and have the images appearing where I want them to. However, I am getting duplicates when they randomise. I only understand how I could use an arrayList to solve this with a list of numbers. No idea how to do it for images and how to load images into an arrayList?
Here is a way with ArrayList and then shuffling the thing - see function shuffle().
I also use a nested for loop that calculates the positions of the images in the grid - see function draw_grid(). That is more flexible than what you had in draw().
(code snippets from the forum)
Welcome to the forum, it’s a great community!
Chrisir
// https://discourse.processing.org/t/how-to-load-images-using-an-arraylist/15263
ArrayList<PImage> img = new ArrayList();
void setup() {
//fullScreen();
size(1200, 900);
// load all
for (int i=0; i<9; i++) {
img.add ( loadImage("img"+i+".jpg") );
}
// shuffle
// img=shuffle( img );
background (0);
}
void draw() {
background (0);
draw_grid();
fill(255);
text("Hit Space Bar to shuffle",
13, height-20);
}
void draw_grid() {
int x0 = 50, y0 = x0, // dist from border
w = 310, h = w, // width and height of a cell / image
off = 0; // offset between images
int k=0;
// nested for loop makes for columns and rows
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
// we calculate the position on the fly
image(img.get(k),
x0+i*(w+off), y0+j*(h+off));
k++;
}
}
// shuffle in-place
ArrayList<PImage> shuffle (ArrayList<PImage> arrL1) {
for (int i=0; i<arrL1.size(); i++) {
int randomPosition = int(random(arrL1.size()));
// swap image at position i with image at position randomPosition
PImage temp = arrL1.get(i);
arrL1.set(i, arrL1.get(randomPosition));
arrL1.set(randomPosition, temp);
}
return arrL1;
}
void keyPressed() {
if (key == ' ') {
// shuffle
img=shuffle( img );
}
}
//
Hi, I can definitely see how it works! I’m new to coding so it might take a while to neaten it up haha. There isn’t anyway to bring the enlarged image to the foreground is there?