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

2014/1/8

Clock

quakster1 quakster1

2014/1/8

#
Iv been reading other discussions on this topic but I dont really understand it. How do I make a clock count up? I canth of any way on how to do it.
danpost danpost

2014/1/8

#
A clock is basically an actor Counter object that runs with a delay int counter field. The delay counter increments each act until a certain value is reached, at which point it is reset back to zero and the Clock counter is incremented. Below, I referenced a simple Actor whose image is changed to display the clock value:
// *** in World class ***
// add instance fields
private Actor clock = new Actor(){};
private int clockTime;
private int clockRegulator;
// in constructor
clock.setImage(new GreenfootImage("Time: "+clockTime, 20, java.awt.Color.black, null);
addObject(clock, 100, 20);
// in act method
runClock();
// new method
private void runClock()
{
    clockRegulator = (clockRegulator+1)%50;
    if (clockRegulator == 0)
    {
        clockTime++;
        clock.setImage(new GreenfootImage("Time: "+clockTime, 20, java.awt.Color.black, null);
    }
}
The '50' at the end of line 14 can be adjusted to suit the amount of delay between ticks of the clock. If you are wondering, that line behaves like the following:
clockRegulator++;
if (clockRegulator == 50) clockRegulator = 0;
Abomb1126 Abomb1126

2014/1/8

#
declare in your class an integer variable like this
int clock = 0;
, then at the bottom of your act method, add the code
clock++;
. What this will do is every time the Actor acts, or every frame, your clock will go up by 1. So after around 50-60 frames, your clock will be around will be at one second, then 50-60 more, two seconds. And so on... Now, if you want to do something after a certain time limit, you can input
//Under the act Method
if(clock == 300){ //This is the number of frames you can change   Remember, 50-60 frames, is about 1 second.
    doThisMethod(); //Complete the method under your choosing
    clock = 0; //resets the clock again
}
danpost danpost

2014/1/8

#
Sorry, lines 7 and 18 are both missing a closing parenthesis at the end of the statement. They should show as:
clock.setImage(new GreenfootImage("Time: "+clockTime, 20, java.awt.Color.black, null));
quakster1 quakster1

2014/1/9

#
I just managed to try this now and when I tried the code, the greenfoot picture was there for a couple seconds there is like a delay. How do I remove it
danpost danpost

2014/1/9

#
quakster1 wrote...
I just managed to try this now and when I tried the code, the greenfoot picture was there for a couple seconds there is like a delay. How do I remove it
Who are you writing to and what is your current code (use the 'code' tag under the input box and show the entire class).
You need to login to post a reply.