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

标签 javascript if-statement while-loop console prompt

当你运行这个脚本时,它会显示两个神奇宝贝的 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/

相关文章:

关于不完整变量的 Javascript 警报

ES6 中的 Javascript 类,如何将它们导入到其他 js 文件和 html 文件中?

java - 如果在外部使用则内部变量

php - 错误中给出的警告 : mysql_fetch_array() expects parameter 1 to be resource, bool 值

javascript - 如何编写挂接到 ng-click 处理程序的指令

javascript - datepicker - 通过 datepicker 对象初始化时,onSelect 事件不会触发

javascript - 使用 JavaScript 中的 switch 循环更改背景颜色

c - 用多个数字返回C中的奇数/偶数

python - 检查一个值在 While 循环 Python 中是否仍然保持不变

c - 程序在 9 个周期后从 while 循环中退出。 C语言编程