开发者

How do I set up a targetting system in Java?

I am making a command-line game in Java to help learn better about GUI and such and I ran into a problem. In the game I want to be able to target another player. I am making a method called attack(). How would I go about, if I wanted to attack a player, bar, making it so that I could use attack(bar) as a function. I don't know how to reference an object in a parameter or an object created in a different class. What I need to my code to do is basically this: Assume my name is Player foo and I am attacking Player bar. Each player has 2 instanc开发者_如何转开发e variables, Player.playerHealth and Player.playerDamage (the damage that they do). I need it to do:

attack(playerTarget) {
    target = playerTarget
    target.playerHealth = target.playerHealth - foo.playerDamage;  
}

So basically I need it to set the player losing health equal to the name in the parameters. How might I achieve this?


I think you are looking for something like this:

public class Player {
    private int playerHealth;
    private int playerDamage;

    public void attack(Player target) {
        target.playerHealth -= this.playerDamage;
    }

    public static void main(String[] args) {
        Player foo = new Player();
        foo.playerHealth = 10;
        foo.playerDamage = 1;

        Player bar = new Player();
        bar.playerHealth = 10;
        bar.playerDamage = 1;

        foo.attack(bar);
        foo.attack(bar);

        System.out.println(bar.playerHealth); // will print 8
    }
}

The attack method is declared on the Player class, so anytime you have a reference 'foo' to a Player, you can call attack in the following way: foo.attack(otherPlayer).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜