I got a game where to players try to kill eachother with bombs. I decided to implement a Health Indicator called HealthGUI. Both players got their own one which get updated every frame to show the correct amount nof hearts/life left.
Heres the HealthGUI class:
public class HealthGUI extends Actor
{
private int life = 3;
GreenfootImage playerTwoThreeHeart = new GreenfootImage("PlayerTwoThreeHeart.png");
GreenfootImage playerTwoTwoHeart = new GreenfootImage("PlayerTwoTwoHeart.png");
GreenfootImage playerTwoOneHeart = new GreenfootImage("PlayerTwoOneHeart.png");
public int getLife() {
return this.life;
}
public void setLife(int life) {
this.life = life;
}
public void act(){
switch(3) {
case 3:
setImage(playerTwoThreeHeart);
case 2:
setImage(playerTwoTwoHeart);
case 1:
setImage(playerTwoOneHeart);
default:
System.out.println("Something went wrong...");
Greenfoot.stop();
}
/DEBUG
System.out.println(life);
}
While debugging i found out that somehow, even though switch(3) is 3 obviously, it returns a default case as if 3 wasnt listed as a case... So i get:
Something went wrong...
3
Something went wrong...
3
In my console (Two times due to two HealthGUIs)
Heres the relevant World Code:
public void prepare() {
HealthGUI healthGUIPlayerOne = new HealthGUI();
HealthGUI healthGUIPlayerTwo = new HealthGUI();
addObject(healthGUIPlayerOne, 100, 20);
addObject(healthGUIPlayerTwo, 700, 20);
Player playerOne = new Player("w", "a", "s", "d", "c", "v", PlayerTeam.ONE, healthGUIPlayerOne);
addObject(playerOne, 100, 300);
Player playerTwo = new Player("up", "left", "down", "right", "b", "n", PlayerTeam.TWO, healthGUIPlayerTwo);
addObject(playerTwo, 800, 300);
}
And finally the if statement that triggers decrementation of HealthGuis life attribute:
if(getOneIntersectingObject(Player.class) != summoner && getOneIntersectingObject(Player.class) != null) {
System.out.println("I should kill you now");
Player opponent = (Player)getOneIntersectingObject(Player.class);
summoner.activateBomb(playerBomb);
isBombInWorld = false;
HealthGUI opponentHealthGUI = opponent.getHealthGUI();
opponentHealthGUI.setLife(opponentHealthGUI.getLife()-1);
//bombWorld.removeObject(opponent);
}
I tried to change my code for 3 hours straight now and just cant get it to work.
I had life in Player before which always gave me NullPointerExceptions when starting the game.
Please help me if you have any suggestions!!! Really frustrated by this one!
Thank you!