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

2020/9/24

How to make a "death counter"

whoisKiwiKoala whoisKiwiKoala

2020/9/24

#
Ok so in my game I want to add a "death counter" which lists the amount of times a player dies. (The counter stays in at the top of your screen the whole game.) Dying means if specific worlds have been loaded for the player, which is caused by an enemy. I don't know how to do this because I am bad at coding please help thanks
danpost danpost

2020/9/24

#
You will need a static field. However, because of the scope applied to static fields (they do not reset upon resetting the scenario), you will need to be able to distinguish between worlds instances that start a game (initial ones) from those that do not (subsequent ones). The best way to accomplish that is by giving your worlds multiple constuctors -- a non-parameterized one for initial worlds and a parameterized one for subsequent worlds:
static Counter deathCounter;

/** constructs initial world */
public MyWorld()
{
    this(false); // redirects as if using 'new MyWorld(false)'
}

/** use 'new MyWorld(true)' to construct subsequent worlds */
public MyWorld(boolean again)
{
    super(600, 400, 1);
    if ( ! again) deathCounter = new Counter();
    // etc.
}
You could use a non-static field, but that would then require you pass, instead of the boolean, the Counter object itself or, at minimum, its value to the subsequent world constructor.
You need to login to post a reply.