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

2014/10/17

End game after certain objects are all gone?

user219 user219

2014/10/17

#
I am currently following along with Greenfoot Introduction to Programming using the little crab scenario, and one of my objectives is to end the game after my little crab dude has eaten all the worms. However, I made it so that new worms are added to the world whenever the crab touches the sides of the world. Therefore I cannot simply use an integer to tell the game to stop..? I have it set at 7 so if new worms are added to the world, the game still currently stops at 7. I have tried getWorld().numberofObjects but am unsure how to implement it. Thanks!
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)


/**
 * This class defines a crab. Crabs live on the beach!!!!! They
 * love worms, hate lobsters.
 */
public class Crab extends Animal


{
   private GreenfootImage image1;
   private GreenfootImage image2;
    private int wormsEaten;
   private int counter = 0;
    
    public Crab()
    {
        image1 = new GreenfootImage("crab.png");
        image2 = new GreenfootImage("crab2.png");
        setImage(image1);
        wormsEaten = 0;
    }
    

    public void act()
    {
        
      move();
      turnAtEdge();
      lookForWorm();
      randomTurn();
      checkKeypress();
      if(counter==3)
      {
          counter=0;
      switchImage();
      
    }
    counter++;
    }
    
    /**crab's walk cycle
       * 
       */ public void switchImage()
    {
    if ( getImage() == image1 )
    {
        setImage(image2);
    }
    else
    {
        setImage(image1);
    }

    }
    
    /**actions taken when crab eats worm.
     * 
     * 
     */public void lookForWorm()
     {
     if (canSee(Worm.class) )
        {
            eat(Worm.class);
            
            wormsEaten = wormsEaten + 1;
            if (wormsEaten == 7)
            {
            Greenfoot.playSound("fanfare.wav");
            Greenfoot.stop();[/b]
        }


       }

    }
Super_Hippo Super_Hippo

2014/10/17

#
if (getWorld().getObjects(Worm.class).isEmpty())
{
   Greenfoot.playSound("fanfare.wav");  
   Greenfoot.stop();
}
'getObjects(Class cls)' is a world method which returns a list of all actors of the given class (or null which returns all actors in the world). 'isEmpty()' checks whether or not the list is empty (=no worm is in the world).
You need to login to post a reply.