Showing posts with label Greenfoot Framework. Show all posts
Showing posts with label Greenfoot Framework. Show all posts

Monday, June 29, 2009

Java Greenfoot: Food Fabric

The ants scenario "ends" if there no more Food objects exist in the world. In such a case, the ants still continuously move and explore the world, but surely for nothing. We can help these poor ants by creating a new actor that is able to produce food : the FoodFabric.

Some basic considerations for this new actor are given as follows.
  • A FoodFabric object shall be represented by dynamic images to indicate that the object is dynamic i.e. can produce food.

  • The basic behaviours of a FoodFabric object are to produce Food objects and to maintain its visual appearance.

import greenfoot.*;  
import java.util.Random;
import java.util.List;

public class FoodFabric extends Actor
{
private static final Random randomizer =
AntWorld.getRandomizer();

private GreenfootImage[] images;
private int size=0;
private int increment=1;
private final static int IMAGE_COUNT= 8;

public FoodFabric() {
initialiseImages();
setImage(images[0]);
}

public void act() { ... }
public void initialiseImages() { ... }
private void generateFood() { ... }
private boolean randomChance() { ... }
}

The skeleton of the class is given above. It might remind us of the structure of the Explosion class in the lunarlander scenario. Indeed, the mechanism for image animation is quite similar to that in the Explosion class. The intialiseImages() method is also more-or-less similar to the method in the Explosion class. However, some image manipulations are done differently.
public void initialiseImages() {
if(images == null) {
GreenfootImage baseImage = new
GreenfootImage("images/circle.png");
GreenfootImage foodImage = new
GreenfootImage("images/center.png");
GreenfootImage scaledImage;
int maxSize = baseImage.getWidth();
int delta = maxSize / IMAGE_COUNT;
int size = 0;
images = new GreenfootImage[IMAGE_COUNT];
for(int i=0; i < IMAGE_COUNT; i ) {
size = size delta;
images[i] = new GreenfootImage(50,50);
scaledImage = new GreenfootImage(baseImage);
scaledImage.scale(size, size);
images[i].drawImage(scaledImage,
25-size/2,25-size/2);
images[i].drawImage(foodImage,10,10);
}
}
}

public void act() {
setImage(images[size]);

size = increment;
if((size>=IMAGE_COUNT)||(size<=0)) {
increment = -increment;
size = increment;
}
generateFood();
}



A FoodFabric object surrounded by some Food objects; the circle in the background grows and shrinks alternately.

The codes before generateFood() in the act() method are to change the appearance of the object. The generateFood() method will put Food objects at slightly randomized positions around the FoodFabric (see the codes below).
private void generateFood() {
int pos = randomizer.nextInt(8);
int x = getX(); int y = getY();
int xFood=x, yFood=y;
int xyOffset = 20;
int xDelta = randomizer.nextInt(10);
int yDelta = randomizer.nextInt(10);
switch(pos) {
// ...
}
if(randomizer.nextInt(2)==0) xFood += xDelta;
else xFood -= xDelta;
if(randomizer.nextInt(2)==0) yFood += yDelta;
else yFood -= yDelta;

if(randomChance(25)) {
List foods = getWorld().getObjectsAt(
xFood, yFood, Food.class);
if(foods.isEmpty()) {
getWorld().addObject(
new Food(), xFood, yFood);
}
}
}



A screenshot showing the ants scenario with a FoodFabric object.


Webpage Keywords : Java programming, Java game, Greenfoot scenario

Java Greenfoot: Scene Visibility

In a game, we might want to hide several objects such that the player cannot immediately know where the objects are located.
The player has to "explore" the environment first in order to get that information. Once an area has been "explored", then it becomes visible.

We will demonstrate how to do this, by using the ants scenario. First we need a new class of objects which act as a cover. We name it Fog in this case. The object actually does nothing. If it exists it hides a part of the world behind it. If the covered area is "explored" the corresponding object shall be removed and the area becomes "clear" and visible.

After creating the Fog class, open the Ant class and make a modification as displayed below.

private void openScene()
{
Fog fog = (Fog) getOneIntersectingObject(Fog.class);
if(fog != null)
getWorld().removeObject(fog);
}

Public void act()
{
// ...
openScene();
}

The method OpenScene() will remove a Fog object that intersects with the corresponding Ant object. There could actually be more than one Fog object intersecting with the ant. But since in the ants scenario we are usually dealing with many Ant objects that continuously move, we do not necessarily remove all intersecting Fog objects at a time. The situation is different for the AntHill object. Here we need to remove all intersecting Fog objects (see the code snippet below)
private void openScene()
{
List fogs = getIntersectingObjects(Fog.class);
Iterator i = fogs.iterator();
while(i.hasNext()) {
Actor a = (Actor) i.next();
getWorld().removeObject(a);
}
}

public void act()
{
// ...
openScene();
}

public void addedToWorld(World world)
{
openScene();
}

The method addedToWorld() needs to be defined, to get the effect immediately works, once an AntHill object is created and placed to the world.

Finally, we need to initialise and create Fog objects to hide all regions in the world for the first time. As can be seen below, this is handled by the method makeFog() which has to be called before scenario3() in the AntWorld() constructor.
public AntWorld()
{
// ...
makeFog();
scenario3();
}

public void makeFog()
{
for(int i=0;i<=SIZE-1;i =25) {
for(int j=0;j<=SIZE-1;j =25) {
addObject(new Fog(), i, j);
}
}
}

The following two screenshots illustrating the effect of the above mentioned modifications.


Starting condition indicating the effect of makeFog() in the AntWorld constructor and openScene() inside the AntHill class.



A condition in the AntWorld after the simulation runs for a while


Webpage Keywords : Java programming, Java game, Greenfoot scenario

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

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

Java Greenfoot: Wombats Collision

Here we consider the wombats or wombats2 scenario included in the standard Greenfoot distribution. The last modification mentioned in the tutorial made by Michael at the Greenfoot site, is to "stop wombats from walking through rocks". This is done by adding the following codes
List rocks = myWorld.getObjectsAt(x, y, Rock.class);  
if(rocks.isEmpty()) { return true; } else { return false; }

which replace the last statement in the canMove() method. With such a modification, a wombat "sees" first before it moves. But, it recognizes only rocks and the borders of the world. We can extend this functionality, by giving a capability to "see" other wombats and then perform an appropriate action. For example, if it is facing other wombat objects it changes its moving direction. To implement this, replace the codes above with the following snippet.
List rocks = myWorld.getObjectsAt(x, y, Rock.class);  
if(!rocks.isEmpty()) { return false; }

List otherwombats = myWorld.getObjectsAt(
x, y, Wombat.class);
if(otherwombats.isEmpty()) { return true; }
else { return false; }

The following picture illustrates the result of this modification.


Wombats behavior after modification; shown by sequential calling of method act()


As you can see, a wombat detects first whether rocks exist in the cell in front of it. If the result is negative, it tries to detect if there are other wombats. When it indeed meets ones, canMove() will return false i.e. it can not move forward, otherwise it can.

Webpage Keywords : Java programming, Java game, Greenfoot scenario

Java Greenfoot: Displaying Information

Displaying Information: A More Interactive "Lunarlander"

Sometimes, it is necessary to give the users some information regarding which type of (key) input is accepted by our scenario.

As an example, let us consider the extended lunarlander scenario. Well, I call this "extended" because I've made several modifications by extending the behavior of the Lander, i.e. it can perform several flight/landing modes which are determined by user inputs. These modifications are addressed in the book and might be discussed in this website next time. Below is a screenshot indicating how such "an information screen" is integrated to the scenario.


Displaying information for the lunarlander scenario

Step 1 : create an image containing the information you want to show and place it in the "images" subfolder of the lunarlander scenario. We will use this as the class image of the "information screen".

Step 2 : create a subclass from Actor, name it as you like and associate it with the image created in step 1 above.

Step 3 : edit the new Actor (here I call it InfoImage) and copy the following codes (explanation at the end).

public class InfoImage extends Actor
{
private boolean active = true;

public InfoImage() { act(); }

public void act() {
if(active) {
Greenfoot.stopSimulation();
active = false;
}
}

public void setActive(boolean val){

active = val;

}
public boolean getActive() { return active; }
}

Step 4 : edit the class Lander and add some codes for the corresponding methods below.

public void act()
{
destroyInfo();
processKeys();
// ... original codes
}

private void processKeys() {
// ... original codes
if(Greenfoot.isKeyDown("i")) {
int xlocal = getWorld().getWidth()/2;
int ylocal = getWorld().getHeight()/2;
getWorld().addObject(new InfoImage(),
xlocal, ylocal);
}
}

private void destroyInfo() {
List listvar =
getWorld().getObjects(InfoImage.class);
Iterator i = listvar.iterator();
if(i.hasNext()){
InfoImage varinfo= (InfoImage) i.next();
if(!varinfo.getActive())
getWorld().removeObject(varinfo);
}
}

An InfoImage object is an actor with a simple behavior. It has to exist in the world if it is in an active state. And if it is active, the simulation shall be stopped/paused. This state is saved in the boolean variable state. If it is not in an active state (variable active = false) the object shall be removed from the world.

The object is created as requested e.g. if the user want to see the information. In our case, this event happens when the user types the key "i". It can also be created at the beginning, by putting the following statement in the Moon constructor:

addObject(new InfoImage(), getWidth()/2, getHeight()/2);

The code fragments mentioned in step 4, must not necessarily be added to the class Lander, since Greenfoot calls the act() method from all objects in the world. But in the lunarlander scenario, we do not have many choices, right ? :-)

Webpage Keywords : Java programming, Java game, Greenfoot scenario