Apocabal
Apocabal

Reputation: 147

Attribute dependencies between two classes

I want to code a little text adventure/dungeon crawler type of game. At the moment I have the classes Creature, Player, and Enemy. The classes Player and Enemy are subclasses of Creature.

I want to make the level of the enemy dependent on the level of the player. So for example, the enemy's level should always be 1 level above the player's level. So when the player is level 4 you should only be able to face enemies which are level 5.

My idea was to put something like this in the constructor of the Enemy class:

 public Enemy(String name, int hp, int atk, int exp) {
    super(name, Player.getLevel + 1, hp, atk);
    this.exp = exp;
 }

But that is clearly not allowed. Now I have no idea how to achieve this result. I lack some basic understanding of Java, but I'm willing to learn.

My code looks like this at the moment. I left the getters and setters out for better readability.

public class Creature {

   private String name;
   private int    level;
   private int    hp;
   private int    atk;

   public Creature (String name, int level, int hp, int atk){
      this.name = name;
      this.level = level;
      this.hp = hp;
      this.atk = atk;
   }
}


public class Player extends Creature {

   private int currentEXP;
   private int expBar;

   public Player(String name) {
      super(name, 1, 100, 10);
      this.currentEXP = 0;
      this.expBar = 50;
   }
}


public class Enemy extends Creature {

   int exp;

   public Enemy(String name, int level, int hp, int atk, int exp) {
      super(name, level, hp, atk);
      this.exp = exp;
   }
}

Upvotes: 2

Views: 527

Answers (1)

Bjørn Vårdal
Bjørn Vårdal

Reputation: 174

First of all, the private modifier makes level unavailable in the subclasses. To solve that, you can either make change private to protected (or nothing / default), or you can provide an accessible getter method (int getLevel() { return level; }).

Your Enemy constructor takes a level argument, so to implement the player level + 1 feature, you can simply pass player.getLevel() + 1, alternatively pass player.getLevel() and let the constructor take care of adding 1.

The method using these classes (assuming main for now) would look something like this:

public static void main(String[] args) {  
    Player p = new Player("Player1");  
    Enemy e = new Enemy("Enemy1", p.getLevel() + 1, 100, 10, 40);  
}  

To clarify, the reason why Player.getLevel + 1 doesn't work is because Player is a class, but you need a Player object (i.e. the result of calling new Player(...)) to refer to instance fields or methods, such as getLevel.

Upvotes: 1

Related Questions