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

2014/10/23

Variables Reset Glitch

BlackBench BlackBench

2014/10/23

#
I have this game called Falling Rocks, and I'm having issues with lives. As far as I can tell, the variables are resetting, even though I didn't tell them to. I have it set up so that three new rocks are generated if you miss one on the bottom. I also want to make it so you can only miss three, but it doesn't work. When I have it so you only have one life, it works great, but any greater than that don't do anything. I know for sure L resets, even though I don't do anything about that. Below is my code, to see if you guys can see any issues with it.
public class Rock extends Actor
{
    public int L = 0;
    public int N = 0;
    public void act() 
    {
        if(Greenfoot.getRandomNumber(100) < 90){
            setLocation(getX(), getY()+1);
        }
        if (isAtEdge())  
        {  
            getWorld().addObject(new Rock(), (Greenfoot.getRandomNumber(490)), 40);
            getWorld().addObject(new Rock(), (Greenfoot.getRandomNumber(490)), 40);
            getWorld().addObject(new Rock(), (Greenfoot.getRandomNumber(490)), 40);
            L++;
            N++;
        }
        else{
            return;
        }
        if(L == 1){
            getWorld().removeObject(this);
        }
        if (N == 3){
            Greenfoot.stop();
        }
    }
}
danpost danpost

2014/10/23

#
Every time you create a new Rock object, it, the new Rock object, receives its own 'L' and 'N' fields for its use. If you want all Rock objects to share the same 'L' and 'N' fields, they you need to declare them as static fields:
public static int L, N;
Their default initial values will be zero; however, because the values of static fields are retained during resetting of the project, you should explicitly set them to zero in the constructor of your subclass of World, using:
Rock.L = 0;
Rock.N = 0;
You need to login to post a reply.