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

2013/1/3

Timer

hertyje hertyje

2013/1/3

#
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
Gevater_Tod4711 Gevater_Tod4711

2013/1/3

#
Well I can give to you a clock class that I use in my game. This clock also shows the time as an image on the screen. If you don't need this you can just delete it from the world.
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;
    }
}
You can change the time which is counted down by changing the value of STARTING_TIME. If you create the clock object it will not start counting. To make it start you have to call the method startClock().
1green2 1green2

2014/1/6

#
I think this works except the clock image is transparent for some reason?
You need to login to post a reply.