gpt4 book ai didi

javascript - JS while 循环不会在 true 处停止

转载 作者:行者123 更新时间:2023-12-01 00:25:01 26 4
gpt4 key购买 nike

当你运行这个脚本时,它会显示两个神奇宝贝的 HP,当你按 1 并单击 Enter 时,它会将你的攻击生命值减去敌人的生命值。当你或 ememy 的生命值达到 0 或低于 0 时,它应该停止并仅在控制台日志中显示谁获胜。相反,需要额外点击才能显示消息。

因此,如果你的马力为 -10,则需要再击中一次。

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 {

}

}

有什么方法可以让这段代码更加高效吗?

最佳答案

您可以简单地添加另一个 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;
}
}

}

关于javascript - JS while 循环不会在 true 处停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59083379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com