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

2017/3/8

how to i make a lobster eat every other crab?

Mjosue Mjosue

2017/3/8

#
Have the lobsters eat every other crab they find, since some of the crabs might not be tasty. Start by assuming that the first crab a lobster finds is not tasty so the lobster does not eat the first crab encountered. I keep the lobster keeps getting eaten on the first touch. A friend told me this has to do because they are still touching when the 1st touch is registered since they are so close. How do I fix this?
Mjosue Mjosue

2017/3/8

#
THIS IS WHAT I HAVE SO FAR public class Lobster extends Actor { /** * Do whatever lobsters do. */ public void act() { turnAtEdge(); randomTurn(); move(5); lookForCrab(); } /** * Check whether we are at the edge of the world. If we are, turn a bit. * If not, do nothing. */ public void turnAtEdge() { if ( isAtEdge() ) { turn(17); } } /** * Randomly decide to turn from the current direction, or not. If we turn * turn a bit left or right by a random degree. */ public void randomTurn() { if (Greenfoot.getRandomNumber(100) > 90) { turn(Greenfoot.getRandomNumber(90)-45); } } /** * Try to pinch a crab. That is: check whether we have stumbled upon a crab. * If we have, remove the crab from the game, and stop the program running. */ public void lookForCrab() { if ( isTouching(Crab.class) ) { removeTouching(Crab.class); Greenfoot.playSound("au.wav"); Greenfoot.stop(); } } }
Super_Hippo Super_Hippo

2017/3/8

#
Well, you don't have anything to check if it was the first touch or not.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//outside methods, on top
private Actor firstCrab = null;
 
//... lookforCrab
Actor a = getOneIntersectingObject(Crab.class);
if (a != null)
{
    if (firstCrab == null) firstCrab = a;
    else if (a != firstCrab)
    {
        getWorld().removeObject(a);
        Greenfoot.playSound("au.wav");
        Greenfoot.stop(); //why this?
    }
}
This does not eat the first crab because it is not tasty. If the first crab touches the lobster at a later point, the lobster still won't eat it because the crab doesn't get tasty after a while.
Mjosue Mjosue

2017/3/8

#
The stop part is to end the game. The professor wants that there.
Super_Hippo Super_Hippo

2017/3/8

#
Does the code work as it should?
Mjosue Mjosue

2017/3/8

#
Illtry it once i am home.
You need to login to post a reply.