Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

javascript - JS while循环不会真的停止(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.(运行此脚本时,按1并单击Enter会显示两个口袋妖怪的生命值,它将您的攻击生命值减去敌人生命值。)

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.(当您或敌人击中0或小于0的生命值时,它应该停止并只显示谁在控制台日志中获胜。) 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.(因此,如果您的功率为-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 { } } Are there any ways I can make this code more efficient?(有什么方法可以使这段代码更有效?)   ask by Neiko101 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can simply add another if condition to check whether life of the player is still greater then '0' or less then '0' in the same turn like this.(您可以简单地添加另一个if条件,以检查玩家的生命是否仍然大于“ 0”还是小于“ 0”,就像这样。)

in this way you don't have to go for next turn to check for the players life plus it rids off the extra conditional statements...(这样,您就不必去下一回合检查玩家的生命,而且它摆脱了多余的条件语句...) 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; } } }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...