Counter.java

 
1
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)
2

    
3
import java.awt.Color;
4
import java.awt.Graphics;
5

    
6
/**
7
 * Counter that displays a text and number.
8
 * 
9
 * @author Michael Kolling
10
 * @version 1.0.1
11
 */
12
public class Counter extends Actor
13
{
14
    private static final Color textColor = new Color(255, 180, 150);
15
    
16
    private int value = 0;
17
    private int target = 0;
18
    private String text;
19
    private int stringLength;
20

    
21
    public Counter()
22
    {
23
        this("");
24
    }
25

    
26
    public Counter(String prefix)
27
    {
28
        text = prefix;
29
        stringLength = (text.length() + 2) * 10;
30

    
31
        setImage(new GreenfootImage(stringLength, 16));
32
        GreenfootImage image = getImage();
33
        image.setColor(textColor);
34

    
35
        updateImage();
36
    }
37
    
38
    public void act() {
39
        if(value < target) {
40
            value++;
41
            updateImage();
42
        }
43
        else if(value > target) {
44
            value--;
45
            updateImage();
46
        }
47
    }
48

    
49
    public void add(int score)
50
    {
51
        target += score;
52
    }
53

    
54
    public int getValue()
55
    {
56
        return value;
57
    }
58

    
59
    /**
60
     * Make the image
61
     */
62
    private void updateImage()
63
    {
64
        GreenfootImage image = getImage();
65
        image.clear();
66
        image.drawString(text + value, 1, 12);
67
    }
68
}