Can't add new mechanic?


#1


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


I tried to add a new mechanic which i simply named dragonShield for experimentation, but whenever I start the code, my browser crashes. This tells me I have an infinite loop, but i can't figure out how.
The idea is that the first time you're hit by the dragon, dragonShield is changed to false but you don't die and keep slaying. Can someone correct my code so I can see what happened?


var slaying = true
var youHit = Math.floor(Math.random()*2)
var damageThisRound=Math.floor(Math.random()*5+1)
var totalDamage=0
var dragonShield = true
while(slaying){
    if(youHit===1){
        console.log("Congrats! You hit the dragon for"+ " " + damageThisRound);
        totalDamage += damageThisRound;
        if (totalDamage>=4){
            console.log("You slew the dragon!");
            slaying=false;
        }
        else{
            youHit = Math.floor(Math.random()*2);
        }
    }else{
        if(dragonShield=true){
            console.log("saved by your shield");
            dragonShield = false;
        }else{
            console.log("The dragon killed you!");
            slaying = false;
        }
    }
}


#2

this should be
if (dragonShield)
or

if (dragonShield == true)

and you didn't add a "youHit" set within your else, so as soon as you miss once, it's an infinite loop


#3

Ok...I don't really get the youHit but at least I know what I did wrong. Thank you!


#4

The youHit needs to be set within your else:

let's go through a few rounds of this:

youHit = 1

round 0
while slaying
-- youHit === 1 ? true
{ damage dragon and either state you killed it, or update youHit ]
-- {for all intents and purposes, youhit = 0 now from the set}

round 1
while slaying
-- youHit === 1 ? false
--else
---- if ( set dragonShield to true ) -- setting a variable to true within this will be evaluated:
------ dragonshield = true ;; if dragonshield -> which will alwars return true.

round 2
youHit is still 0 since we didn't give it a value within the else statement -> inf. loop


#5

Ah ok I think I get the idea now.


#6

actually now im getting a repetitive answer...I figured out it does not repeat if I am saved by my shield. So, I am saved and then killed every time. Is there a way to fix this?(I don't think slaying is staying true)


#7

Nevermind I fixed it I needed to move where I put the youHit value


#8

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