Random from an array ?

edited September 2014 in How To...

Hello, I'm new to processing. I was looking for solution half of a day before asking I would like to pick up random from an array. how the code would look like ?

int[] dice = {15,56,3,5,54,10};
void draw(){
     if (mousePressed==true){
       for(int i=0; i<=dice.length; i++){
         //??
       }
     }
}

Answers

  • Answer ✓

    There are some issues with your code which you will discover.

    The draw method is executed ~60 times a second so will you hold done a mouse button you could get several changes. It is better to use the mouse clicked event and catch this outside the draw method and store the selected random number in a variable so here it is

    int[] dice = { 15, 56, 3, 5, 54, 10  };
    int value = 0;
    
    void draw() {
      background(255);
      fill(0);
      text("Value = " + value, 4, 30);
    }
    
    void mouseClicked() {
      value = dice[int(random(0, dice.length))];
    }
    
  • Extra tip: No need to use 2 arguments for random() when picking from 0:
    value = dice[(int) random(dice.length)];

    http://processing.org/reference/random_.html

  • Another option is the combo noLoop() + redraw():
    http://processing.org/reference/noLoop_.html
    http://processing.org/reference/redraw_.html

    // forum.processing.org/two/discussion/7352/random-from-an-array-
    
    static final int[] dice = {
      15, 56, 3, 5, 54, 10
    };
    
    void setup() {
      size(200, 150, JAVA2D);
      frameRate(5);
      smooth(4);
      noLoop();
      fill(#008000);
    
      textSize(050);
      textAlign(CENTER, CENTER);
    }
    
    void draw() {
      background(-1);
      int pick = dice[(int) random(dice.length)];
      text("Roll: " + nf(pick, 2), width>>1, height>>1);
    }
    
    void mousePressed() {
      redraw();
    }
    
    void keyPressed() {
      redraw();
    }
    
  • Thank you guys!

Sign In or Register to comment.