why is my exit timer not working?

edited December 2017 in Questions about Code

I'm making a chrismas tree program, that when you hit esc a timer starts and a message appear on the screen before the game closes, but when I press the button the game automatically ends without the timer.

https://paste.ofcode.org/UqmfvSGJ6Z3DrVWaAhC2Av

I want to display stuff right before the game closes.

Tagged:

Answers

  • Answer ✓

    One cannot run your code as it is incomplete. Nevertheless, what you need is to override the exit() function as I show below. If you press ESC, hit the x button in your window or call exit(), the code will execute. The code that you want to execute when your program exits should be placed there. I used a for loop as a demonstration.

    Kf

    void exit(){
    
      for(int i=0;i<1000000;i++)
        if(i%100==0)
           println("HOLD "+i);
    
      super.exit();
    }
    
  • so I just create an exit function if I understand correct? and I wanted the stuff to happen before the program runs the exit. In my mind placing the exit in the timer should bought me a few seconds to show a message. Here the full page of the first script or whatever that first page is. https://paste.ofcode.org/adSM3bAURSHy2zwzRRYek9

  • edited December 2017 Answer ✓

    This is one approach. Notice it is not 100% effective as it doesn't work if you close your window by clicking on the x in the top corner. But it works when you press ESC or any time you call the exit() function. I am deferring to call super.exit() only after the timer is done. Btw, do not use 1/frameCount as it doesn't do what you think it does. Below is the code.

    Kf

    boolean esc = false;
    float timer;
    
    void setup() {
      size(600, 600);
    }
    
    void draw() {
      background(0);
      noStroke();
      if (esc == false) {
      } else if (esc == true){
        //key=0;
        timer -= 1;
        text("This program was made by Cody Tremblay.",50,300);
        if (timer < 0){
          finalExit();
        }
      }
    }
    
    void keyPressed() {
      if (keyCode == ESC){
        exit();
      }
    }
    
    void exit(){ 
      esc=true;
      timer=90;
      while(timer>0);  //NOTICE this empty definition
      //super.exit();
      println("EXIT called");
    }
    
    void finalExit(){
     super.exit(); 
    }
    

    *******EDIT: Adding the while() inside the exit allows this code to work as you expected when you click on the X of the window of your sketch or when you press ALT+F4 in a Windows machine.

Sign In or Register to comment.