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

2013/4/29

Stopping the game..

jennnnay24 jennnnay24

2013/4/29

#
I need to figure out how to stop the entire game when the Worms, Crabs, or Lobsters number, or population, equals zero. This is what I have now, but it's not working.
public CrabWorld() 
    {
        super(560, 560, 1);
        populateWorld();
        act();
        
    }

    
    /**
     * Create the objects for the start of the game.
     */
    
    public void populateWorld()
    {
    
        int i = 0;
        
        for (i=0; i<5; i++)
            addObject (new Crab(), Greenfoot.getRandomNumber (561), Greenfoot.getRandomNumber (561)); 
            // Hartley - this code randomly adds 5 crabs each time the world is reset. This code satifies R1
            
        for (i=0; i<2; i++)
            addObject (new Lobster(), Greenfoot.getRandomNumber (561), Greenfoot.getRandomNumber (561)); 
            // Hartley - this code randomly adds 2 lobster each time the world is reset. This code satifies R2
            
        for (i=0; i<50; i++)
            addObject (new Worm(), Greenfoot.getRandomNumber (561), Greenfoot.getRandomNumber (561)); 
            // Hartley - this code randomly adds 50 worms each time the world is reset. This code satifies R3
    }
    
    /**
     * Stop the game once all the Worms, or Crabs, or Lobsters’ numbers (population) reaches zero.
     */
    public void act()
    {
        if (getObjects(Worm.class) == null || getObjects(Crab.class) == null || getObjects(Lobster.class) == null) 
        Greenfoot.stop();
    }    
}
davmac davmac

2013/4/29

#
The getObjects(...) method doesn't return null, ever. If there are no objects of the requested type, it returns an empty list. You can check whether a list of empty using the 'isEmpty()' method:
if (getObjects(Worm.class).isEmpty() || getObjects(Crab.class).isEmpty() || getObjects(Lobster.class).isEmpty())   
        Greenfoot.stop(); 
jennnnay24 jennnnay24

2013/4/29

#
Yes, that worked! Thank you soo much. I'm still trying to learn all of this...
You need to login to post a reply.