I am writing a code for a text-based adventure (Java), it's called the World of Zuul, in school, and I have to implement a health state for the player. I made an interface class:
public interface PlayerState {
public void heal();
public void injure(int damage);
public String getState();
}
I also made three classes:
public class ImmobileState implements PlayerState{
public void ImmobileState(){}
public void heal(){
System.out.println("Player is now healthy");
Player.setState(new HealthyState());
};
public void injure(int damage){
System.out.println("You was already immobile, so nothing happened?");
Player.setState();
};
public String getState(){return "Immobile";};
}
public class InjuredState implements PlayerState{
public void InjuredState(){}
public void heal(){
System.out.println("You are now healthy");
Player.setState(new HealthyState());
}
public void injure(int damage) {
if (damage == 0) {
System.out.println("Nothing happened...");
Player.setState(new HealthyState());
} else {
System.out.println("You are now immobile");
Player.setState(new ImmobileState());
}
}
public String getState(){return "Injured";}
}
public class HealthyState implements PlayerState{
public void HealthyState(){}
public void heal(){};
public void injure(int damage){
if(damage <= 10 && damage > 0) {
System.out.println("You are now injured");
Player.setState(new InjuredState());
}else if(damage == 0){
System.out.println("Nothing happened...");
Player.setState(new HealthyState());
}
else {
System.out.println("You are now immobile");
Player.setState(new ImmobileState());
}
};
public String getState(){return "Healthy";};
}
the problem here is the setState method in the Player-class:
public class Player {
private PlayerState state;
public Player(){
}
public void setState(PlayerState state) {
this.state = state;
}
public void heal(){
state.heal();
}
public void injure(int damage){
state.injure(damage);
}
public String showStatus(){
StringBuilder longStatus = new StringBuilder("> Status of the Player");
longStatus.append("\nhealtj state: "+ state.getState());
String fullStatus = longStatus.toString();
return fullStatus;
}
}
This is not the full player code, but the important parts. If i try the code, there comes this error:
Non-static method 'setState(model.states.PlayerState)' cannot be referenced from a static context
It comes three times, once for every state.
I hope this wasn't too much or to less to explain my problem. Hopefully someone can help me.
ChatGpt suggested me to do that:
public Player(){
Player player = new Player();
player.setState(new PlayerState);
}
This makes no sense because I declare the Player object already in my Game-class.