This site requires JavaScript, please enable it in your browser!
Greenfoot back
ezuxr
ezuxr wrote ...

2017/3/2

Have a problem with text for time

ezuxr ezuxr

2017/3/2

#
This is the code that I have for my time and the text...
private int timer = 900;
public MyWorld()
    { Text timerText = new Text();
        addObject(timerText, 115, 15);
        timerText.setText("Time left: " + (timer/60) + " " + "seconds");}

public void act(){
     if (timer>0)
     {
      timer--;
       Random r = new Random();
       if (timer%60==0) {
           timerText.setText("Time left: " + (timer/60) + " " + "seconds");
       }
       if(timer == 0)
       {
           Gameover gameover = new Gameover();
           addObject(gameover, 305, 200);
           Greenfoot.stop();
        }
     }

  }
The time works well and the text appears right but the problem is that the text appears "Time left: 15 seconds" even after clicking run... In short the number written in the text doesn't decrease as the time goes... What should I add more to make sure that the number is decreasing as the time flows...
danpost danpost

2017/3/2

#
Will need to see the code of your Text class. (not sure why you create a Random object in the middle of the code). (also, could move lines 15 through 20 to before line 14 so that the check is performed 1/60th of the time instead of every act cycle). (the outer 'if' block, checking the value of 'timer' to be greater than zero is not needed as the program is stopped when it reaches zero, although I can see why you might have done that. But now, each time 'Run' is clicked after the game stops, another Gameover object is added into the world. Better would be to use the 'started' method:
public void started()
{
    if (timer == 0) Greenfoot.stop();
}
You need to login to post a reply.