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

2014/1/21

How to write a line of code

JasonZhu JasonZhu

2014/1/21

#
I have 3 different worlds named: Maze1 Maze2 Maze3 How would I write a line of code in an if statement that checks whether the currently set world is Maze1? I need to use this for an object that changes the world to the next and I though by learning this, it would beat the excessive code of make 3 different same objects when one object can accomplish this.
JasonZhu JasonZhu

2014/1/21

#
I tried this, but I get a casting error:
        if((Maze1)getWorld()!=null&&getOneIntersectingObject(Player.class)!=null){
            Greenfoot.setWorld(new Maze2());
        }else
        if((Maze2)getWorld()!=null&&getOneIntersectingObject(Player.class)!=null){
            Greenfoot.setWorld(new Maze3());
        }else
        if((Maze3)getWorld()!=null&&getOneIntersectingObject(Player.class)!=null){
            Greenfoot.setWorld(new GameOver());
        }              
    }   
JasonZhu JasonZhu

2014/1/21

#
I tested a single line:
if((Maze1)getWorld()!=null&&getOneIntersectingObject(Player.class)!=null){  
   Greenfoot.setWorld(new Maze2());  
}
It works, but if I have the other else if statements in there, I get a casting error, is there a way to avoid this without having to make multiple same objects?
davmac davmac

2014/1/21

#
World world = getWorld();
if (world instanceof Maze1) {
   Greenfoot.setWorld(new Maze2());
}
else if (world instanceof Maze2) {
   Greenfoot.setWorld(new Maze3());
}
// etc
JasonZhu JasonZhu

2014/1/21

#
Oh! "instanceof", I forgot to try that. Thanks for your reply!
JasonZhu JasonZhu

2014/1/21

#
Oh! This works to keep the game continually running after the world is set. I was going to ask how to do keep the scenario running after the world is set because how I was previously setting the world, it failed to run the scenario after it set the world.
You need to login to post a reply.