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

2013/7/15

Can we display timer in a game?

1
2
danpost danpost

2013/7/19

#
I came up with the following for the CountDown class:
import greenfoot.*;
import java.awt.Color;

public class CountDown extends Actor
{
    private static final Color TRANS = new Color(0, 0, 0, 0),
                               BLACK = Color.black,
                               LIGHT = Color.lightGray,
                               DARK = Color.darkGray;
    private int count = 10;
    private int timer;
    
    public CountDown()
    {
        updateImage();
    }
    
    private void updateImage()
    {
        GreenfootImage text = new GreenfootImage(""+count, 24, BLACK, TRANS);
        int gap = 8;
        GreenfootImage base = new GreenfootImage(text.getWidth()+gap*2, text.getHeight()+gap*2);
        base.drawImage(text, gap, gap);
        for (int i=0; i<3; i++) base.drawRect(i, i, base.getWidth()-1-i*2, base.getHeight()-1-i*2);
        setImage(base);
    }

    public void act()
    {
        if (count == 0)
        {
            if (Greenfoot.isKeyDown("enter")) getWorld().removeObject(this);
            return;
        }
        timer = (timer+1)%60;
        if (timer == 0)
        {
            count--;
            updateImage();
            if (count == 0)
            {
                String msg = "Press 'enter'\nto launch\nthe rocket";
                GreenfootImage sign = new GreenfootImage(msg, 36, Color.black, new Color(0, 0, 0, 0));
                int gap = 30;
                GreenfootImage base = new GreenfootImage(sign.getWidth()+gap*2, sign.getHeight()+gap*2);
                base.setColor(DARK);
                base.fill();
                base.setColor(LIGHT);
                int frame = 10;
                base.fillRect(frame, frame, base.getWidth()-1-frame*2, base.getHeight()-1-frame*2);
                base.drawImage(sign, gap, gap);
                setImage(base);
            }
        }
    }
}
and this in the world class for the trigger to launch the rocket:
import greenfoot.*;

public class Background extends World
{
    private boolean ready;
    private Rocket rocket = new Rocket();
    
    public Background()
    {    
        super(800, 400, 1);
        addObject(rocket, getWidth()/2, getHeight()-rocket.getImage().getHeight()/2);
        addObject(new CountDown(), 400, 200);
    }
    
    public void act()
    {
        if (!ready && !getObjects(CountDown.class).isEmpty()) ready = true;
        if (ready && getObjects(CountDown.class).isEmpty())
        {
            rocket.launch();
        }
    }
}
Add a public void method (called 'launch') in the rocket class that changes a boolean flag to 'true' for the thrusting state.
You need to login to post a reply.
1
2