-
Notifications
You must be signed in to change notification settings - Fork 2
/
Counter.java
71 lines (60 loc) · 1.41 KB
/
Counter.java
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
70
71
import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot)
import java.awt.Color;
import java.awt.Graphics;
/**
* Counter that displays a text and number.
*
* @author Michael Kolling
* @version 1.0.1
*/
public class Counter extends Actor
{
private final String prefix;
private final Color textColor;
// the counter seeks to keep value in sync with target
private int value = 0;
private int target = 0;
public Counter(String prefix)
{
this(new Color(255, 180, 150), prefix);
}
public Counter(Color textColor, String prefix)
{
this.textColor = textColor;
this.prefix = prefix;
int prefixLength = (prefix.length() + 2) * 10;
GreenfootImage image = new GreenfootImage(prefixLength, 16);
image.setColor(textColor);
setImage(image);
updateImage();
}
public void act() {
if (value < target)
{
value++;
updateImage();
}
else if (value > target)
{
value--;
updateImage();
}
}
public void add(int score)
{
target += score;
}
public int getValue()
{
return value;
}
/**
* Update the counter image
*/
private void updateImage()
{
GreenfootImage image = getImage();
image.clear();
image.drawString(prefix + value, 1, 12);
}
}