This site requires JavaScript, please enable it in your browser!
Greenfoot back
jjimenez77
jjimenez77 wrote ...

2013/4/8

wombats2 how to make the Wombat smarter

jjimenez77 jjimenez77

2013/4/8

#
hello, i would appreciate any help regarding this issue. i'm modifying the scenario that comes with greenfoot wombat2, i want to make the wombat smarter, so that the wombat is always searching for the leaf, so he can eat it, i dont want the wombat to be walking around randomly, i would like him to look for the leaf, can somebody show me the code that i should use, i'm new at java programing.. thanks in advance ps. the souce code is in the greenfoot scenarios that come with it by default. sorry my english
danpost danpost

2013/4/8

#
It would all depend on how you want the wombat to search for the leaf and how smart you want it to be. He could map out (remember) where he has been and check places he has not been. He could find the closest leaf and go to eat it. Then repeat. He could systematically traverse the grid without mapping it out. He could have other ways.
jjimenez77 jjimenez77

2013/4/8

#
i want him to find the closest leaft and go eat it, not to transverse the grid without mapping it out, and if i put another leaf where he was already, the he must go back and eat it.
danpost danpost

2013/4/8

#
The following will find the closest leaf and then make a move toward it (if any found).
boolean inWorld = true;
int range = 1;
while (getNeighbours(range, false, Leaf.class).isEmpty())
{
    range++;
    if (range > getWorld().getWidth()+getWorld().getHeight()-1)
    {
        inWorld = false;
        break;
    }
}
if (inWorld)
{
    Leaf leaf = (Leaf)getNeighbours(range, false, Leaf.class).get(0);
    if (getX() != leaf.getX()) setLocation((int)Math.signum(leaf.getX()-getX()), getY());
    else if (getY() != leaf.getY()) setLocation(getX(), (int)Math.signum(leaf.getY()-getY()));
}
That should do it. The 'Math.signum' returns the sign of the value of the evaluated expression, negative one for negative values, positive one for positive values and zero for zero. You should 'canSee'/'eat' the Leaf class and if no leaf is eaten process this code.
You need to login to post a reply.