Greetings and thank you in advance for any help or guidance.
I am currently developing a Space Battle game and I am curious to know if there is a way to utilize a JavaScript SWITCH case statement to streamline the numerous If/Else statements that are currently in my code.
I am unsure where to start with the switch (expression)
.
Would it be appropriate to implement a switch (expression)
in this program?
// Implementing the Battle Function to manage the battle process
let shipsBattle = (ship1, ship2) => {
let ships = [ship1, ship2]; // storing the ships in an array
let attack = false;
let attacking = 0;
let beingAttacked = 1;
let temp;
console.log("%c Attack Begins =================", "font-size: 30px");
while (ships[beingAttacked].hull > 0) { //Keep attacking as long as the hull is above 0
// Execution of the attack
if (ships[beingAttacked].hull > 0) {
console.log("\n"); // Display attack information on the console
console.log(
`%c ${ships[attacking].name} attacked ${ships[beingAttacked].name}`,
"color: purple; border: 1px solid grey; font-size: 18px;"
);
attack = ships[attacking].attack(); // Initiate attack on enemy ship
if (attack === true) {
ships[beingAttacked].hull -= ships[attacking].firePower; //Increase Fire power
console.log(
`%c Attack Successful! ${ships[beingAttacked].name} Hull: ${ships[beingAttacked].hull}`,
"color: green; font-weight: bold; font-size: 16px;"
);
} else {
console.log(
`%c Attack Unsuccessful! ${ships[beingAttacked].name} Hull: ${ships[beingAttacked].hull}`,
"color: red; font-size: 16px;"
);
}
if (ships[beingAttacked].hull <= 0) { // Verify if the ship being attacked is destroyed
console.log(
`%c ${ships[beingAttacked].name} has been destroyed`,
"color: red; border: 1px solid grey; font-size: 16px;"
);
if (ships[beingAttacked] === ussSchwartz) {
alert("Game Over!!!"); //Notify player of Game Over when USS Ship is destroyed
} else if (
ships[beingAttacked].name === alienShips[alienShips.length - 1].name
) {
alert(
`%c ${ships[beingAttacked].name} destroyed!\nAlien fleet has been destroyed!\nyou have been victorious`,
"color: green;"
);
} //Inform player of victory if USS destroys alien fleet
else {
game.userResponse = prompt(
`${alienShips[game.targetShip].name} destroyed!!\n${
ussSchwartz.name
} Hull: ${
ussSchwartz.hull
}\nWould you like to ATTACK the next ship or RETREAT from battle?`,
""
);
game.targetShip += 1; //Prompt player to continue or retreat
checkUserPrompt();
return;
}
} else {
temp = attacking; // Switch attacking/attacked ships
attacking = beingAttacked;
beingAttacked = temp;
}
}
}
};