Modifying damageThisRound so total damage cannot exceed dragon's health (4)


#1



I'm not having any issues with my code, it runs, but it could perhaps be written more concisely . I expanded the code with a switch statement inside the while loop so to ensure totalDamage did not exceed the dragon's health, like in a video game, when you can't hit more damage than the enemy has health. I've made a variable so the dragon's health can be easily changed - dragonHealth. My question is, how can I improve the code to cater for changes in the dragon's health? For example , say the dragon has 100 health. Is there a quick way to code for this without having to write switch cases all the way up to 100? Like if you created a game with all sorts of enemies with different health values there must surely be a shortcut? A function or something?


//      DRAGON SLAYER

function randomGen(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
var slaying = 1;
var youHit = randomGen(0,2);
var totalDamage = 0;
var damageOnHit = 0;
var dragonHealth = 5;

while (slaying) {
    if (youHit >= 1) {
        switch (totalDamage) {
            case 0:
                damageOnHit = randomGen(1,5);
                break;
            case 1:
                damageOnHit = randomGen(1,4);
                break;
            case 2:
                damageOnHit = randomGen(1,3);
                break;
            case 3:
                damageOnHit = randomGen(1,2);
                break;
            case 4:
                damageOnHit = 1;
                break;
        }
        console.log("You hit the dragon and did " + damageOnHit + " damage!");
        totalDamage += damageOnHit;
        if (totalDamage === dragonHealth) {
            console.log("Congratulations! You slew the dragon! What a boss!");
            slaying = 0;
        } else {
            youHit = randomGen(0,2);
        } 
    } else {
        console.log("Oh no! You miss the dragon and are incinerated by its fiery breath!");
        slaying = 0;
    }
}


#2

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.