I recently started with the Greenfoot book.
I followed every step and followed every task but somehow I just can't get the crab image switching.
I looked it up in crab scenario-5 which is a working example of how it should be.
As far as I can see The code match so I don't understand why mine doesn't switch.
Here my code:
public class Crab extends Animal
{
private GreenfootImage image1;
private GreenfootImage image2;
public Crab()
{
image1 = new GreenfootImage("crab.png");
image2 = new GreenfootImage("crab2.png");
setImage(image1);
}
public void act()
{
checkKeyPress();
move();
canSeeWorm();
switchImage();
}
public void canSeeWorm()
{
if (canSee(Worm.class))
{
eat(Worm.class);
Greenfoot.playSound("slurp.wav");
}
}
public void checkKeyPress()
{
if (Greenfoot.isKeyDown("left"))
{
turn(-4);
}
if (Greenfoot.isKeyDown("right"))
{
turn(4);
}
}
public void turnAtEdge()
{
if (atWorldEdge())
{
turn(4);
}
}
public void switchImage()
{
if (getImage() == image1)
{
setImage(image2);
}
else
{
setImage(image1);
}
}
}
==================================================================================================================
Here the code of the example:
public class Crab extends Animal
{
private GreenfootImage image1;
private GreenfootImage image2;
private int wormsEaten;
/**
* Create a crab and initialize its two images.
*/
public Crab()
{
image1 = new GreenfootImage("crab.png");
image2 = new GreenfootImage("crab2.png");
setImage(image1);
wormsEaten = 0;
}
/**
* 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();
lookForWorm();
switchImage();
}
/**
* Alternate the crab's image between image1 and image2.
*/
public void switchImage()
{
if (getImage() == 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);
}
}

