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

2024/3/17

Help for score variable to be accessed across worlds and actors

yipyip yipyip

2024/3/17

#
I have a score variable in my GameWorld which works, but I need it to also be accessed by the EndWorld which should show the final score.
public class GameWorld extends World
{
    public int score = 0;
    public GameWorld()
    { 
        super(600, 400, 1);
        setBackground("sandstone.jpg");
        thing t1 = new thing();
        frog f1 = new frog();
        spider s1 = new spider();
        addObject(t1, 80, 80);
        int y = Greenfoot.getRandomNumber(getHeight());
        int ys = Greenfoot.getRandomNumber(getHeight());
        addObject(f1, 610, y);
        addObject(s1, 610, ys);
        showScore();
        score++;
    }
    public void act(){
        count();
    }
    public void count(){
       score = score + 1;
       showScore();
    }
    public void showScore()
    {
        showText("Score: " + score, 50, 25);
    }
}
What can I do to my EndWorld to have it access that final score? I need to display is as text. Also would it be possible to have my actors access the score value while its increasing? Please help.
danpost danpost

2024/3/19

#
yipyip wrote...
What can I do to my EndWorld to have it access that final score? I need to display is as text. Also would it be possible to have my actors access the score value while its increasing?
Any active actor in a GameWorld instance has access to that world simply by using the following:
GameWorld gw = (GameWorld)getWorld();
Then, the score of the game is acquired by what follows the equal sign in the following code line:
int gameScore = gw.score;
You can display that value in the EndWorld world when you create that world (from within an actor).
You need to login to post a reply.