JavaScript | 자바스크립트 | 'WHILE' LOOPS IN JAVASCRIPT 둘

JavaScript | 자바스크립트 | 'WHILE' LOOPS IN JAVASCRIPT 둘

Dragon Slayer! | Codecademy
Let's use our knowledge of 'while' loops to defeat a dragon!


One. Putting an End to the Burnination 
1/6 What you'll be building
File1 _ script.js
var slaying = true;
// A bit of new math magic to calculate the odds
// of hitting the dragon. We'll cover this soon!
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;
  }
}

2/6 Declare your variables
File1 _ script.js
var slaying = true;
var youHIt = Math.floor(Math.random() * 2);
var damageThisRound = Math.floor(Math.random()*5 + 1);

var totalDamage = 0;

3/6 The 'while' loop
File1 _ script.js
var slaying = true;
var youHIt = Math.floor(Math.random() * 2);
var damageThisRound = Math.floor(Math.random()*5 + 1);
var totalDamage = 0;

while(slaying) {

    slaying = false;

}

4/6 The first 'if' statement
File1 _ script.js
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.");
    } else {
        console.log("The dragon defeated you.");
    }
    slaying = false;

}

5/6 The second 'if' statement
File1 _ script.js
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.");
        totalDamage += damageThisRound;
        if(totalDamage >= 4) {
            console.log("You Win!");
            slaying = false;
        } else {
            youHit = Math.floor(Math.random() * 2);
        }
    } else {
        console.log("The dragon defeated you.");
    }
    slaying = false;

}

6/6 Well done!
File1 _ script.js

Next Course: More on Control Flow in JS