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

2014/4/21

Score Counter after enemy death

PaisleyAinsley PaisleyAinsley

2014/4/21

#
Hi! I'm working on a game for a beginner programming course and I'm struggling to end the game and have my score counter/end game screen pop up! All codes I've seen for this issue are useful when one enemy dies (before the removeObject code on the death method) but I have five enemies and obviously don't want the game to end until all five are killed. Here is my code: /** * If NegaDoge runs out of life, then he dies! */ private void die() { Greenfoot.playSound("au.wav"); getWorld().removeObject(this); if (NegaDoge.class == null) { DogeWorld dogeWorld = (DogeWorld) getWorld(); ScoreBoard scoreboard = new ScoreBoard(); getWorld().addObject (scoreboard, dogeWorld.getWidth()/2, dogeWorld.getHeight()/2); } }/ It compiles, but it doesn't work after I've killed all the enemies.
PaisleyAinsley PaisleyAinsley

2014/4/21

#
Just tested the code I have in the if statement, I inserted it inbetween "playSound" and "removeObject" as normally suggested and it does work! But like I said, I want the score board to appear after all five enemies are dead and my instinct was the make the if statement shown above and it doesn't work! :(
danpost danpost

2014/4/21

#
It does not work the way you want because you are asking the wrong question (you are not using the correct condition in the 'if' statement). The other problem I see is the use of 'getWorld' after 'removeObject(this)' which will return 'null'. The correct question is whether there are any NegaDoge objects in the World (instead of asking if the class does not exist; of course the class exists or you would not have had NegaDoge objects in your world to begin with). Use the world class method 'getObjects' to get a list of all NegaDoge objects in your world; then, use the List class method 'isEmpty' to determine if any are -- generally speaking:
if (getWorld().getObjects(NegaDoge.class).isEmpty())
However, this, again, uses 'getWorld' and it will return 'null' after using 'removeObject(this)'. So, we need to hold a reference to the world in a local variable before removing 'this' from the world. You are showing a line for that as the first line in the 'if' block, but that, too, is past the 'removeObject(this)' ( I am referring to this line: DogeWorld dogeWorld = (DogeWorld)getWorld();' ). Move this line up to before the 'removeObject(this)' line and change all occurrences of 'getWorld()' after it in the method to 'dogeWorld'.
PaisleyAinsley PaisleyAinsley

2014/4/21

#
This worked! Thank you so much for your help and explaining it in a way that helps me understand!
You need to login to post a reply.