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

2013/4/29

Crab energy

jennnnay24 jennnnay24

2013/4/29

#
There have been a few discussions about crab energy but I still have not been able to put anything together and figure it out for myself. I need to make the crab lose 1/20 of a worm (energy) with every move. This is what I have...
public class Crab extends Animal
{
    private GreenfootImage image1;
    private GreenfootImage image2;
    private int wormsEaten;
    private int targetWormsEaten;
    private int energyBurnRate;
    private int numberOfSteps;
    
    /**
     * Create a crab and initialize its two images.
     */
    public Crab()
    {
        image1 = new GreenfootImage("crab.png");
        image2 = new GreenfootImage("crab2.png");
        setImage(image1);
        wormsEaten = (Greenfoot.getRandomNumber (23)+5);
        targetWormsEaten = wormsEaten + 10;
    }
        
    /** 
     * 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()
    {
        randomTurn();
        move();
        lookForWorm();
        switchImage();
        turnAtEdge();
    }
    
    /**
     * Alternate the crab's image between image1 and image2.
     */
    public void switchImage()
    {
        if (getImage() == image1) 
        {
            setImage(image2);
        }
        else
        {
            setImage(image1);
        }
    }
    
    /**
     * Check whether we have stumbled upon a worm.
     * If we have, eat it. If not, do nothing. If we have
     * eaten eight worms, we win.
     */
    public void lookForWorm()
    {
        if (wormsEaten != targetWormsEaten && canSee(Worm.class))
        {
            eat(Worm.class);
            Greenfoot.playSound("slurp.wav");
            
            wormsEaten = wormsEaten + 1;
            if (wormsEaten == 8) 
            {
                return;
            }
            if (wormsEaten <= 0)  
            {  
            getWorld().removeObject(this);  
            return;  
            } 
        }
    }
    
    /**
     * 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);
        }
    }
    
        /**
     * Check whether we are at the edge of the world. If we are, turn a bit.
     * If not, do nothing.
     */
    public void turnAtEdge()
    {
        if ( atWorldEdge() ) 
        {
            turn(17);
        }
    }
      
}
You need to login to post a reply.