Displaying randomised coloured squares

Hello, I’m trying to display randomised coloured squares but the issue is, when I use my code outside of a void draw() function, it works fine, but when I put it in a void draw() function, the colours of the squares continues to change infinitely. I’m an absolute beginner and this is a component for a project I’m doing. Any help would be appreciated :slight_smile:

Here is my code:

void setup(){
size(500, 500);
}

void draw(){
background(100);
rectMode(CORNER);
fill(0, 255, 0);
noStroke();

for (int y = 0; y < 500; y = y + 25) {
for (int x = 0; x < 200; x = x + 25){
float r = random(62, 225);
fill(0, random(62, 225), 0);
rect(y, x, 25, 25);
}
}

in theory you need to store the colors in an array and fill this once in setup() and use it in draw()

Hi,

Welcome to the forum! :wink:

Remember that you can format your code by using the </> button when editing your message on the forum or use backticks : ``` your code ``` → your code

By definition, randomness has the property so that :

A random sequence of events, symbols or steps often has no order and does not follow an intelligible pattern or combination.

But because the draw() function executes multiple times per second (roughly 60), then the random() function should return a different (unpredictable to be exact because it can be the same) value each time! :slight_smile:

If you want to save the random colors once, you need to store them into variables, as described by @chrisir

1 Like

Another way than I have described is to

  • get rid of background() [Edited: I was wrong here. That won’t help you] or
  • use noLoop()
    but since it is part of a bigger project I assume this won’t help you. (for different reasons)

// just use noLoop() here, program stops, colors stay the same
// (but won't help you, when you want to do other things with your Sketch)


void setup() {
  size(500, 500);
}

void draw() {
  background(100);
  rectMode(CORNER);
  fill(0, 255, 0);
  noStroke();

  for (int y = 0; y < 500; y = y + 25) {
    for (int x = 0; x < 200; x = x + 25) {
      float r = random(62, 225);
      fill(0, random(62, 225), 0);
      rect(y, x, 25, 25);
    }
  }

  noLoop();
}