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

2017/12/19

Multiple Lives

massivassl massivassl

2017/12/19

#
Hi. So i'm having this poblem implementing a multiple lives system into the game i'm making.
private int troopcounter = 5;
public void die()
    {
            if (canSee (Player2Bullet.class))
            {
                eat (Player2Bullet.class);
                Greenfoot.playSound ("wilhelm.wav");//plays whilhelm scream on death
            
            
                getWorld().addObject (new DeadSoviet(), getX(), getY()+20);//adds a new actor with image of a dead Soviet soldier
            
            
                getWorld().addObject (new Player1(), 55, 230);//adds new soldier to the game
                getWorld().removeObject(this);//removes old character from the game
                troopcounter--; //decreases number of troops available by one
                if (troopcounter == 0)//enemy side wins if all available troops are dead
                {
                    Greenfoot.setWorld(new AxisWin()); 
                }
            }
       
        
            else if (canSee (Grenade2.class))
            {
            
                getWorld().addObject (new DeadSoviet(), getX(), getY()+20);
             
                Greenfoot.playSound ("wilhelm.wav");
          
                getWorld().addObject (new Player1(), 55, 230);
                getWorld().removeObject(this);
                troopcounter--;
                if (troopcounter == 0)
                {
                    Greenfoot.setWorld(new AxisWin()); 
                }
            }
    }
Right now, if tested, the game spawns infinite amounts of soviet soldiers, and the troopcounter variable doesn't seem to be updating, when there should only be 5 soviet soldiers available for spawning
danpost danpost

2017/12/19

#
The troopcounter field goes bye-bye with the soldier when it dies (each soldier is given its own troopcounter field to work with).
massivassl massivassl

2017/12/19

#
danpost wrote...
The troopcounter field goes bye-bye with the soldier when it dies (each soldier is given its own troopcounter field to work with).
i see, so hwo would i make make it such that all soldiers share the same counter?
danpost danpost

2017/12/19

#
massivassl wrote...
so how would i make make it such that all soldiers share the same counter?
One way is to make the field 'static'. But you must ensure that you zero the field in your initial world constructor or the value will carry over from game to game. However, if all soldiers are removed from the world when they die, you do not have to keep track of how many are still in the world. You can simply use the following in your World subclass act method:
if (getObjects(SovietSoldier.class).isEmpty()) Greenfoot.setWorld(new AxisWin());
You need to login to post a reply.