Search code examples
processing

Is there a way to keep track of objects clicked and display them as a message when the program ends in processing java?


Im trying to create a small game where the user clicks randomly generated coins and I want it to keep track of how many they click. Also, I want this message to print out when I click the stop button on the processing window.

I tried using the exit() command as a public void, but that did not work.


Solution

  • You're on the right track. You can check if the object is over a rectangle in the mouseClicked() even handler to increment your counter.

    You should be able to override the exit() sketch function, however I noticed that it doesn't trigger when you use the stop button in the Processing IDE. It does work when you use the ESCAPE key to close the sketch. This might actual work better if you plan to export the sketch as an application (via File > Export Application).

    Here's a super basic sketch to illustrated the above ideas:

    // dummy coin data
    int[][] coinBoundingBoxes = {
      {30, 30, 30, 30},
      {135, 30, 30, 30},
      {250, 30, 30, 30},
      {30, 150, 30, 30},
      {135, 150, 30, 30},
      {250, 150, 30, 30},
      {30, 250, 30, 30},
      {135, 250, 30, 30},
      {250, 250, 30, 30},
    };
    // total number of coins clicked
    int numClicks = 0;
    
    void setup(){
      size(300, 300);
    }
    
    void draw(){
      background(0);
      // draw coins
      fill(255, 192, 0);
      for(int[] bbox : coinBoundingBoxes)
        ellipse(bbox[0] + bbox[2] * 0.5, bbox[1] + bbox[3] * 0.5, bbox[2], bbox[3]);
      // draw text
      fill(255);
      text(numClicks, 10, 15);
    }
    
    void mouseClicked(){
      // check if any coin is clicked to increment
      for(int[] bbox : coinBoundingBoxes){
        if(isInRect(mouseX, mouseY, bbox)){
          numClicks++;
        }
      }
    }
    
    // check is x,y are within bbox x,y,w,h (0, 1, 2, 3)
    boolean isInRect(int x, int y, int[] r){
      return (x >= r[0] && x <= r[0] + r[2]) &&
             (y >= r[1] && y <= r[1] + r[3]);
    }
    
    // override exit to print clicks first
    void exit(){
      println("total clicks: ", numClicks);
      super.exit();
    }