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

2013/3/18

Need help with score counter and timer!

cagrinsoni97 cagrinsoni97

2013/3/18

#
I am working on a game, and would really appreciate if anybody could tell me how to add a score counter and a timer. Thanks.
danpost danpost

2013/3/19

#
A simple score counter and timer can both be created from the same class code. Create a new sub-class of Actor and name it 'Statistic'. Replace the code created in that class with the code below. Create one instance of the class for a timer and another instance for a counter. Use the methods available to change the caption and/or value.
import greenfoot.*;
import java.awt.Color;

public class Statistic extends Actor
{
    private String caption = "";
    private int value;

    // constructor for a Statistic object
    public Statistic(String statText)
    {
        caption = statText;
        updateImage();
    }

    // constructor for just displaying a number
    public Statistic()
    {
        this(""); // calls the constructor above
    }

    // creates and updates the image of this Statistic object
    private void updateImage()
    {
        String imgText = caption;
        if (!"".equals(caption)) imgText += ": ";
        GreenfootImage image = new GreenfootImage(imgText + value, 16, Color.black, new Color(0, 0, 0, 0));
        setImage(image);
    }

    // Used to set, change or remove the caption
    public void setCaption(String statText)
    {
        caption = statText;
        updateImage();
    }

    // used to set the value to a specific amount
    public void setValue(int val)
    {
        value = val;
        updateImage();
    }

    // used to adjust the value (a negative amount reduces the value)
    public void add(int amt)
    {
        value += amt;
        updateImage();
    }

    // returns the current caption of this Statistic object
    public String getCaption()
    {
        return caption;
    }

    // returns the current value of this Statistic object
    public int getValue()
    {
        return value;
    }
}
cagrinsoni97 cagrinsoni97

2013/3/20

#
Thanks, but how do I update the image? (sorry, I'm a beginner)
danpost danpost

2013/3/20

#
Lines 22 through 29 is the 'updateImage' method. It is called automatically anytime the caption or the value of the object changes. You just need to create and add the objects in your world class, setting field references to the objects so you can access them. Add these objects to the world in your world constructor.
private Statistic score = new Statistic("Score");
private Statistic timer = new Statistic("Time");
Then when the score changes (let us say goes up by five): score.add(5); Initially save a start time using System.currentTimeMillis() in a long field, and use the same minus the start time divided by 1000 as the value to set the timer object to.
You need to login to post a reply.