javascript - Can't figure out why infinite loop occurs -
i'm practising loops in javascript whilst writing got infinite loop can't solve i'm sure hindsight 20/20 kind of problem cant't see it. loop in meleechoice
/*var meleevalues = function() {*/ var userdmg = math.floor(math.random()* 5 + 10); var ghouldmg = math.floor(math.random()* 4 + 8); var ghoulhealth = 100; var userhealth = 110 ; var usertotaldmg = 0 ; var ghoultotaldmg = 0; var firstatk = function() { firststrike = math.floor(math.random()* 2 + 1); if(firststrike === 1) { ghoulhealth = 100 - usertotaldmg; console.log("you hit ghoul " + userdmg + " damage"); console.log("the ghoul has " + ghoulhealth + " health left"); userhealth = 110 - ghoultotaldmg; console.log("ghoul hits " + userdmg + " damage"); console.log("you have " + userhealth + " health left"); } else { userhealth = 110 - ghoultotaldmg; console.log("ghoul hits " + userdmg + " damage"); console.log("you have " + userhealth + " health left"); ghoulhealth = 100 - usertotaldmg; console.log("you hit ghoul " + userdmg + " damage"); console.log("the ghoul has " + ghoulhealth + " health left"); } } var meleechoice = function() { while(ghoulhealth > 0 && userhealth > 0) { usertotaldmg += userdmg; ghoultotaldmg += ghouldmg; firstatk; userdmg = math.floor(math.random()* 5 + 10); ghouldmg = math.floor(math.random()* 4 + 8); if (ghoulhealth < 0 && userhealth > 0) { console.log("congratulations, have defeated ghoul , gained 20xp"); } else if (ghoulhealth > 0 && userhealth < 0) { console.log("you have been slain ghoul, may corpse serve warning future explorers"); } else { console.log("it's not on yet"); } } } meleechoice() /*var user = prompt("you run ghoul whilst exploring dungeon, choose do?", "fight | sneak | run").tolowercase(); switch(user) { case "fight": var fight = prompt("do use melee or magic").tolowercase() if(fight === "melee") { meleechoice } }*/ thanks
if @ predicate in while loop, see depends on both ghoulhealth
userhealth
. yet inside loop never change values of either of these. means if predicate true @ start, loop commence , predicate forever remain true.
as pointed out in comments well, seems due how using function firstatk. should call firstatk()
, note parentheses. , there mistakes in logic method seems. userhealth , ghoulhealth start @ 100 / 110 respectively, health might never drop low enough make predicate false.
Comments
Post a Comment