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

2017/7/1

Set a time limit to the game

Penlos Penlos

2017/7/1

#
I already got a running game, but it runs for an unlimited amount of time. And now I want to set a time limit to the game, because it should end after like 3min. Is there a way to like set a timer and after 3min all actors get deleted and an ending screen appears? Thank you in forward.
Super_Hippo Super_Hippo

2017/7/1

#
You could add that to your world subclass:
1
2
3
4
5
6
7
8
9
10
11
private int timer = 3*60*55; //about 3 min at normal speed
 
public void act()
{
    if (--timer == 0)
    {
        removeObjects(getObjects(null));
        //(create and) set different background
        //Greenfoot.stop(); //stop the scenario (if wanted)
    }
}
You could also display the time of course.
Penlos Penlos

2017/7/1

#
Thank you very much! It works well. But I got two questions: What number would 2min be?
Super_Hippo wrote...
You could also display the time of course.
How would you do that?
Super_Hippo Super_Hippo

2017/7/1

#
The calculation (3*60*55) is (3 minutes * 60 seconds/minute * 55 act cycles / second). So for 2 minutes, you can change the 3 to a 2. The easiest way to display the time would be to use the showText method.
1
getWorld().showText("Time left: " + timer/55 + "seconds");
Alternatively, you can add an Actor object to the world which you will give an image showing the time. You could also try to display minutes and second if you wish.
Penlos Penlos

2017/7/1

#
But getworld and showtext do have to be in actor class, don't they?
danpost danpost

2017/7/1

#
The best object to be used to run a game timer is the World object. As such, you would not use getWorld at all. The following would be sufficient:
1
showText("Time left: " + timer/55 + " seconds");
You could show minutes and seconds like this:
1
showText("Time left: " + timer/(60*55) + " min. " + (timer%(60*55))/55 + "sec.");
Penlos Penlos

2017/7/1

#
Thank you both very much! You were a great help to me.
You need to login to post a reply.