外部方法调用帮助

时间:2011-08-15 04:33:08

标签: java

所以我想做的就是在一个对象上调用一个外部方法,它比我想象的要复杂一些,并且在正确实现它时遇到了问题。 方法是:

攻击(玩家受害者)

该方法需要在对象上调用hit()方法;如果hit()方法成功(通过布尔值测试?):

  • 使用if语句调用对象上的damage()方法来确定损坏

  • 在(PlayerVictim)上调用takeDamage()来造成伤害。

这是迄今为止编码的播放器类; attack()方法位于底部。 我的主要问题是如何在当前武器上使用外部方法伤害()并在玩家受害者身上使用takeDamage()

public class Player
{
   private String myPlayerName;
   private Weapon myWeapon;
   private int myCurrentHealth;
   private int myMaxHealth;
   private int myNumPotions;


    /**
     * Constructor initializing class Player
     * Parameters of the player should be:
     * player name, players initial health, the players weapon.
     */
    public Player(String myPlayer, int initialHealth, Weapon currentWeapon) {
        myPlayerName = myPlayer;
        this.myWeapon = currentWeapon;
        myMaxHealth = 30; 
        myCurrentHealth = initialHealth;
        myNumPotions = 0;       
    }

    /**
     * Attack method which attacks opposing player
     * with current equipped weapon.
     */
    public void attack(Player victim) {
        currentWeapon.hit();
        if (boolean currentWeapon.hit() = true) {
            currentWeapon.damage(int dam);
            return dam;

        }
        Player victim.takeDamage(int damage);

    }


}

和武器类:

import java.util.Random;
public class Weapon
{
    private int myHitProb;
    private int myMaxDamage;
    private Random myRNG;

    /**
     * Create a new weapon with a hit probability and damage
     */
    public Weapon(int hitProb, int damage) {
        myHitProb = hitProb;
        myMaxDamage = damage;
        myRNG = new Random();
    }

    public boolean hit() {

        int r = myRNG.nextInt(100);

        if (r < myHitProb) {
            return true;
        }
        else {
            return false;
        }
    }

    public int damage() {
        int dam = myRNG.nextInt(myMaxDamage) + 1;        
        return dam;
    }
}

1 个答案:

答案 0 :(得分:1)

你的attack()方法可能有很多东西,但不是可编译的java 也许这就是你的意思:

public void attack(Player victim) {
    if (currentWeapon.hit()) {
        victim.takeDamage(currentWeapon.damage());
    }
}

尽量记住这条准则:如果看起来很难,你可能会采取错误的方式(除非你正在研究Mars Lander program :))