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


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | 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; } } |