AntHill的构造

蚂蚁的巢穴包括： code format="java" import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot)
 * 有限数量的蚂蚁；
 * 巢穴的位置，可以由本身控制也可以从world对象控制；
 * 巢穴的样子，就是图片的设置；
 * 巢穴中蚂蚁找到的食物的数量

/** * A hill full of ants. * * @author Michael Kolling * @version 1.1 */ public class AntHill extends Actor {   /** Number of ants that have come out so far. */   private int ants = 0;

/** Total number of ants in this hill. */   private int maxAnts = 40;

/** Counter to show how much food have been collected so far. */   private Counter foodCounter;

/**    * Constructor for ant hill with default number of ants (40). */   public AntHill {   }

/**    * Construct an ant hill with a given number of ants. */   public AntHill(int numberOfAnts) {       maxAnts = numberOfAnts; }

/**    * Act: If there are still ants left inside, see whether one should come out. */   public void act {       if(ants < maxAnts) {           if(Greenfoot.getRandomNumber(100) < 10) {               getWorld.addObject(new Ant(this), getX, getY); ants++; }       }    }

/**    * Record that we have collected another bit of food. */   public void countFood {       if(foodCounter == null) {           foodCounter = new Counter("Food: "); int x = getX; int y = getY + getImage.getWidth/2 + 8;

getWorld.addObject(foodCounter, x, y); }       foodCounter.increment; } } code 上面AntHill中提到一个Counter类，介绍一下他的实现： =返回= code format="java5" import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot)

/** * Counter that displays some taxt and a number. * * @author Michael Kolling * @version 1.1 */ public class Counter extends Actor {   private int value = 0; private String text;

/**    * Create a counter without a text prefix, initialized to zero. */   public Counter {       this(""); }

/**    * Create a counter with a given text prefix, initialized to zero. */   public Counter(String prefix) {       text = prefix; int imageWidth= (text.length + 2) * 10; setImage(new GreenfootImage(imageWidth, 16)); updateImage; }

/**    * Increment the counter value by one. */   public void increment {       value++; updateImage; }

/**    * Show the current text and count on this actor's image. */   private void updateImage {       GreenfootImage image = getImage; image.clear; image.drawString(text + value, 1, 12); } } code