The Second IF statement


#1


https://www.codecademy.com/courses/javascript-beginner-en-mrTNH-6VIZ9/0/5?curriculum_id=506324b3a7dffd00020bf661

Hey guys, I've just finished the second IF statement and its displaying my code without any error messages but when I run it the only outcome is that I seem to lose every time, it is just because of chance or have I missed something?

Cheers!


slaying = true;
youHit = Math.floor(Math.random()* 2);
damageThisRound = Math.floor(Math.random()*5 + 1);
totalDamage = 0;

while(slaying) 
{
    console.log("Yassss you slayyyy!");
    slaying=false;

if (youHit === true)  {
    console.log("Yas you slayed da dragon. OOohh he needs some milk!");
    totalDamage += damageThisRound;
    slaying = false;
    
        if(totalDamage >= 4) {
            console.log("SLEW DEMMM. Dragon KO'd");
            slaying = false;
            } 
            
            else {
                youHit = Math.floor(Math.random()*2);
                }
    }
else 
    {
    console.log("Dragon whooped yo ass bruh. Damn Daniel :(");
    }
}


#2

It works fine, though you forgot to use var keyword while creating variables!


#3

Ahh right ok, thanks for that @greentreemee. The result kept coming back that i'd lost every time, just wanted to check. Var's added now!


#4

Does it solve the problem?


#5

Hmmm no its still only producing one result. I even increased the youHit var and decreased the totalDamage to give a better probability but still same result :confused:


#6

var is lowercased not Var.. tell me what you get by doing that..ok


#7

Yeah i'm still getting the same result. I'm not sure if its the order of my statements, it works but its annoying that I don't get both results. I don't think anybody would want to play this game


#8

I have the same problem, some time i get like 4 results put if I try to rerun the code it stucks in looping and the browser frozen
here is my code

var slaying = true;
var youHit= Math.floor(Math.random()*2);
var damageThisRound = Math.floor(Math.random()*5+1);
var totalDamage= 0;

while(slaying){
if (youHit){
console.log("you hit!");
totalDamage += damageThisRoound;
if(totalDamage>=4){
console.log("you win!");
slaying=false;
}else{
youHit=Math.floor(Math.random()*2);
}
}else {
console.log("dragon defeated you");

}
}


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.