// answer to http://codereview.stackexchange.com/questions/90669/dragon-slayer-game-in-javascript#90669
Slaying dragons... That's the kind of code review I just can't say no to...
So, essentially, we have this logic:
- Setup:
youHitis set to 0 or 1 randomlydamageThisRoundis set to 1, 2, 3, 4, 5 randomly
- Play one game round:
- If
youHitis 0 at any time, you die - If
youHitis 1, you do some damage (always the same damage)- If the total damage reaches 4, the dragon dies
- Otherwise update
youHitand play another round
- If
A few improvement ideas:
-
The
slayingvariable is not really great. The name is not great and you don't really need it. When the game is over, you can break out of the loop without the extra variable. -
The logic of calculating
youHitis duplicated. It would be better to write it once, in a function. The name is not so great either, and you don't actually need a variable, you could use the function directly. -
damageThisRoundis a misleading name. It suggests a different damage per round, but it's actually the same every round. -
The indentation is off in the middle of the loop
-
The health of the dragon hardcoded as 4 is not great. It would be better to put that in a variable. Actually, it's also strange to have a cumulative total damage. It would make more sense to have decreasing health.
Putting it together:
function hit() {
return Math.floor(Math.random() * 2);
}
var damagePerRound = Math.floor(Math.random() * 5 + 1)
var healthOfDragon = 4;
while (true) {
if (hit()) {
confirm("Congratulations, you hit, dealing " + damagePerRound + " damage!");
healthOfDragon -= damageThisRound;
if (healthOfDragon <= 0) {
confirm("You slew the dragon!");
break;
}
} else {
confirm("Unlucky, you were slain by the dragon!");
break;
}
}