mercredi 27 novembre 2019

JS while loop doesnt stop at true

When you run this script it shows the HP for both of the pokemon when you press 1 and click enter it subtracts your attack hit points to the enemies hit points. When you or the ememy hits 0 or less than 0 hit points it is supposed to stop and just show who won in the console log. Instead it takes an extra hit to for it to show the message.

So if you are at -10 hp it takes one more hit.

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 {

  }

}

Are there any ways I can make this code more efficient?

Aucun commentaire:

Enregistrer un commentaire