Hello , i'm working on a small game and i want to add a timer in the world class . Because i want after the time elapses my game to start, can anyone help me ? thanks
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
import java.awt.Font;
/**
* Write a description of class Clock here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Clock extends Actor
{
private static final int STARTING_TIME = 180;
private int seconds = STARTING_TIME;
private long lastCurrentSecond;
private long timeSaved = 0;
private boolean count = false;
public Clock() {
getImage().clear();
getImage().scale(130, 70);
}
public void act() {
if (count) {
if (System.currentTimeMillis() - lastCurrentSecond >= 1000) {
lastCurrentSecond += 1000;
seconds--;
drawTime();
}
if (seconds == 0) {
//time up;
}
}
}
private void drawTime() {
int min = (int) (seconds / 60);
int sec = seconds % 60;
String remainingTime;
if (sec < 10) {
remainingTime = min+":0"+sec;
}
else {
remainingTime = min+":"+sec;
}
getImage().setColor(Color.gray);
getImage().fill();
GreenfootImage text = new GreenfootImage("Time left:", 30, Color.black, new Color(0, 0, 0, 0));
GreenfootImage time = new GreenfootImage(remainingTime, 40, Color.black, new Color(0, 0, 0, 0));
getImage().drawImage(text, (getImage().getWidth()/2)-(text.getWidth()/2), 5);
getImage().drawImage(time, (getImage().getWidth()/2)-(time.getWidth()/2), 30);
}
public void startClock() {
lastCurrentSecond = System.currentTimeMillis() - timeSaved;
count = true;
}
public void stopClock() {
timeSaved = System.currentTimeMillis() - lastCurrentSecond;
count = false;
}
public void resetClock() {
seconds = STARTING_TIME;
}
}