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

2015/3/25

Help - life counter

Leenza Leenza

2015/3/25

#
This is my code so far. In the lives class
public class Lives extends Actor
{
    /**
     * Act - do whatever the Lives wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        // Static variable here from the Crab class.
        GreenfootImage textImage = new GreenfootImage("Lives - " + Hero.numLives, 24, new Color(50, 255, 100), new Color(0, 0, 0, 0));
        GreenfootImage image = new GreenfootImage(textImage.getWidth()+12, 36);
        image.setColor(new Color(196, 0, 0));
        image.fill();
        image.setColor(new Color(100, 0, 196));
        image.fillRect(3, 3, image.getWidth()-6, 30);
        image.drawImage(textImage, 6, 6);
        setImage(image);
    }    
}
In the Hero class:
/**
     * 
     */
    public void lookForEnemy()
    {
        if (canSee(Enemy.class))
        {
            // Take away a life and see if you're out
            numLives--;
            if (numLives == 0)
            {
                // Bring up the "Lose" world
                Greenfoot.setWorld(new Loser());
                Greenfoot.stop();
            }
            else
            {
                // Respawn in another spot
                setLocation(Greenfoot.getRandomNumber(getWorld().getWidth()), Greenfoot.getRandomNumber(getWorld().getHeight()));
            }
        }
     }
The problem I am having is if I press the reset button the number of lives does not go back to three (which is what I want). Instead it stays at the number that i had before. Does anyone know how to fix this?
Super_Hippo Super_Hippo

2015/3/25

#
For example in the Hero class, have this code:
public Hero()
{
    numLives = 3;
}
Static variables aren't recreated when resetting.
xWanna xWanna

2015/3/25

#
You have to read out the variable of the Hero class in the Lives class. Lives class: (Replace Welt with your world name
 World welt = (Welt) getWorld(); 
 int numLives2 = welt.getHero().numLives;
and you have to place the variable numLives as public in the hero class
public int Lives = 30;
And say this in your world:
public Hero hero = new Hero();

public Welt(){

getHero();
}

public Hero gethero() {
        return hero;
    }
Leenza Leenza

2015/3/25

#
Super_Hippo wrote...
For example in the Hero class, have this code:
public Hero()
{
    numLives = 3;
}
Thank you that helped a lot.
Super_Hippo wrote...
Static variables aren't recreated when resetting.
So do you mean it is impossible to make the variable go back to three when i press reset? (sorry if that is dumb question, but programming is still very new to me)
Super_Hippo Super_Hippo

2015/3/25

#
No, but it is not enough to have a line like 'private static int numLives = 3;'. You need the line I gave you above.
You need to login to post a reply.