Simple JavaScript if / else statements -


i'm learning javascript. here code. simple program in user fights dragon, added bit if dragon reduces user's health 0, code finishes. whenever run code, though, once dragon begins reduce health of user, happens. user isn't able trade blows dragon. doing wrong?

var userhealth = 5; var youhit = math.floor(math.random() * 2); var damagethisround = math.floor(math.random()*5 + 1); var totaldamage = 0; var dragondamage = math.floor(math.random() * 2); while (userhealth > 0) {     if (youhit) {         console.log("you hit dragon!");         totaldamage += damagethisround;         console.log("total damage dealt: " + totaldamage + "!");         if (totaldamage >= 4) {             console.log("you slew dragon!");             userhealth = 0;         }         else {             youhit = math.floor(math.random() * 2);         }     }     else {         console.log("the dragon has dealt damage you!");         userhealth -= dragondamage;         dragondamage = math.floor(math.random() * 2);         console.log("your health now: " + userhealth + "!"); } } 

youhit calculated once. because of that, once dragon deals damage player, keep dealing damage.

you can wrap calculations in function , fire them instead:

function fightdragon() {     var userhealth = 5;     var youhit = function() {         return math.floor(math.random() * 2);     };     var damagethisround = function() {         return math.floor(math.random() * 5 + 1);     }     var totaldamage = 0;     var dragondamage = function() {         return math.floor(math.random() * 2);     }      while (userhealth > 0) {         var damage = youhit();         if (damage) {             console.log("you hit dragon!");             totaldamage += damagethisround();             console.log("total damage dealt: " + totaldamage + "!");             if (totaldamage >= 4) {                 console.log('you slew dragon!');                 break;             }         } else {             console.log('the dragon has dealt damage you!');             userhealth -= dragondamage();             console.log('your health now: ' + userhealth + '!')         }     }  } 

Comments