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

2018/8/23

Trying to spawn 2 enemies when one is is killed

adao3 adao3

2018/8/23

#
hey guys, I have been trying to get the world to spawn 2 enemies when one is killed, my code states that there are no error but it somehow doesnt work.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class MyWorld extends World
{

   
    public MyWorld()
    {    
   
        super(1000, 600, 1); 
        prepare();
    }
    public void act()
    {
        int max = 5;        
    
        int randomwidth = Greenfoot.getRandomNumber(200);
       int randomheight = Greenfoot.getRandomNumber(500);
       
       if (getObjects(Enemy.class).size()<max)
 {
  addObject(new Enemy(),randomwidth,randomheight);    
    }
    if (getObjects(Enemy.class).size()<max-1){
        max++;
    }
}


   /**
     * Prepare the world for the start of the program.
     * That is: create the initial objects and add them to the world.
     */
    private void prepare()
    {
        player player = new player();
        addObject(player,469,241);
        player.setLocation(936,566);
        player.setLocation(943,919);
        player.setLocation(479,273);
    }
}
any solutions?
danpost danpost

2018/8/24

#
One major problem is that max is a new variable every act cycle and is always initially set to 5. Another issue with the current code is that as long as the number of Enemy object in the world is less than max, max will increase and always stay greater than the number of Enemy objects in the world. You can either add two Enemy object into the world at the same time or introduce a target field. However, maybe the best way is to override the removeObject method:
public void removeObject(Actor object)
{
    super.removeObject(object);
    if (object instanceof Enemy) max++;
}
Then, all you would need is lines 17 through 22 in your act method with line 15 moved outside the method so it is not recreated every act step.
You need to login to post a reply.