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

2012/6/22

Looping enemy numbers

davemib123 davemib123

2012/6/22

#
Hi all, having an attempt at some programming with greenfoot, but come to a little problem. I am trying to get my code to add 3 enemies if 3 enemies are no longer present on the screen. I so far have this for the world:
public class City extends World
{
     /**
     * Constructor for objects of class City.
     * 
     */
    public City()
    {    
        super(700, 300, 1);
        populateCity();
        enemySwarm();
    }

    public void populateCity()
    {
        addObject(new Ship(), 100, 120);       
    }

    public void enemySwarm()
    {

        int count = 1;
        while (count < 4) {
            addObject(new enemyShip(), 800, Greenfoot.getRandomNumber(300));
            count++;
        }
    }
}
and this for the enemy:
public class enemyShip extends Enemies
{
private int velocity = 3;
private int outOfBoundary = 400;

    /**
     * Act - do whatever the enemyShip wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
   moveLeft();
                      if (getX() <= getWorld().getWidth() - (getWorld().getWidth() - outOfBoundary))
         {
             getWorld().removeObject(this);
        }
    }    
        
    public void moveLeft()
    {
        setLocation(getX() - velocity, getY());
    }
}
danpost danpost

2012/6/22

#
In your world class, change lines 19 through 27 (your 'enemySwarm' method) to this:
public void enemySwarm()
{
    while (getObjects(enemyShip.class).size < 3) addObject(new enemyShip(), 800, Greenfoot.getRandomNumber(300));
}
Also, line 13 in the enemyShip class code does not look right. I think you meant:
if (getX() <= outOfboundary))
davemib123 davemib123

2012/6/26

#
Great thanks for this :)
You need to login to post a reply.