JS while循环不会在true处停止

问题描述 投票:0回答:2

运行该脚本时,按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 {

  }

}

有什么方法可以使这段代码更有效?

javascript if-statement while-loop console prompt
2个回答
0
投票

虽然当条件为false时循环停止,但在这种情况下,将其设置为false,则不会停止,因为您没有明确确定它。您可以通过2种方式进行操作。

第一:

while(!firstFight ==假)

第二:

var firstFight = true;while(firstFight)然后在if else语句中将firstFight设置为false。


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 {

  }

}
© www.soinside.com 2019 - 2024. All rights reserved.