speak
speak

Reputation: 5382

Text Based Java Game Pass Variables To Another Class

I am coding a text based Java game, I have ran into a few issues I cannot get my head around.

My code works along these lines:

        public class main() {
           run initial method for menu
           Player player = new Player(name,1,1,1);
           do{
           game code
           while(running = true)
          }

       public class Player() {
           string name
            int age
            int level
            int exp

           getName()
           setName() etc etc
          }

       public class Train() {
        kill monster
        totalExp = monsters killed

        }

Now, the problem is, how do I pass the exp gained to my player class which has my get and set methods? The exp is calculated/generated in the Train class, but I need to pass it through to Player so I can use .set/.get and display the updated information in my Main class.

Would adding:

Player player = new Player(name,1,1,1) into the Train class just create a NEW object of Player so I would have two, and assign the exp to the player in Train() but leave the one in Main() alone.

Many thanks for your help.

Upvotes: 0

Views: 231

Answers (2)

Michael
Michael

Reputation: 1239

You are correct in your assumption that adding a new object of Player in train would leave another unaffected. What you can do is add a reference to a Player in your Train class, and assign it in your constructor. E.g.

class Train {
    Player player;
    public Train(Player p) {
        player = p;
        /* ... */
    }
    /* ... */
}

You can then call player.method() in the train class, and it will update the Player you passed to the constructor.

Thus, when you create an instance of Train, pass it the Player you have already created and it will update the player based on what happens in Train.

Player p = new Player(...);
Train t = new Train(p);

Upvotes: 2

Attila
Attila

Reputation: 28772

You could pass the player instance to the Train method so Train can operate on that instance directly

E.g.:

public void Train(Player player) {
  kill monster
  totalExp = monsters killed
  player.setXP(player.getXP() + totalExp)
}

Upvotes: 2

Related Questions