// 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:
youHit
is set to 0 or 1 randomlydamageThisRound
is set to 1, 2, 3, 4, 5 randomly
- Play one game round:
- If
youHit
is 0 at any time, you die - If
youHit
is 1, you do some damage (always the same damage)- If the total damage reaches 4, the dragon dies
- Otherwise update
youHit
and play another round
- If
A few improvement ideas:
-
The
slaying
variable 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
youHit
is 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. -
damageThisRound
is 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;
}
}