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

2016/6/17

Helicopter game need help displaying score under gameover

joseph.a joseph.a

2016/6/17

#
I have 2 worlds one set up for a daytime mode and one for night. I have made it so when the user loses the game the score moves under the gameover image and shows the user his score. This is how i did it
 private void showGameOver() {
        
        HelicopterWorld world = (HelicopterWorld)getWorld();
          world.addObject(new GameOver(), getWorld().getWidth()/2, getWorld().getHeight()/2);
      world.scoreObj.setLocation(getWorld().getWidth()/2, getWorld().getHeight()/2+50);
      
     
    }
But i try doing the same for DayTime world by replacing the HelicopterWorld to DayTime and it doesn't work the game runs in daytime mode and when i die this message appears java.lang.ClassCastException: DayTime cannot be cast to HelicopterWorld at Helicopter.showGameOver(Helicopter.java:58) at Helicopter.act(Helicopter.java:44) how can i fix help!
valdes valdes

2016/6/17

#
Your two worlds are independent, so you cannot cast one into the other. I imagine that showGameOver() is inside some Actor class. That actor will need to know inside what type of World is in, to do the proper cast
HelicopterWorld world = (HelicopterWorld)getWorld();
or 
DayTime world = (DayTime)getWorld();
The elegant solution will be to use inheritance. Create a new World:
public class MyWorld extends World
{
  // Declare only the scoreObj object
  // no methods or constructor
}
change both your worlds inheritance to
public class HelicopterWorld extends MyWorld

public class DayTime extends MyWorld
I imagine both worlds have the scoreObj object, delete the declaration on both of them. and finally in your showGameOver method
MyWorld world = (MyWorld)getWorld();
You need to login to post a reply.