I already implemented a health system for my ship in my game which is written in Java. The way the health works is this: everytime the ship takes a hit from the fire projectile, the health drops 1 heart.
The first issue is:
Although the code works, I feel the following code implementation does not seem to be efficient in a situation where the ship can start off with more than 3 hearts.
The way I created the effect of the heart disappearing is using if statements to set different images that displays a different numbers of hearts depending on the life of the ship. 2 Pictures of setting different images of heart display to a JLabel object is not so bad using 2 if statements...but if my ship had 20 hearts when the game starts, that would mean 20 if statements. The code will be painful to implement or worse to debug. It is also duplicated code as it is.
On a side note: The ShipLifeTitle is a JLabel that is attached to the BorderLayout.North of the JPanel.
Here are 3 ImageIcons that are set to a single JLabel for the game:
The second issue is:
The code is tied to a particular skill from a monster. But if for example, my game had 20 skills, I would be using the same heart animating code for all 20 skills which would means I will need to copy and paste 20 times for the hearts to animate properly. But if I were to change my game to have 20 hearts instead of 3 hearts, I would need to edit my heart animating code in all 20 classes...
I have two questions:
Can everyone suggest an efficient way or a common way to create a more efficient health system?
Should I insert the health animation code in a collision function of a enemy skill class?
public class OneEyeFireSkill extends Sprite {
public void checkShipCollision(ArrayList<GameComponent> gameObjects, ShipLifeTitle shipLifeTitle )
{
for(GameComponent component: gameObjects)
{
if(component instanceof Ship)
{
// if collision happens
if((rectangle.intersects(((Ship) component).getRectangle())))
{
((Ship) component).setLife(((Ship) component).getLife()-1);
if(((Ship) component).getLife() == 2)
{
shipLifeTitle.setTitleToTwoHearts();
}
if(((Ship) component).getLife() == 1)
{
shipLifeTitle.setTitleToOneHearts();
}
if(((Ship) component).getLife() == 0)
{
shipLifeTitle.setGameOverTitle();
((Ship) component).removeAtDeath();
}
Game.getInstance().remove(this);
}
}
}
}
public class ShipLifeTitle extends JLabel {
public ShipLifeTitle() throws IOException
{
ImageIcon threeHeartsIcon = new ImageIcon("src/Ship/shipLifeTitle3.png");
setIcon(threeHeartsIcon);
}
public void setTitleToTwoHearts()
{
ImageIcon twoHeartsIcon = new ImageIcon("src/Ship/shipLifeTitle2.png");
setIcon(twoHeartsIcon);
}
public void setTitleToOneHearts()
{
ImageIcon oneHeartIcon = new ImageIcon("src/Ship/shipLifeTitle1.png");
setIcon(oneHeartIcon);
}