运行此脚本时,按1并单击Enter会显示两个口袋妖怪的生命值,它将您的攻击生命值减去敌人生命值。当您或敌人击中0或小于0的生命值时,它应该停止并只显示谁在控制台日志中获胜。取而代之的是显示消息。
因此,如果您的功率为-10 hp,则需要再承受一击。
let firstFight = false;
while (!firstFight) {
let fightOptions = prompt("1. Fight, 2.Items, 3.Potions " + wildPokemon[0].name + ":" + wildPokemon[0].hp + " " + pokeBox[0].name + ":" + pokeBox[0].hp);
if (fightOptions == 1) {
if (!firstFight) {
if (wildPokemon[0].hp <= 0) {
console.log("You have won!");
firstFight = true;
} else {
let attack1 = wildPokemon[0].hp -= pokeBox[0].attack.hp;
console.log(wildPokemon[0].hp);
}
if (pokeBox[0].hp <= 0) {
console.log(wildPokemon[0] + " has killed you");
firstFight = true;
} else {
let attack2 = pokeBox[0].hp -= wildPokemon[0].attack.hp;
console.log(pokeBox[0].hp);
}
}
} else if (fightOptions == 2) {
} else if (fightOptions == 3) {
} else {
}
}
有什么方法可以使这段代码更有效?
答案 0 :(得分:2)
您可以简单地添加另一个if条件,以检查玩家的生命是否仍然大于还是等于“ 0”还是小于等于“ 0”。
这样,您就不必去下一回合检查玩家的生命,而且它摆脱了多余的条件语句...
if (fightOptions == 1) {
let attack1 = wildPokemon[0].hp -= pokeBox[0].attack.hp;
console.log(wildPokemon[0].hp);
if (wildPokemon[0].hp <= 0) {
console.log("You have won!");
firstFight = true;
}
if (!firstFight){
let attack2 = pokeBox[0].hp -= wildPokemon[0].attack.hp;
console.log(pokeBox[0].hp);
if (pokeBox[0].hp <= 0) {
console.log(wildPokemon[0] + " has killed you");
firstFight = true;
}
}
}
答案 1 :(得分:0)
当条件为false时,循环将停止,但在这种情况下,将其设置为false,则不会停止,因为您未明确确定条件。您可以通过两种方式进行操作。
第一:
while(!firstFight == false)
第二:
var firstFight = true; while(firstFight) 然后在if else语句中将firstFight设置为false。
答案 2 :(得分:0)
问题是,要检查点是否等于或小于零后,要减去这些点。您可以通过以下方式进行检查:
let firstFight = false;
while (!firstFight) {
let fightOptions = prompt("1. Fight, 2.Items, 3.Potions " + wildPokemon[0].name + ":" + wildPokemon[0].hp + " " + pokeBox[0].name + ":" + pokeBox[0].hp);
if (fightOptions == 1) {
wildPokemon[0].hp -= pokeBox[0].attack.hp;
if (wildPokemon[0].hp <= 0) {
console.log("You have won!");
firstFight = true;
} else {
console.log(wildPokemon[0].hp);
}
pokeBox[0].hp -= wildPokemon[0].attack.hp;
if (!firstFight && pokeBox[0].hp <= 0) {
console.log(wildPokemon[0] + " has killed you");
firstFight = true;
} else {
console.log(pokeBox[0].hp);
}
} else if (fightOptions == 2) {
} else if (fightOptions == 3) {
} else {
}
}