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

2017/1/19

What is wrong with this script?

t_k_990 t_k_990

2017/1/19

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

/**
 * This class defines a crab. Crabs live on the beach.
 */
public class Crab extends Animal
{
    public int wormCount = 0;
    public void act()
    {
        keydown();
        lookForWorm();
        seckeydown();
        eatOtherPlayer();
        win();
    }
    public void lookForWorm()
    {
            if ( canSee(Worm.class) )
        {
            eat(Worm.class);
            getWorld().addObject (new Worm(), Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber(560));
            wormCount = wormCount + 1;
        }
        if (wormCount != 2)
        {
            getWorld().addObject (new two(), 10, 500);
        }
        if (wormCount != 3)
        {
            getWorld().addObject (new three(), 15, 500);
        }
    }
    public void win()
    {
        if (wormCount >= 8)
        {
            Greenfoot.playSound("fanfare.wav");
            getWorld().addObject (new CrabWin(), 500, 500);
            if (wormCount >= 8)
            {
                Greenfoot.stop();
            }
        }
    }
    public void keydown()
    {
        if (Greenfoot.isKeyDown("right") )
        {
            setLocation(getX()+10, getY());
        }
        if (Greenfoot.isKeyDown("left") )
        {
            setLocation(getX()-10, getY());
        }
    }
    public void seckeydown()
    {
        if (Greenfoot.isKeyDown("up") )
        {
            setLocation(getX(), getY()-10);
        }
        if (Greenfoot.isKeyDown("down") )
        {
            setLocation(getX(), getY()+10);
        }
    }
    public void randomturn()
    {
        Greenfoot.getRandomNumber(99);
        if(Greenfoot.getRandomNumber(99)<5);
        // 50% of the time it gonna turn + move
        turn(Greenfoot.getRandomNumber(99)-20);
    }
    public void eatOtherPlayer()
    {
        if (canSee(Camel.class) && Greenfoot.isKeyDown("shift") )
        {
            eat(Camel.class);
            Greenfoot.playSound("au.wav");
            Greenfoot.stop();
            Greenfoot.playSound("fanfare.wav");
            getWorld().addObject(new CrabWin(), 500, 500);
        }
    }
}


Super_Hippo Super_Hippo

2017/1/19

#
'!=' means 'not equal to'. So every time the 'lookForWorm' method is executed (which happens once each act cycle for each Crab in the active world), a 'two' and a 'three' are added to the world. Btw, the comment in line 72 is not true. Because of the semicolon at the end of line 71, line 73 is not affected by the condition at all.
danpost danpost

2017/1/19

#
Move line 24 down to line 32 so that you only add a 'two' or 'three' when the value of 'wormsEaten' changes.
You need to login to post a reply.