Lesson 12 Challenge 2 Complete
by nathanesa
JavaScript
// Function to get damage from ogre's attack.
function getOgreAttack() {
var firstRoll = Math.floor(Math.random() * 6) + 1;
var damage;
if (firstRoll < 3) {
damage = 0;
} else {
damage = Math.floor(Math.random() * 6) + 1 + Math.floor(Math.random() * 6) + 1;
}
return damage;
}
// Function to get damage from player's attack.
function getPlayerAttack(lunge) {
var damage;
if (lunge == false) {
var firstRoll = Math.floor(Math.random() * 8) + 1;
if (firstRoll < 3) {
damage = 0;
} else if (firstRoll == 8) {
damage = 20;
} else {
damage = Math.floor(Math.random() * 5) + 1 + Math.floor(Math.random() * 5) + 1 + Math.floor(Math.random() * 5) + 1;
}
} else {
var firstRoll = Math.floor(Math.random() * 8) + 1
if (firstRoll < 4) {
damage = 0;
} else {
damage = Math.floor(Math.random() * 10) + 1 + Math.floor(Math.random() * 10) + 1 + Math.floor(Math.random() * 10) + 1;
}
}
return damage;
}
// Main program.
var playerHealth = 40;
var ogreHealth = 60;
while (playerHealth > 0 && ogreHealth > 0) {
// Do ogre's attack.
var ogreDamage = getOgreAttack();
alert('Ogre hits you for ' + ogreDamage + ' points.');
playerHealth = playerHealth - ogreDamage;
// Do player's attack.
if (playerHealth > 0) {
var response = prompt('Do you want to lunge? (Y/N)');
if (response == 'Y') {
var playerDamage = getPlayerAttack(true);
} else {
var playerDamage = getPlayerAttack(false);
}
alert('You hit Ogre for ' + playerDamage + ' points.');
ogreHealth = ogreHealth - playerDamage;
}
// Display current health.
alert('Ogre health points: ' + ogreHealth + ' Your health points: ' + playerHealth);
}
// Finally, declare the winner.
if (ogreHealth <= 0) {
alert('You defeated the ogre!');
} else {
alert('The ogre defeated you!');
}