Instead of retyping the same code, will this work?


#1

So in 'The second 'IF' statement, the instructions say youHit should be assigned a new random 1 or 0. Then, the sample shows it being retyped as

youHit = Math.floor(Math.random() * 2);

I typed it as follows though, and wanted to know if this would work the same since the variable had already been declared prior?

youHit;

The code passed and worked, but I want to clarify that this truly works.

Full code snippet here:

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 defeated the dragon!");
            slaying = false;
        }
        else {
            youHit;
        }
    }
    else {
        console.log("The dragon defeated you.");
    }
    
    slaying = false;
}

#2

You might want to rename it to damagePerRound as now it'll be the same throughout the game.
If you want it to re-roll each time, then you would need a function or a getter which is essentially a function with the syntax of a regular variable.


#3

As @ionatan already said, no it won't work the same way as:

youHit = Math.floor(Math.random() * 2);

means that you compute a value (of either 0 or 1) and that you assign this value to youHit. So throughout the game youHit will always be that value unless you reassign it by for example:

youHit = Math.floor(Math.random() * 2);

Also there is another problem with your code:

if(youhit = 1) {

First of all it uses the variable named youhit which is never declared in your code, the other variable is named youHit and the other thing is that = is the assignment operator not the comparison one, so you don't check if youhit is 1 but you set youhit to be 1. As a side effect an assignment statement has the value you assign so you condition is effectively 1 which is treated as if it meant if(true), regardless of the value of youhit or youHit.


#4

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