我正在努力使用Java方法

时间:2015-09-28 03:52:12

标签: java methods

我正在尝试编写一些战斗方法,但我遇到了一些困难。

代码:

    int attackPower;
    int defencePower;
    int healthPoints;
    int startingHealthPoints;
    int remainingHealthPoints;
    int damageDone = 0;

    //Constructor
    public Combat(int initialAttackPower, int initialDefencePower, int initialHealthPoints) {
        attackPower = initialAttackPower;
        defencePower = initialDefencePower;
        healthPoints = initialHealthPoints;
    }

    //Methods 
    public void setAttackPower(int newAttackPower) {
        attackPower = newAttackPower;
    }

    public void setDefencePower(int newDefencePower) {
        defencePower = newDefencePower;
    }

    public void setHealthPoints(int newHealthPoints) {
        healthPoints = newHealthPoints;
    }

    int getAttackPower() {
        return attackPower;
    }

    int getDefencePower() {
        return defencePower;
    }

    int getHealthPoints() {
        return healthPoints;
    }

    int getDamageDone() {
        damageDone = 5;
        return damageDone;
    }

    int getStartingHealthPoints(int currentHP) {
        if (damageDone == 0) {
            return startingHealthPoints = healthPoints;
        }
        else {
            return startingHealthPoints = currentHP + damageDone;
        }
    }

    int getRemainingHealthPoints() {
            return remainingHealthPoints = startingHealthPoints - damageDone;
        }

主要

Combat combat1 = new Combat(15,20,100);
       System.out.println("Total HP: " + combat1.getHealthPoints());
       System.out.println("Starting HP: " + combat1.getStartingHealthPoints(combat1.getRemainingHealthPoints()));
       System.out.println("Attack 1: " + combat1.getDamageDone());
       System.out.println("After Attack 1 HP: " + combat1.getRemainingHealthPoints());
       System.out.println("Before Attack 1 HP: " + combat1.getStartingHealthPoints(combat1.getRemainingHealthPoints()));
       System.out.println("Attack 2: " + combat1.getDamageDone());
       System.out.println("After Attack 2 HP: " + combat1.getRemainingHealthPoints());
       System.out.println("Before Attack 2 HP: " + combat1.getStartingHealthPoints(combat1.getRemainingHealthPoints()));
       System.out.println("Total HP: " + combat1.getHealthPoints());

主要输出:

Total HP: 100
Starting HP: 100
Attack 1: 5
After Attack 1 HP: 95
Before Attack 1 HP: 100
Attack 2: 5
After Attack 2 HP: 95
Before Attack 2 HP: 100
Total HP: 100

理想情况下,每次攻击后,startingHealth和remainingHealth都应相应更改。因此,例如,在攻击之后2 HP应该是90并且在攻击之前HP应该是95.然后对于攻击之后3 HP应该是85并且在HP之前应该是90.所以等等。我可能犯了一个简单的错误,但我真的可以使用一些帮助。

1 个答案:

答案 0 :(得分:2)

你的"之前"将会:       getHealthPoints()

接下来是某种receiveAttack()方法,您可以传入表示攻击强度的健康点。

    public void receiveAttack(int damage) {
       healthPoints -= damage;
    }

现在,再次调用getHealthPoints()并获得总数。

如果您需要存储"最近的损坏",请确保为此添加另一个字段,并在对象受到攻击时存储它。