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

2014/1/5

How to check if all instances of a class have been removed

Euan Euan

2014/1/5

#
Hey, I've been working on game for a computer science class and I've figured out most of my game apart from the issue of my victory condition not being able to work. I have four classes which are concerned here: Player, Bandit, Bullet and Character. All of which are sub-classes of Character (apart from Character of course). This is the way in which I had been trying to work the victory condition: WITHIN CHARACTER:
public int banditsKilled = 0;
    public void act()
    {
        checkForWin();
    }

 public void checkForWin()
    {
        if (banditsKilled == 16)
        {
            banditsKilled = 0;
      //Artic is just another subclass of world that I'm switching to for the second level, but it's not that important.
            Greenfoot.setWorld(new Artic());
        }
    }
    
    public void addToBanditsKilled()
    {
        banditsKilled++;
    }
WITHIN BANDIT (The bullet doesn't kill the bandit, it is the bandit that removes the bullet and then itself, therefore there is no code within bullet apart from the code that removes it at world edge)
 public void act()
    {   
        move(5);
        worldEdgeTurn();
        checkForBullet();
    }

public void checkForBullet()
    {
        if(canSee(Bullet.class))
        {
            addToBanditsKilled();
            kill(Bullet.class);
            randomCrateDrop();
            getWorld().removeObject(this);
        }
    } 
The bullet is spawned by the player, but there is no code within Player that relates to any of this, but it is what the player plays as. The amount of each class within the world: BANDIT = 16 PLAYER = 1 CHARACTER = 1 BULLET = INFINITE AMOUNT Any help would be greatly appreciated as the game is pretty much finished apart from the victory condition. Euan.
Gevater_Tod4711 Gevater_Tod4711

2014/1/5

#
The problem is that the method addToBanditsKilled in line 12 of your Bandit class counts up the value of the variable banditsKilled in the Bandit object but not in the Character object. So in every killed Bandit object the value is one and in your character it's always null. The easiest way would be to not count the killed Bandits but check whether there are no more Bandits in the world in line 9 of your Character class. To check this you can use this code:
if (getWorld().getObjects(Bandit.class).isEmpty()) {  

    //all Bandits have been killed;

    //Artic is just another subclass of world that I'm switching to for the second level, but it's not that important.  
    Greenfoot.setWorld(new Artic());
}  
Euan Euan

2014/1/5

#
Thanks a million, I added it and it worked a charm, thanks for the quick and helpful reply
You need to login to post a reply.