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

2018/3/17

Removing hearts from an health bar

Kestroz Kestroz

2018/3/17

#
Hi, I've recently been making a game and im creating a health bar for the enemy boss, that is composed of 20 hearts. However, I have no idea on how to remove these hearts 1 by 1, as one attack only does 1 heart of damage. I've made the hearts in my world class with a for loop. If anyone could help that'd be great How I've made the hearts: for(int i = 1; i<11; i++) { BossHealth heart = new BossHealth(); addObject(heart, 455 + (i * 50), 55); } for(int i = 1; i<11; i++) { BossHealth heart2 = new BossHealth(); addObject(heart2, 455 + (i * 50), 100); }
Super_Hippo Super_Hippo

2018/3/17

#
You need to keep a reference to the health objects. You could create the hearts from the boss object and save them in an array. Then you can always remove the last heart.
Game/maniac Game/maniac

2018/3/17

#
Continuing from Super_Hippo's solution you could use a stack instead of an array for easier management. I would also recommend encapsulating the hearts inside a class. Here is an example:
import greenfoot.World;
import java.util.Stack;

public class HealthBar
{
    private Stack<Heart> hearts;
    
    private int x;
    private int y;
    
    private int spacing;
    private int rowLength;
    
    private World world;
    
    public HealthBar(int x, int y, World world) {
        this(x, y, 20, 50, 10, world);
    }
    
    public HealthBar(int x, int y, int numHearts, int spacing, int rowLength, World world) {
        this.x = x;
        this.y = y;
        this.spacing = spacing;
        this.rowLength = rowLength;
        this.world = world;
        
        hearts = new Stack<Heart>();
        
        for (int i = 0; i < numHearts; i++) addHeart();
    }
    
    public void addHeart() {
        Heart heart = new Heart();
        int i = hearts.size();
        hearts.add(heart);
        int column = i % rowLength;
        int row = i / rowLength;
        world.addObject(heart, x + column * spacing, y + row * spacing);
    }
    
    public void removeHeart() {
        Heart heart = hearts.pop();
        world.removeObject(heart);
    }
    
    public Heart[] getHearts() {
        return hearts.toArray(new Heart[hearts.size()]);
    }
}
You need to login to post a reply.