我有一个关于物体的问题。我开发了一些基本的RPG。在这个游戏中,我有一个角色(假设这个角色对象是英雄)。英雄有装备,按主手,防弹衣等。这个英雄想用他手中的武器攻击,比方说他有一把长剑。
一个词来看待我的武器类--这个类中的对象有“攻击”方法。该方法获取攻击者和目标的参数,因此(这里的武器对象).attack(英雄,hero2)使用武器对象攻击hero2。
我的问题如下--当代码知道“英雄”是第一个调用攻击方法的对象时,我是否可以避免使用攻击(英雄,hero2)?
这是攻击命令:
hero.getEquipment().getPrimaryHand().attack(hero, hero2);在攻击方法中,“这里的一些代码”能被替换为“英雄”吗?
hero.getEquipment().getPrimaryHand().attack(some code here, hero2);编辑:添加MeleeWeapon类(武器子类):
public class MeleeWeapon extends Weapon {
boolean throwable;
MeleeWeapon(String name,String reqTraining, boolean oneHaned, int n, int dice, int attackBonus, int damageBonus,double weight, long cost, boolean throwable) {
super(name, reqTraining, weight, cost, oneHaned, n, dice, attackBonus, damageBonus);
this.throwable = throwable;
}
static ArrayList<MeleeWeapon> meleeWeaponList = new ArrayList<MeleeWeapon>();
static
{
meleeWeaponList.add(new MeleeWeapon("Long Sword","Martial", true, 1, 8, 0, 0,8, 10, false));
meleeWeaponList.add(new MeleeWeapon("Short Sword", "Martial", true, 1, 6, 0, 0,5, 5, false));
meleeWeaponList.add(new MeleeWeapon("Dagger","Basic", true, 1, 4, 0, 0,2, 3, true));
meleeWeaponList.add(new MeleeWeapon("Quarter-staff", "Basic", false, 1, 4, 0, 0,3, 2, false));
meleeWeaponList.add(new MeleeWeapon("Shield", "Shield", false, 1, 4, 0, 0,8, 8, false));
}
public void attack(Character attacker, Character defender){
int attackRoll = DiceRoller.roll(20) + attacker.getBaseAttackBonus() + attacker.getModifier(attacker.getStrength()) + getAttackBonus() ;
System.out.println(attacker.getName() + " attack Roll: " + attackRoll + "AC: " + defender.getArmorClass());
if (attackRoll >= defender.getArmorClass()){
System.out.println("Defender: " + defender.getName() + " had " + defender.getCurrentHp());
int damage = DiceRoller.roll(getN(), getDice()) + attacker.getModifier(attacker.getStrength()) + getDamageBonus() ;
System.out.println("Damage : " + damage);
defender.setCurrentHp(attacker.getCurrentHp() - damage);
System.out.println("Defender: " + defender.getName() + " has " + defender.getCurrentHp());
} else {
System.out.println("Missed Attack");
}
}发布于 2015-11-17 10:42:20
您可以在Character类中使用一个攻击方法来包装其他attack方法:
public void attack (Character other) {
getEquipment().getPrimaryHand().attack (this, other);
}你简单地称它为:
hero.attack (otherHero);发布于 2015-11-17 10:56:50
武器不应该是攻击的武器。英雄应该有攻击的方法。你需要通过另一个被攻击的英雄。用于攻击的武器将为该方法所知,因为它也应该可以在Hero类中使用。
英雄应该有攻击的方法而不是武器的原因有几个:
这是一个如何设置它的快速示例(显然,字段/类/方法可能因为它只是一个示例而缺失)。
class Hero {
Weapon weapon;
int health = 100;
public void setWeapon(Weapon weapon) {
this.weapon = weapon;
}
public Weapon getWeapon() {
return this.weapon;
}
public void attack(Hero heroBeingAttacked) {
if (weapon.getType() == 1)
heroBeingAttacked.wasAttacked(5);
else if (weapon.getType() == 2)
heroBeingAttacked.wasAttacked(15);
else
heroBeingAttacked.wasAttacked(0);
}
public void wasAttacked(int damage) {
this.health -= damage;
//check if Hero dies, etc.
}
}https://stackoverflow.com/questions/33754830
复制相似问题