How do I make a loop that only runs once?

For a project, I want to change the background for the starting screen every time it is loaded up. So the user opens the program and the background is displayed, they play for a bit, press a key to reset and go back to the start screen – I now want to display a different random background image. At the moment, I can randomly select an image once if I do it in setup (below) or have them basically run all at once if I put it in draw (epilepsy warning). I want whatever code that solves this to run once when startScreen is initiated selecting a random background image each time. I tried noLoop() which solved the epilepsy problem but stopped the rest of the program from working. Thank you for any help or insight you can provide!

int random_ssc;
//setup
for (int i = 0; i < backgrounds.length; i++) {
    backgrounds[i] = loadImage("legostartscreen"+i+".png");
  }
    random_ssc = int(random(4));
//void startScreen() which is one of my cases in the draw
 background(backgrounds[random_ssc]);
1 Like

use an external variable.


boolean bool = false;
void loop(){
if(!bool){
 for (int i=0;i<someNum;i++){
  doSomething();
}}
bool = true;
}

alternatively you could use an incremental counter;

2 Likes

Why are you needing a loop to set the background to a random image?

From the looks of it, you only need the loop to load your array of images, so all you need to do is update your variable used to get a random index from the images array when your start screen is called.

boolean isShowingStartScreen = false, showStartScreen = false;
color[] cols = {#22223B, #4A4E69, #9A8C98, #C9ADA7, #F2E9E4};

int colsIdx = 0;

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

void draw() {
  background(3, 7, 11);

  if (showStartScreen) startScreen();
}

void startScreen() {
  if (isShowingStartScreen && showStartScreen) colsIdx = int(random(cols.length)); 

  isShowingStartScreen = false;

  pushStyle();
  rectMode(CENTER);
  fill(cols[colsIdx]);
  rect(width*0.5, height*0.5, 100, 100);
  popStyle();
}

void mousePressed() {
  showStartScreen = !showStartScreen;
  isShowingStartScreen = true;
}

Thank you this was really helpful!

2 Likes