Return to Snippet

Revision: 39603
at January 19, 2011 02:02 by joswald


Initial Code
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)

/**
 * This class defines a crab. Crabs live on the beach.
 */
public class Crab extends Animal
{
    private final int MAX_TURN_DEGREES = 25;    
    private final int ANIMATION_FRAMES = 2;
    private int animationCounter = 0;
    private GreenfootImage[] images;
    
    public Crab()
    {
        images = new GreenfootImage[ANIMATION_FRAMES];
        
        for( int i = 1; i <= ANIMATION_FRAMES; i++ )
        {
            images[i-1] = new GreenfootImage( "crab" + i + ".png" );
        }
        setImage( images[animationCounter] );
        animationCounter++;
    }
    
    public void animate()
    {
        animationCounter = animationCounter % ANIMATION_FRAMES;
        setImage( images[animationCounter] );
        animationCounter++;
    }
    
    public void turnAtEdge()
    {
        if( atWorldEdge() )
        {
            turn(17);
        }
    }
    
    public void randomTurn()
    {
        if( Greenfoot.getRandomNumber(100) < 15 )
        {
            int directionToTurn = Greenfoot.getRandomNumber(3) - 1; // left, right, or no turn
            turn( directionToTurn * Greenfoot.getRandomNumber(MAX_TURN_DEGREES) );
        }
    }
    
    public void lookForWorm()
    {
        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 act()
    {
        checkKeyPress();
        move();
        animate();
        lookForWorm();
    }
}

Initial URL


Initial Description
I had a subtle mistake in my code that was causing the exception. The corrected source code is below:

Initial Title
Crab Scenario Animation

Initial Tags
java

Initial Language
Java