malty-ale
malty-ale

Reputation: 21

For loop vs. while loop in Javascript

Complete beginner here...

Working through an online example of a mindless probability 'game' where the user kills a dragon or gets eaten. I know the game works using a while loop, so I tried replicating it with a for loop but failed. I'm curious primarily why the for loop isn't working and if there's some obvious reason this needs to be completed using a while loop.

Below is the working example with a while loop to give context.

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 the dragon and did " + damageThisRound + " damage!");
    totalDamage += damageThisRound;

    if (totalDamage >= 4) {
      console.log("You did it! You slew the dragon!");
      slaying = false;
    } else {
      youHit = Math.floor(Math.random() * 2);
    }
  } else {
    console.log("The dragon burninates you! You're toast.");
    slaying = false;
  }
}

And here is the not working for loop.

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

for(totalDamage=0;totalDamage>3;totalDamage+=damageThisRound){
    if(youHit){
        console.log("You hit and did "+damageThisRound);
        totalDamage += damageThisRound;

        if(totalDamage>3){
            console.log("You did it! You slew the dragon!");
        } else {
            youHit = Math.floor(Math.random() * 2);
        }
    } else {
        console.log("The dragon kills you");
    }
}

Thanks

Upvotes: 1

Views: 464

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

Your loop condition is the problem

var youHit, damageThisRound;
for (var totalDamage = 0; totalDamage < 4; totalDamage += damageThisRound) {
  youHit = Math.floor(Math.random() * 2);
  if (youHit) {
    //need to calculare the damage in each loop
    damageThisRound = Math.floor(Math.random() * 5 + 1);
    snippet.log("You hit and did " + damageThisRound);

  } else {
    snippet.log("The dragon kills you");
    //you need to stop the loop here
    break;
  }
}
//need this outside of the loop since the increment is in the for loop block
if (youHit) {
  snippet.log("You did it! You slew the dragon!");
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Upvotes: 1

user1823
user1823

Reputation: 1111

In your for loop, you set totalDamage to 0, and then you call totalDamage > 3. Instead, change the for loop to

for(totalDamage=0;totalDamage<3;totalDamage+=damageThisRound){

In other words, you switched a sign around, because you are setting a variable to 0 and then only proceeding when the variable is greater than 3.

Upvotes: 1

Related Questions