5. Dragon Slayer - 2nd If Statement - Question


#1


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


Code works. However it's a little funky when it runs certain times. When I run it, there are 3 different outcomes. 1.) Dragon defeated me. If I'm understanding this correctly, that's when youHit === 0 in the first if statement, it goes all the way down to the 2nd else statement and runs the console.log and then ends b/c slaying is false. The 2nd outcome is, I defeat the dragon. This is when youHit === 1 at the top, but since totalDamage is less than 4, we keep looping and youHit keeps getting 1, until eventually we get to 4 and the console.log statement runs that I slayed the dragon. The third outcome reads in the console, 'you hit the dragon!' and then false. If I'm trying to understand the loop, I think this is when the first youHit === 1 and the 2nd youHit === 0 and then it get to slaying = false so it logs, one hit, and then false. Is that correct? Is that how it should be?


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("You hit the dragon!");
        totalDamage += damageThisRound;
        if(totalDamage >= 4) {
            console.log("You slayed the dragon!");
            slaying = false;
        } else {
            youHit === Math.floor(Math.random() * 2);
        };
    } else {
        console.log("The dragon defeated you");
    };
    slaying = false
};


#2

yes,you are correct :slight_smile:


#3

Thanks, codeman.

I guess if I was building this game, I would make sure that there were only two outcomes, I win or the dragon wins. Having the third outcome doesn't really move the game forward.


#4

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