Good evening,
I have created my code below which appears to go through. The problem is that the image is never displayed on the canvas. I have even dropped the food manually on the canvas and watched the debug window walk the code and still no food. Here is the code:
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.Random;
import java.awt.Color;
/**
* A pile of food for which ants will search.
* A new object consists of 100 crumbs.
*/
public class Food extends Actor
{
private int nCrumbs;
private static final int MAX_CRUMBS = 100; // number of crumbs in one food pile
private static final int IMG_SIZE = 30; // the height and width of a food object
private static final int CRUMB_SIZE = 3; // the radius of a single crumb
private GreenfootImage image = null;
/**
* Create a new food source.
* It will have a certain number of crumbs
*/
public Food()
{
nCrumbs = MAX_CRUMBS;
updateImage();
}
/**
* Update the image of this food
*/
public void updateImage()
{
// Initialize image variable (already declared) as a new Image object
GreenfootImage image = new GreenfootImage(IMG_SIZE, IMG_SIZE);
// declare local variables x and y
int locX, locY;
// For-loop that counts up to the total number of crumbs in the Food object
for (int i = 0; i < nCrumbs; i++)
{
// Pick a random x for the crumb's center--random, not Gaussian
locX = Greenfoot.getRandomNumber(IMG_SIZE - 4) + 2;
// Pick a random y for the crumb's center--random, not Gaussian
locY = Greenfoot.getRandomNumber(IMG_SIZE - 4) + 2;
// Draw a solid circle centered at x and y with diameter 3
Color myColor = new Color(160, 200, 60);
//image.fillOval(locX, locY, CRUMB_SIZE, CRUMB_SIZE);
image.setColorAt(locX, locY, myColor);
setImage(image);
}
}
/**
* Get the image of this food
*/
public GreenfootImage getImage()
{
if (image == null)
{
updateImage();
}
return image;
}
/**
* Set the image
*/
public void setImage()
{
updateImage();
}
/**
* Decrease the number of crumbs available
* One ant takes one crumb from the Food pile
*/
// This is the method that is invoked when Ants pick up crumbs.
// decrease the number of crumbs in the pile by one
// If there are no crumbs left in this object ...
// removeObject(this); // Why doesn’t this remove the Food object??
// otherwise....
// update image
//Added code from original and remarked out the code within the method.
public void takeSome()
{
if (nCrumbs <= 0)
{
getWorld().removeObject(this);
}
else
{
updateImage();
}
}
/**
* Act - do whatever the Food wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// No action code required. Food is inert.
}
}
