Christian Christian - 3 months ago 6
HTML Question

Javascript doesn't run the whole function (JSLInt doesn't mention)

I checked my javascript code in jslint.com and jshint.com, it says there is no errors. But for some reason, my code isn't running to what I desire. It seems that either the while statement is not working or it stops after the while statement: (By the way, I'm creating this tool for Minecraft)

function attackMode() {

playerData();

if (Enchantment1.value == "Sharpness") {
damageTaken = damageTaken + (1.25 * EnchantmentLevel1.value);

}

if (Enchantment1.value == "Fire Aspect") {
damageTaken = damageTaken + (EnchantmentLevel1.value * 1.37);

}

if (Enchantment2.value == "Sharpness") {
damageTaken2 = damageTaken2 + (1.25 * EnchantmentLevel2.value);

}

if (Enchantment2.value == "Fire Aspect") {
damageTaken2 = damageTaken2 + (EnchantmentLevel2.value * 1.37);

}

while (HP1 <= 0) {
HP1 = HP1 - damageTaken2;
hits1 = hits1 + 1;

}

while (HP2 <= 0) {
HP2 = HP2 - damageTaken1;
hits2 = hits2 + 1;

}

if (hits1 > hits2) {
//document.getElementById('playerWon').innerHTML = player1.value;
alert(player1.value + "won!");
} else if (hits1 < hits2) {
//document.getElementById('playerWon').innerHTML = player2.value;
alert(player2.value + "won!");
}

//alert("test"); <- test
}


The problem is, when, in HTML, it runs the function by the button, it only runs from the if statements to the first while statement. I know this since I put
alert("test")
at the end to see if it runs the whole code. I know I spelled the function correctly since, if I put
alert("test")
at the beginning, it works. Here's the code for the button:
<button id="typeMode" onclick="attackMode()">Attack!</button>
. More specifically, it is in a div with a certain class. Another thing I put was "use strict;" on the first line of my javascript code.

Am I using the wrong syntax? Is it because I forgot to put a semi-colon ';' or something?

Any help is appreciated!

Answer

Your loops are running if the HP is less than or equal to 0. You probably want to swap the comparison around.

  while (HP1 >= 0) {
      HP1 = HP1 - damageTaken2;
      hits1 = hits1 + 1;

  }   

  while (HP2 >= 0) {
      HP2 = HP2 - damageTaken1;
      hits2 = hits2 + 1;

  }

  if (hits1 > hits2) {
      //document.getElementById('playerWon').innerHTML = player1.value;
      alert(player1.value + "won!");
  } else if (hits1 < hits2) {
      //document.getElementById('playerWon').innerHTML = player2.value;
      alert(player2.value + "won!");
  } else {
      alert("draw!");
  }
Comments