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

2023/1/27

How to reset a World while the Program is running?

Bankspeers Bankspeers

2023/1/27

#
How to reset a World while the Program is running? In my Game I want to give the user the option to reset the Level with just the press of the R button.
Super_Hippo Super_Hippo

2023/1/27

#
Greenfoot.setWorld(new MyWorld()); //with MyWorld being the class of the world you want to restart
Bankspeers Bankspeers

2023/1/27

#
I have tried it but it doesn't work, because it can't detect the world in which I am in and that set the world to the world in which I was before. If i do this it changes the world to one single world everytime. But the thing that I want is, that when you are in whatever world 3 or so and you than press the R key that you would get the world 3 and that when you are in world 5 you get world 5 and not the world that is pre set.
Super_Hippo Super_Hippo

2023/1/28

#
You would place the code in the world’s act method so it should be straight forward how to detect in which world you are and change the ‘new MyWorld()’ to part to whatever you need. Please show your code if you are still having trouble.
danpost danpost

2023/1/28

#
With different levels, you might need to do something like the following:
// in superclass of the levels
public void act()
{
    String key = Greenfoot.getKey();
    if ("r".equals(key) || "R".equals(key)
    {
        resetWorld();
    }
    // other key detection codes here, if any
}

// to be overridden in each level subclass
protected void resetWorld() {}
To override the method resetWorld, in each level subclass, use code similar to the following:
// in Level1 world, for example
protected void resetWorld()
{
    Greenfoot.setWorld(new Level1());
}
To give a way to reset the entire game, you could modify the empty resetWorld method in the superclass (line 13 above) as follows:
protected void resetWorld()
{
    Greenfoot.setWorld(new MyWorld());
}
You can then call this method directly from this superclass, or you can use:
super.resetWorld();
from any level subclass to reset the game.
Bankspeers Bankspeers

2023/1/28

#
Thank you, now it works
You need to login to post a reply.