Dragon Slayer always win with this code?


#1


My code ALWAYS leads to a win, and I am unsure why exactly.

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=1) {
        console.log("It's a hit, well done! You did " + damageThisRound + " damage!");
        totalDamage+=damageThisRound
        if(totalDamage>=4) {
            console.log("The dragon is dead! You have accomplished much! Congrats!!!");
            slaying=false
        } else {
            youHit=Math.floor(Math.random()*2);
        }
    } else {
        console.log("You miss, and the dragon takes advantage of the opportunity to eat you whole!")
        slaying=false;
    }
}


#2

= is for assigning/equating. == is for comparison. Check your if statement and see if you are using == instead of =.


#3

Thanks! I found a fix by just removing the =1 entirely, so it looked like if (youHit) but I was still confused why that wouldn't work.


#4

When you do an if statement such as if (youHit=1), it will always evaluate to True because any number that is not 0, is True. Hence why you keep getting the winning message.
youHit=1 means to assign 1 to variable youHit.

If you do if (youHit == 1) or if (youHit === 1) (I forgot which), then you are basically saying if youHit is equal to 1. == or === is for comparison and will produce True or False depending on whether youHit is equal to 1 instead of just True when you do if (youHit = 1).

I hope this clears up the confusion.


#5

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