Search code examples
processing

How to pick a random string from an array on mouse press in Processing


I want to do the following in Processing:

  • Display text on the screen
  • When mouse is not pressed, always display the first string in the array
  • When mouse is pressed, choose a random string from the array and have this string persist until the mouse is pressed again

I tried moving "int index = int(random(0, 3));" two draw() but this picks a random string many times a second, and I want it to pick it once until I press the mouse again.

In draw(), the value of index is always zero. It only changes in mousePressed().

Here's my code:

String[] sentences = { // defines an array of three strings
  "Sentence one",
  "Sentence two",
  "Sentence three",
};

int index = 0; // initializes variable "index" to zero

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

void draw() {
  background(255);
  fill(0);
  text(sentences[index], 10, 100); // picks a random sentence from the array
}

void mousePressed() {
  if (mousePressed == true) { // when mouse pressed 
    int index = int(random(0, 3)); // picks a random value for index: either 0,1,2
  }
}

Solution

  • You're experiencing variable shadowing. This line:

    int index = int(random(0, 3)); // picks a random value for index: either 0,1,2
    

    declares index as a local variable, so within that scope only it shadows the global variable.

    you probably meant

    index = int(random(0, 3)); // picks a random value for index: either 0,1,2
    

    (you're defining and assigning index at the top of your code, but in mousePressed() you just want to assign a different variable to the previously defined variable)

    Off topic:

    • if (mousePressed == true) is the same as if (mousePressed), but in this context (within the mousePressed() function is redundant since it will always be true there
    • you're not handling the "when the mouse is not pressed" case: mouseReleased() can help with that.

    Here's a modified version of your code reflecting the above:

    String[] sentences = { // defines an array of three strings
      "Sentence one",
      "Sentence two",
      "Sentence three",
    };
    
    int index = 0; // initializes variable "index" to zero
    
    void setup() {
      size(600, 600);
    }
    
    void draw() {
      background(255);
      fill(0);
      text(sentences[index], 10, 100); // displays sentence at index from the array
    }
    
    // when mouse pressed 
    void mousePressed() {
      index = int(random(3)); // picks a random value for index: either 0,1,2
    }
    // when mouse released
    void mouseReleased() {
      index = 0; // always displays the 1st sentence when mouse is not pressed
    }