# Slaying the Dragon: Question about math.random()

#1

Hi! I'm at the end of the Dragon Slayer! section, the one titled "Well Done!". I finished the excercise and decided to add in a few pieces of code in order to make you and dragon fight a longer battle, with the player and the dragon both having more health points and with the dragon fighting the same way you do (instead of just insta-killing you) by accumulating damage onto your character.

My question is: Every time I run it, the damage is the same for every interaction. I.e. when I hit "Save and Submit Code" everything runs great, but every loop does, for example, 4 damage for both the player and the dragon until one dies. If I run it again, the damage might be 3 instead, but it never changes from 3 until the end of the battle.

It looks something like this in the console display:

"You took 3 damage from the dragon, but survived.
You took 3 damage from the dragon, but survived.
You took 3 damage from the dragon, but survived.
Yeah! You hit the dragon for 3 damage!
You took 3 damage from the dragon, but survived.
Yeah! You hit the dragon for 3 damage!
The dragon crushed you after dealing 21 damage.
false"

``````Here is my code:

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("Yeah! You hit the dragon for " + damageThisRound + " damage!");
totalDamage += damageThisRound;

if (totalDamage >= 20) {
console.log("You slew the dragon by doing " + totalDamage + " damage!");
slaying = false;
} else {
youHit = Math.floor(Math.random() * 2);
}
} else {
totalDamage += damageThisRound;

if (totalDamage >= 18) {
console.log("The dragon crushed you after dealing " + totalDamage + " damage.");
slaying = false;
} else {
console.log("You took " + damageThisRound + " damage from the dragon, but survived.");
youHit = Math.floor(Math.random() * 2);
}
}
};.``````

Anyone have an idea for why the Math.random doesn't seem to be repeating its process every time it loops? Thanks!

#2

there is only one place you determine the damage for this round:

``var damageThisRound = Math.floor(Math.random() * 5 + 1);``

now this number is generated and fixed, until you generate a new number. So i would place this inside the loop:

``````while(slaying) {
var damageThisRound = Math.floor(Math.random() * 5 + 1);``````

this way damageThisRound is a random number every time the while loops run

#3

Ah! That makes perfect sense. When the loop runs, it no longer considers the variables at the top of the code, only what's within the loop, meaning anything run at the top is static for the rest of the iterations. Thanks!!!

#4

yes, you seem to understand. very good

#5