Monday, June 29, 2009

Java Greenfoot: Forbidden Area

The ants scenario more-or-less simulates a case of "swarm intelligence". How intelligent they are, surely depends on our "codes". The ants in current version of the scenario cannot see "dangerous" obstacles or areas from which they should make a distance. Here we will modify the behavour of ants, so they can recognise regions in the world they can enter and those they cannot. To make such a modification, we just need the following two steps.

Step 1 : make a background for the world, containing "forbidden areas" which are marked with a different colour (it is black in this case). Load it in the AntWorld constructor e.g. setBackground("antbackground.png");


The starting condition; all regions in black are "forbidden"

Step 2 : open the class Ant, find the method move() and write
several statements as listed below.
private void move() {
try {
int x = getX() + deltaX;
int y = getY() + deltaY;

Color color = getWorld().getColorAt(x, y);
if(!color.equals(Color.BLACK)) setLocation(x,y);
}
catch (IndexOutOfBoundsException e) {}
setRotation((int)
(180 * Math.atan2(deltaY, deltaX) / Math.PI));
}


A situation in the AntWorld (after the simulation runs for a while)

Don't forget to import the Color package in the Ant class. We also need to change a parameter for executing randomWalk() in headHome() method, because if the value is too small, ants may get stuck in many places.
if (randomChance(45)) {
randomWalk();
}

This doesn't solve the problem entirely also. We need some other moving strategies other than headHome(), so what do you think ? :-D

Webpage Keywords : Java programming, Java game, Greenfoot scenario

No comments:

Post a Comment