Hello, I am using Little-Crab4 and trying to complete Exercise 4.27 in the book. Right now I have my crab image switch each cycle, but I need to change it to every 2 or 3 cycles. So I will have to add a counter and a if statement, but I am completely lost. Here is the question from the book:
The crab image changes fairly quickly while the crab runs, which makes our little crab look a little hyperactive. Maybe it would look nicer if the crab image changed on every second or third act cycle. Try to implement this. To do this, you could add a counter that is incremented in the act method. Every time it reaches two (or Three), the image changes and the counter is reset to zero.
Thank you for your help. Also, here is the code I currently have:
/**
* This class defines a crab. Crabs live on the beach. They like sand worms
* (very yummy, especially the green ones).
*
* Version: 4
*
* The crab is keyboard controlled and eats worms. In this version, we have added
* a sound when the crab eats a worm.
*/
public class Crab extends Actor
{
private GreenfootImage image1;
private GreenfootImage image2;
public Crab()
{
//constructor only done once in life of crab
image1 = new GreenfootImage("crab.png");
image2 = new GreenfootImage("crab2.png");
setImage(image1);
}
/**
* Act - do whatever the crab wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
checkKeypress();
move(5);
switchImage();
lookForWorm();
if ( isAtEdge() )
{
turn(180);
}
}
public void switchImage()
{
GreenfootImage tempImage;
tempImage = getImage();
if ( tempImage == image1 )
setImage(image2);
else
setImage(image1);
}
/**
* Check whether a control key on the keyboard has been pressed.
* If it has, react accordingly.
*/
public void checkKeypress()
{
if (Greenfoot.isKeyDown("left"))
{
turn(-4);
}
if (Greenfoot.isKeyDown("right"))
{
turn(4);
}
}
/**
* Check whether we have stumbled upon a worm.
* If we have, eat it. If not, do nothing.
*/
public void lookForWorm()
{
if ( isTouching(Worm.class) )
{
removeTouching(Worm.class);
Greenfoot.playSound("slurp.wav");
}
}
}
