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

2025/7/11

I want use a variable in multiple actors

Afternoon Afternoon

2025/7/11

#
I tried to make the lives variable in the world and have the actors access it from there but it doesn't work. This is my code in the World.
public class Sea extends World
{
    public Sea()
    {    
        
        super(1350, 700, 1); 
        addObject(new Player(), getWidth()/2, getHeight()/2);
        for(int count=1; count<=10; count=count+1)
        {
            addObject(new Fish(), Greenfoot.getRandomNumber(getWidth()), Greenfoot.getRandomNumber(getHeight()));
        }
        int life = 3;
        addObject(new Life1(), getWidth()/50,getHeight()*25/26);
        addObject(new Life2(), getWidth()/50+55,getHeight()*25/26);
        addObject(new Life3(), getWidth()/50+110,getHeight()*25/26);
    }
}
and this is my code in the actor
public class Life3 extends Actor
{
    int life =  ((Sea) getWorld()).life;
    public void act()
    {
        
    }
}
My goal is to have three heart actors disappear as life decreases and a player actor that decreases life when they get hit. Can someone please help?
danpost danpost

2025/7/11

#
Afternoon wrote...
I tried to make the lives variable in the world and have the actors access it from there but it doesn't work. This is my code in the World. << Code Omitted >> My goal is to have three heart actors disappear as life decreases and a player actor that decreases life when they get hit. Can someone please help?
Instead of three different Life# actors, try just one displaying the correct number of lives. You could start with the following:
import greenfoot.*;

public class Lives extends Actor
{
    int maxLives;
    int lives;
    GreenfootImage heart;
    
    public Lives(int howMany) {
        maxLives = howMany;
        lives = maxLives;
        heart = getImage();
        updateImage();
    }
    
    private void updateImage() {
        GreenfootImage image = new GreenfootImage(55*heart.getWidth(), heart.getHeight());
        for (int i=0; i<lives; i++) image.drawImage(heart, i*55, 0);
        setImage(image);
    }

    public void adjustLives(int change) {
        lives += change;
        if (lives > maxLives) lives = maxLives;
        else if (lives < 0) lives = 0;
        updateImage();
    }
    
    public int getLives() {
        return lives;
    }
}
With this, you can keep a reference to the single Lives object in your Sea class:
// field
Lives lives = new Lives(3);

// in constructor
addObject(lives, getWidth()/2+80, getHeight()*25/26);

// in act
if (lives.getLives() == 0) {
    // any finalizing codes (possibles: remove main actor, display a game over message, etc.)
    Greenfoot.stop();
}
You need to login to post a reply.