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

2015/10/2

HOW DO I MAKE THE LOBSTERS EAT EVERY OTHER CRAB THEY FIND!!! PLEASE HELP

Mack Mack

2015/10/2

#
I'M USING "LITTLE-CRAB 5 SCENARIO" AND THIS IS THE CODE THE LOBSTER ALREADY HAS. 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(); } } }
danpost danpost

2015/10/2

#
You want your lobster to eat, basically, the second crab touched each time. You cannot simply count when a crab is touched, because the first crab touched will probably be still touched on the following act cycle. You really need to track the changes in touching or not touching a crab. The third change will be the second time a crab is touched (after a period of not touching a crab). So, at least one int field is needed to count the changes in this state (incremented any time the actor goes from not touching to touching and from touching to not touching). An Actor field could also be added to hold the first crab touched (only if that crab is not allowed to be eaten by touching, un-touching and touching again)
Mack Mack

2015/10/2

#
Can you show me what that would look like please?
danpost danpost

2015/10/2

#
Mack wrote...
Can you show me what that would look like please?
It would be something like this:
// instance field
private int touchCounter;

// the 'lookForCrab' method
public void lookForCrab()
{
    // check for change in touching state
    if (isTouching(Crab.class) == (touchCounter % 2 == 0))
    {
        // track state
        touchCounter = (touchCounter+1) % 4;
        // check for second touch
        if (touchCounter == 3)
        {
            removeTouching(Crab.class);
            Greenfoot.playSound("au.wav");
        }
    }
}
Mack Mack

2015/10/2

#
THANK YOU SOOOOOOO MUCH!!! YOU ROCK!!!!! :))
You need to login to post a reply.