我有一个if语句(基于回合的攻击),如果有一个简单的方法来突破if语句,那么如果敌人已经死了就不会反击?
希望不做另一个if语句等于我已经拥有的语句。在彼此内部有两个相同的if语句听起来很愚蠢。
最简单的方法是,一旦敌人死亡,我会猜到While循环爆发。但我不是专家。
while (!monster.isDead() && !player.isDead())
{
HashSet<String> input = reader.getInput();
if(input.contains("attack")) {
int playerAttack = player.attack();
int monsterAttack = monster.attack();
if (monster.getMonsterLiv() > 0)
{
monster.getAttacked(playerAttack);
System.out.println(Utilities.battleString(player.getName(), monster.getMonsterNavn(), playerAttack, monsterAttack, monster.getMonsterLiv()));
overView += "\n" + Utilities.battleString(player.getName(), monster.getMonsterNavn(), playerAttack, monsterAttack, monster.getMonsterLiv());
player.getAttacked(monster.attack());
System.out.println(Utilities.battleString(monster.getMonsterNavn(), player.getName(), monsterAttack, playerAttack, player.getHealth()));
overView += "\n" + Utilities.battleString(monster.getMonsterNavn(), player.getName(), monsterAttack, playerAttack, player.getHealth());
} else {
monster.getAttacked(playerAttack);
System.out.println(player.getName() + " attacks " + monster.getMonsterNavn() + " for " + playerAttack + " damage, and kills the " + monster.getMonsterNavn());
overView += "\n" + player.getName() + " attacks " + monster.getMonsterNavn() + " for " + playerAttack + " damage, and kills the " + monster.getMonsterNavn();
}
}
else if (input.contains("run"))
{
player.setGold(player.getGold() - 50);
break;
}
else {
System.out.println("Unknown word, try \"attack\" or \"run\" instead!");
}
}
我这样做的方式可能有点奇怪。任何格式的代码提示也欢迎!
答案 0 :(得分:2)
按如下方式更改攻击例程的内容:
int playerAttack = player.attack();
int monsterAttack = monster.attack();
monster.getAttacked(playerAttack);
//etc
if (monster.getMonsterLiv() > 0)
{
player.getAttacked(monster.attack());
//etc
} else {
//The monster dies from massive damage!
}
这个想法是你总是将玩家的攻击应用于怪物,然后你只有在怪物还有生命的情况下才会将玩家的攻击应用于怪物。
这样你就不必“突破”你的逻辑;下一个循环迭代将自动结束。