我做了以下两个对象:
Fighter Lucas = new Fighter(Statistics.punchStrength,
Statistics.movementSpeed, Statistics.reflex);
Opponent Simon = new Opponent(Statistics.punchStrength2,
Statistics.movementSpeed2, Statistics.reflex2);
我想通过比较它们的随机变量使它们“战斗”,但是我不知道该怎么做。
最佳答案
您的Fighter
类应具有方法attack(Opponent)
class Figher{
// ..
public void attack(Opponent opponent){
int opponentMaxDamage = calculateHitpointsBy(opponent);
int damageByOpponent = opponent.defend(this, opponentMaxDamage);
this.lifePoints-=damageByOpponent;
}
public boolean isAlive(){
return 0< this.lifePoints;
}
// ..
}
并且您的Opponent类应具有方法
defend(Fighter)
class Opponent{
// ..
public void defend(Figher fighter, int maxAttackDamage){
int myDamage = reduceDamage(fighter,int maxAttackDamage);
int attackerDamage = calculateAttackerDamage(fighter);
this.lifePoints-=myDamage ;
}
public boolean isAlive(){
return 0< this.lifePoints;
}
// ..
}
这使您可以在以后为寿命点添加更复杂的计算。例如:攻击者对对手的实际伤害可能取决于她所穿戴的设备。对手受到的伤害也可能如此。
方法
isAlive()
可以提取到公共基类中。您可以通过以下方式使用它:
Fighter Lucas = new Fighter(Statistics.punchStrength, Statistics.movementSpeed, Statistics.reflex);
Opponent Simon = new Opponent(Statistics.punchStrength2, Statistics.movementSpeed2, Statistics.reflex2);
// fight
while(Lucas.isAlive()&&Simon.isAlive())
Lucas.attack(Simon);
// report winner
if(Lucas.isAlive())
System.out.println("winner is Lucas");
if(Simon.isAlive())
System.out.println("winner is Simon");