Dragon Slaying code questions

#1

In the Dragon Slaying game we set the variable youHit:

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

And this variable should become equal to a random number from 0 to 1(inclusively).
Next, while we're slaying the dragon, we either HIT (true or 1) or MISS (false or 0).

Here's my while statement:

while(slaying) {
if (youHit) {
console.log("You hit!"); }
else {
console.log("You missed!")}

1. Would it be OK to type while(slaying===1)?
2. What about random fraction numbers? How does the program make zeros and ones out of them?

Thanks!

#2
1. No, it's not OK. When you are using boolean variable, there is no need to check if is equal to true/false or 1/0. The variable is true or false and that is enough.

2.

``Math.random();``

returns a random number between 0 and 1.

#3

the function math.floor will round the number to either 0 or 1 depending on your fraction. i.e. if you get 0.3 from Math.random then it will round to 0; likewise, if you get 0.7 it will round to 1.

#4

I have one question too. What is the difference between `if(youHit)` and `if(youHit === 1)` ? Both works fine. As I imagine if (youHit) only checks if it is true, right? and a number 1 stands for a word "true" ?

#5

It's about coding style and writing high quality code. It's redundant code.

The boolean variable has only two possible values - true or false. `youHit === 1` will return true. But this is unnecessary, because "youHit" has already the value true. That is all you need.

Also it's easy to forget to write "===" or "==" when you are beginner. If you write only one equal sign like this:

``````var someBool = false;
if(someBool = true){
console.log("Hi!");
}``````

that will always return true and will give wrong result.

#6

I have another question. Exercise says that:

damageThisRound = Math.floor(Math.random()5 + 1) sets damageThisRound to a random number that's between 1 and 5 (up to and including 5).*

But that's not exactly true. If Math.random results '1', then 1*5 = 5, and 5+1 = 6 (and flooring will result the same). So damageThisRound will be a number between 1 and 6, included (not only 1 to 5). Isn't it?

#7

No. `Math.random()` returns a random number between 0 (inclusive) and 1 (exclusive).

#8

Oh, thanks. I didn't notice that 1 was excluded.

I understand now.

#9

It's my understanding that Math.floor will always round down. That is how you do not end up with a value between 1 and 6, instead a value between 1 and 5 with the statement "var damageThisRound = Math.floor(Math.random()* 5 + 1);"