6/6 - Keeping It Going


#1

2 Things -

1- The dragon never actually wins in my code

2- what changes would I make to make it so that if I hit the dragon but don't kill him, i keep my total damage and take another hit at him?


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 With " + damageThisRound + ". Your Total was " + totalDamage +".");
        totalDamage+= damageThisRound;
            if(totalDamage>=4){
                console.log("You slew the dragon with "+ totalDamage + ", " + damageThisRound + "of it came this round.");
                slaying = false;}
            else{
                youHit = Math.floor(Math.random()*2);}}
    else{
        console.log("Loser!");}
    slaying = false;}

#2

The reason the dragon never wins is because never fail to hit:

    youHit = 1

= operator means you assign a value here and assignment statements have the value you assigns so in this case 1. If you now dig a bit deeper you find that 1 has a value of true (0 would be false) so you always hit because no matter what youHit was now it is 1. So better use == (compares values) or === (compares values and types) here.

I don't really get the second question. Isn't that what you're already doing? Or do you want to one hit him? In this case you could get away from this totalDamage and damageThisRound thing and just implement another coinflip option like you did for youHit. What might be a more obvious choice would have been to reduce the dragon's HP instead of stacking up your attackDamage to a totalDamage. Is this what you mean? In this case you would just decleare a dragonHP at the top and set it to e.g. 4 and instead of totalDamge and instead of increasing totalDamage you would decrease dragonsHP by the amount of damageThisRound and if it falls below 0 you won.


#3

I think I understand his question. Both of our dragons die with one hit when it's supposed to be 4. I apologize in advance for the brackets. It's easier for me to to keep track this way.

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 him!! Great job!");
        totalDamage += damageThisRound;
        if (totalDamage>= 4)
            {console.log("You killed the dragon!! The town is safe!");
            slaying=false;
            }
        else
            {youHit = Math.floor(Math.random() * 2);
            };
        }
    else 
        {console.log("You were burned to a crisp. Better luck nest time.");
        slaying=false;
        };
    
    }