加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Counter.java 2.54 KB
一键复制 编辑 原始数据 按行查看 历史
luyanfei78 提交于 2021-04-13 22:33 . add initial files.
import greenfoot.*;
/**
* A Counter class that allows you to display a numerical value on screen.
*
* The Counter is an actor, so you will need to create it, and then add it to
* the world in Greenfoot. If you keep a reference to the Counter then you
* can adjust its value.
*
* @author Neil Brown and Michael Kölling
* @version 1.1
*/
public class Counter extends Actor
{
private static final Color transparent = new Color(0,0,0,0);
private GreenfootImage background;
private int value;
private int target;
private String prefix;
public Counter()
{
this(new String());
}
/**
* Create a new counter, initialised to 0.
*/
public Counter(String prefix)
{
background = getImage(); // get image from class
value = 0;
target = 0;
this.prefix = prefix;
updateImage();
}
/**
* Animate the display to count up (or down) to the current target value.
*/
public void act()
{
if (value < target) {
value++;
updateImage();
}
else if (value > target) {
value--;
updateImage();
}
}
/**
* Add a new score to the current counter value. This will animate
* the counter over consecutive frames until it reaches the new value.
*/
public void add(int score)
{
target += score;
}
/**
* Return the current counter value.
*/
public int getValue()
{
return target;
}
/**
* Set a new counter value. This will not animate the counter.
*/
public void setValue(int newValue)
{
target = newValue;
value = newValue;
updateImage();
}
/**
* Sets a text prefix that should be displayed before
* the counter value (e.g. "Score: ").
*/
public void setPrefix(String prefix)
{
this.prefix = prefix;
updateImage();
}
/**
* Update the image on screen to show the current value.
*/
private void updateImage()
{
GreenfootImage image = new GreenfootImage(background);
GreenfootImage text = new GreenfootImage(prefix + value, 22, Color.BLACK, transparent);
if (text.getWidth() > image.getWidth() - 20)
{
image.scale(text.getWidth() + 20, image.getHeight());
}
image.drawImage(text, (image.getWidth()-text.getWidth())/2,
(image.getHeight()-text.getHeight())/2);
setImage(image);
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化