Search code examples
processingmousepress

Processing - Mouse Pressed to generate new values


I have this code to generate a grid of random tiles, using class and object. I want to whenever user press the mouse, canvas will automatically refresh and generate a new art work. And the mousepress function I've tried has not working yet. Thank you for your help!

  void setup(){
   size(400,400);
   for (int i=0; i<8; i++){
     for (int j=0; j<8; j++){
       blk[i][j]= new Block(i*50,j*50);
     }
   }
}



void draw(){
   background(255);
   for (int i=0; i<8; i++){
     for (int j=0; j<8; j++){
       float num = random(0,5);
        if (int(num)<3){
          blk[i][j].tile();
          blk[i][j].line1();  
        }
        else {
          blk[i][j].tile();
          blk[i][j].line2();  
        }         
     }
   }
   noLoop();
}

void mousePressed(){
  
}
// Class
class Block{
  
  float x,y;
  
  Block(float _x, float _y){
    x=_x;
    y=_y;
  }
  
  void tile(){
    stroke(0);
    strokeWeight(2);
    square(x,y,50);
  }
  
  void line1(){
    stroke(0);
    strokeWeight(2);
    line(x,y,x+50,y+50);
  }
  
  void line2(){
    stroke(0);
    strokeWeight(2);
    line(x+50,y,x,y+50);
  }
}

Solution

  • When the mouse is pressed tell it to redraw():

    void mousePressed() {
      redraw();
    }
    

    I also had to add this line of code at the top of the code that you posted:

    Block[][] blk = new Block[400][400];