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

2012/5/17

How do you detect whether certain actors are gone

kartikitrak kartikitrak

2012/5/17

#
Hello. I am fairly new to Greenfoot and I have encountered a problem. I am trying to make a small game similiar to space invaders and I would like to know when all the enemies are dead so I can change the level. I know there is a numberOfObjects method but I'm not sure if that would work when determining if there is just the user's ship or just 1 enemy ship left. Simply put, how do you determine when you have all the enemy actors dead and just the player actor is alive Thanks : D
trash1000 trash1000

2012/5/17

#
Do you mean 'dead' like in 'removed from world'? Then I'd say somerhing like this should do it:
public void areThereEnemies() {
    return getObjects(Enemy.class) == null;
}
danpost danpost

2012/5/17

#
The World class method 'getObjects(Class cls)' will return a list of all the objects of the class specified; and there is a List method called 'isEmpty()' that will return a boolean (true/false) value. Ergo,
if (getObjects(Enemy.class).isEmpty()) {
    // no enemies are left in the world
    // do what you have to do, here
}
I am assuming 'Enemy' is the name of the class.
trash1000 trash1000

2012/5/17

#
Forget my first post it's full of mistakes. it's basically the same as danpost suggested but just for correctioj purposes:
public boolean areThereEnemies() {
    return getObjects(Enemy.class).isEmpty();
}
danpost danpost

2012/5/17

#
@trash1000, you will return the opposite of what you want with that code. You would need to change to value returned with a '!', OR (better yet) change the name of the method to 'areEnemiesGone()'.
kartikitrak kartikitrak

2012/5/17

#
Thanks so much! It worked perfectly : D
You need to login to post a reply.