Monday, June 29, 2009

Java Greenfoot: Self Replication

To create more dynamics, we will extend the ants scenario, such that the ants population can grow.

There are two ways to implement this. If the condition for a population growth is met:
  • just increase the value of maxAnts. You will need a mutator method for the variable. Additional ants will then automatically be created (see the act() method)

  • create new AntHill objects


Starting condition, using scenario3() with additional two Predator objects (scenario ants2e)

Here we address the second case. Copy and place the following code snippet to the AntHill class. checkFoodCount() basically checks if the value of the foodCounter is high enough for "expanding" the population. This is the condition mentioned above. If it is the case, the AntHill object will instantiate a new AntHill object at a random position. The number of ants living in the new AntHill object is set to be a half of that in the parent AntHill.
private int maxFoodCount = 40;

private void checkFoodCount() {
if(foodCounter != null) {
if(foodCounter.getValue() >= maxFoodCount) {
foodCounter.setValue(0);
AntHill anthill;
int x,y;
do {
x = 5 Greenfoot.getRandomNumber
(getWorld().getWidth()-10);
y = 5 Greenfoot.getRandomNumber
(getWorld().getHeight()-10);
anthill = (AntHill) getOneIntersectingObject
(AntHill.class);
} while (anthill != null);
getWorld().addObject(new AntHill(maxAnts/2), x, y);
}
}
}

The method checkFoodCount() shall be called within the act() method, as displayed below:
public void act() {
if(ants < maxAnts) {
if(randomizer.nextInt(100) < 10) {
getWorld().addObject(new Ant(this), getX(), getY());
ants ;
}
}
checkFoodCount();
}


You will also need a mutator for the variable value in the Counter class, since the value has to be reset every time the AntHill object replicates itself.
public void setValue(int val) 
{value = val; updateImage();}

Webpage Keywords : Java programming, Java game, Greenfoot scenario

No comments:

Post a Comment