How to create randomly assigned array?

Hi everyone,
I’m still very new to processing, and I want to be able to create an array (or class?) of 7 different floor types I have made out of rectangles. Below is the code for these different floor types, in the state I have currently got them. I want to have a section of code that can generate one of the floor types, randomly chosen, at a set interval indefinitely. Any pointers towards how to achieve this would be very much appreciated!

int yPos1 = 0;
int yPos2 = 125;
int yPos3 = 250;
int yPos4 = 375;
int yPos5 = 500;
int yPos6 = 625;
int yPos7 = 750;
float speed = 2.5, direction = 1;

void setup() {
  size (800, 800);
  frameRate(60);
}

void draw()
{

  clear(); 
  background (129, 209, 245);
  fill (245, 181, 62);
  rect(0, yPos1, 300, 20);
  rect (450, yPos1, 800, 20);
  yPos1 += speed * direction;

  fill (245, 181, 62);
  rect(150, yPos2, 450, 20);
  yPos2 += speed * direction;

  fill (245, 181, 62);
  rect(300, yPos3, 400, 20);
  rect(0, yPos3, 150, 20);
  yPos3 += speed * direction;

  fill (245, 181, 62);
  rect(200, yPos4, 600, 20);
  yPos4 += speed * direction;

  fill (245, 181, 62);
  rect(0, yPos5, 500, 20);
  rect(650, yPos5, 150, 20);
  yPos5 += speed * direction;

  fill (245, 181, 62);
  rect(0, yPos6, 200, 20);
  rect (325, yPos6, 125, 20);
  rect (600, yPos6, 200, 20);
  yPos6 += speed * direction;

  fill (245, 181, 62);
  rect(0, yPos7, 600, 20);
  yPos7 += speed * direction;
}
1 Like

Hi there,

First of all, you can format your code by pressing Ctrl+T in the Processing IDE code editor and use the </> button when you edit a message on the forum.

Then there’s few things to change before trying to solve your problem. You are repeating yourself too much :

  • You can set the fill color once (because it’s going to stay the same)
  • Since you have the same objects (your floors) but with different properties, it’s useful to create a specific class so your code is modular (https://processing.org/tutorials/objects/)

For example, the structure could be :

class Floor{
    int posX, posY, sizeX, sizeY;
    Floor(int posX, int posY, int sizeX, int sizeY){/*...*/}
    void display(){/*...*/}
    void update(){/*...*/}
}
2 Likes

Awesome, thanks for the help!

Many ways to approach this. some points should care about

  • you can use ArrayList of the floor class based on josephh post to keep track the floor objects like what @josephh has posted. see https://processing.org/reference/ArrayList.html
  • on the certain condition, like the floor get to the bottom of the screen, remove that floor and generate a new floor and push to the ArrayList or you can just reset that floor to the initial condition with random properties (position and size or something) without being removed
  • see https://processing.org/reference/random_.html to randomize thing
1 Like