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.
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
Playerin yourTrainclass, and assign it in your constructor. E.g.You can then call
player.method()in the train class, and it will update thePlayeryou passed to the constructor.Thus, when you create an instance of
Train, pass it thePlayeryou have already created and it will update the player based on what happens in Train.