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

2013/4/26

how do you do a time counter

MBX5 MBX5

2013/4/26

#
hey im trying to create a time counter to show how long the player has been alive for can anyone help?
Entity1037 Entity1037

2013/4/27

#
You can do almost all of the normal java coding in greenfoot. Try using sleep, and every second, have a variable count up one. This should work: while (true){ Try{ Thread.sleep(1000); //The time is measured in miliseconds secondsAlive++; }catch{} } I can't try it at the moment to see if it works because I'm on my phone, but I don't see why not.
Duta Duta

2013/4/27

#
One way would be to store the time when the player is first spawned, and then at later stages use the difference between the current time and the start time for finding how long the player has been alive. For example:
1
2
3
4
5
6
7
8
9
// When the game is started, do:
long startTime = System.currentTimeMillis();
 
// Later (for example in an act() method), do:
long currentTime = System.currentTimeMillis();
int durationMillis = (int)(currentTime - startTime);
// durationMillis is in milliseconds, so you
// can convert to seconds/minutes whatever:
int durationSecs = durationMillis / 1000;
EDIT: This, however, won't work nicely with pausing. I'll make and upload an example scenario in a minute or three
Duta Duta

2013/4/27

#
I made a quick example that works nicely with the Greenfoot pause/resume button. Sorry I took so long, I got distracted. http://www.greenfoot.org/scenarios/8157
Gevater_Tod4711 Gevater_Tod4711

2013/4/27

#
There are many ways to do that. Like Duta already sad you can count the time using System.currentTimeMillis(). Another way would be to use a clock like this one or just to count up the acts. If you count up the acts you have to know how many acts there are per second. Therefore this scenario can help you. @Entity1037 This way will not work in Greenfoot. You can't use a infinite loop in Greenfoot because the code will always be executed again and again and the whole other code will never be executed. (And I think the catch block needs to know which exception should be caught. In this case it's an InterruptedException I think.)
Entity1037 Entity1037

2013/4/27

#
@Gevater_Tod4711 Oh... good to know.
You need to login to post a reply.