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

2020/4/13

Calling variable between worlds

jay4221 jay4221

2020/4/13

#
The game I have is designed to have a player move around avoiding obstacles until the time runs out or they hit something. When the game ends, the game switches to a different world and displays a message. If they lose, I want to display how much time they had left but when I call my "time" variable it shows 60(sec) which is the start time. Here's the code for my object when it hits an obstacle
public void hit()
    {
        if (isTouching(Barrel.class) || isTouching(RandomCar.class)){
            gameWorld ref = new gameWorld(); // create variable that holds value of other gameWorld
            Greenfoot.setWorld(ref);
            ref.result = false;
            System.out.println(ref.time);
            Greenfoot.setWorld(new endScreen(ref.result,ref.time));
        }
    }
and here is the code from my game world that changes the time (time variable is initiated at the beginning of my code which isn't in this section) :
public int timeCheck()
    {
        if (time > 199){
            time--;
            showText("Time left: " + time/100 , 300, 40);
            result = false;
        } else {
            result = true;
            Greenfoot.setWorld(new endScreen(result, time));
        }
        return time;
    }
and here is the code for my end screen:
public class endScreen extends World
{
    boolean endResult;
    int timeLeft;
    /**
     * Constructor for objects of class endScreen.
     * 
     */
    public endScreen(boolean result, int time)
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(600, 400, 1); 
        setBackground("endBackground.jpg");
        endResult = result;
        timeLeft = time/100;
        message();
    }
    
    public void message()
    {
        showText("Game Over",300, 200);
        // change message depending on whether they won or not
        if (endResult == true){
            showText("You Won!", 300, 230);
        } else {
            showText("You lost, try again", 300, 230);
            // reference variable to time left in game  
            showText("You had " + timeLeft + " seconds left",300, 250);
        }
    }
    
}
If there is any other code needed just let me know and i'll post it.
danpost danpost

2020/4/13

#
You need to replace lines 4 thru 7 in your hit method with code getting a reference to the currently active world -- not to a new game world that is in its initial state of not being played yet. Use:
gameWorld ref = (gameWorld)getWorld();
followed by your line 8.
jay4221 jay4221

2020/4/13

#
oh thank you so much, that makes a lot more sense and fixed my code.
You need to login to post a reply.