javascript - Looping JS Function Until if or else Condition is Met -


i have created function when called parameters play out , either tell player won or died based on math. have tested function , works, set parameters in function calling player win , displayed win message alert. if increase monster health player not win first time function called, function not repeat tried set "else fight()" (as seen below).

my question this, how loop function same parameters before until else or else if arguments met?

calling function in html:

<a class="button" onclick="javascript:fight(8, 5, 1, 10, 3);">test fight</a><br> 

js function:

var playerhealth = 100;  function fight(monsterhealth, monsterdmg, monsterarmor, itemdmg, armorsts) {  newplayerhealth = playerhealth - monsterdmg / armorsts + 2;  newmonsterhealth = monsterhealth - itemdmg / monsterarmor + 2;  if (playerhealth <= 0) {       alert('you died...');  }  else if (newmonsterhealth <= 0) {       alert('you won!');  }  else  {  var newplayerhealth =  playerhealth;  fight(newmonsterhealth, monsterdmg, monsterarmor, itemdmg, armorsts);  } } 

edit: updated function , says win no matter how high monster's damage or health is.

in code playerhealth intialize inside function resetting players health 100 in recursive call.

newmonsterhealth not persisted considering recursive calls.

  <html> <head> <script>      var playerhealth = 100;  function fight(monsterhealth, monsterdmg, monsterarmor, itemdmg, armorsts) {   playerhealth = playerhealth - math.floor(monsterdmg / armorsts) ;     console.log("player helath"+playerhealth);  monsterhealth = monsterhealth - math.floor(itemdmg / monsterarmor) ;     console.log("monster helath"+monsterhealth);  if (playerhealth <= 0) {       alert('you died...');  }  else if (monsterhealth <= 0) {       alert('you won!');  }  else fight(monsterhealth, monsterdmg, monsterarmor, itemdmg, armorsts); }   </script> </head> <body>     <a class="button" onclick="javascript:fight(100, 40, 1, 10, 3);">test fight</a><br>     </body> </html> 

p.s. removed +2 logic (i won't understood why adding)


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -