Can't add new mechanic?


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
        console.log("Congrats! You hit the dragon for"+ " " + damageThisRound);
        totalDamage += damageThisRound;
        if (totalDamage>=4){
            console.log("You slew the dragon!");
            youHit = Math.floor(Math.random()*2);
            console.log("saved by your shield");
            dragonShield = false;
            console.log("The dragon killed you!");
            slaying = false;


this should be
if (dragonShield)

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


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


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
---- 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


Ah ok I think I get the idea now.


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)


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


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