How to pass object parameter to a Java Thread?

Viewed 57

I am on a project to make a text-based RPG game using thread. What I am wondering is, I created a monster class that contains an attack-player method. I have been trying to make a monster to attack player(which is me) automatically with thread. it does attack automatically though, but it does not actually affect the player's status(player's hp etc). I am trying to put the player object as a parameter of auto attack method(which is run method), but I am not really sure what I thought is the right way. I would like to know to set player as a parameter of the run method so that the attack method can affect player's status!

here is the code. attack method works well, but run method does not affect player's status. I probably am able to figure out what the problem is, but what should I do to put the put the player as the parameter so that run method is able to actually affect the player. Thank you!

public void run() {

    while (!stop) {

        try {

            attack(player);

            sleep(2000);

        } catch (Exception e) {
            return;
        }
    }
}

public void attack(Player player) {

    damage = att - player.defence;

    if (att < player.defence) {

        player.hp -= 0;

    } else player.hp -= damage;
}
1 Answers

you have not given the entire code. I am assuming your code to be liked below :

class Test implements Runnable{
boolean stop=false;
public void setStop(boolean stopParams){ this.stop=stopParams;}
public void run() {

    while (!stop) {

        try {

            attack(player);

            sleep(2000);

        } catch (Exception e) {
            return;
        }
    }
}

public void attack(Player player) {

    damage = att - player.defence;

    if (att < player.defence) {

        player.hp -= 0;

    } else player.hp -= damage;
}
}

Related