I started to learn programming just a few days ago. And I've written code for a simple original game for practice, using some knowledge of JavaScript that I have gained so far.
Is the following code properly written? I'm especially concerned about the use of "Math.floor", "Math.random", "function", and "if / else".
Incidentally, "Metal King" is the name of a monster in the game, and "Angelo" is a character.
alert("Metal Kings (A, B, and C) have appeared!");
// Which Metal King (A, B, or C) will Angelo decide to attack? \
// 33% probability for each.
var MetalKingABC = 1 + Math.floor(Math.random() * 3);
if (MetalKingABC === 1) {
MetalKingABC = "Metal King A";
}
else if (MetalKingABC === 2) {
MetalKingABC = "Metal King B";
}
else {
MetalKingABC = "Metal King C";
}
var WhichOneToAttack = function(MonsterName) {
alert("Angelo is about to attack " + MonsterName + ".");
// Metal King has a 50% chance of fleeing the battle.
var FleeOrFight = 1 + Math.floor(Math.random() * 2);
if (FleeOrFight === 1) {
alert(MonsterName + " flees like lightning!");
// The battle ends here before Angelo attacks.
}
else // Metal King stays, and Angelo attacks.
{
// 70% chance of MISS, 20% of ONE damage, 10% of Critical.
var MissOneCritical = 1 + Math.floor(Math.random() * 10);
if (MissOneCritical <= 7) {
alert(MonsterName + " swiftly evades Angelo's attack.");
}
else if (MissOneCritical <= 9) {
alert("Angelo inflicts 1 point of damage on " + MonsterName + ".");
}
else {
// The damage dealt by a critical hit can range from 197 to 256 points.
var CriticalRange = 197 + Math.floor(Math.random() * 60);
alert("Angelo lands a critical hit on " + MonsterName + ", dealing massive \
damage of " + CriticalRange + " points! Angelo defeats " + MonsterName + ".");
// When defeated, Metal King drops a shield with an 80% probability.
var ShieldDrop = 1 + Math.floor(Math.random() * 10);
if (ShieldDrop <= 8) {
alert(MonsterName + " drops a shield. Angelo obtains a Diamond Shield!");
}
else {
// No code is written in this else portion, since Metal King didn't drop \
// any item.
}
}
}
};
// Finally, call the function.
WhichOneToAttack(MetalKingABC);
if
/else
, or that you're using them? \$\endgroup\$if
/else
statements are really common, and using lots is almost never a symptom of bad code. \$\endgroup\$