【发布时间】:2020-06-29 23:28:00
【问题描述】:
您好,提前感谢您提供的任何帮助或见解。
我正在开发一款 Space Battle 游戏,我想知道是否有办法使用 JavaScript SWITCH case 语句来替换我代码中的许多 If/Else 语句。
我不知道switch (expression) 从哪一行开始。 switch (expression) 适合这个程序吗?
// Battle Function = Set up a function that "Holds" the battle
let shipsBattle = (ship1, ship2) => {
let ships = [ship1, ship2]; // put the ships into 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) { //While the hull is greater than 0...Keep attacking
// Attacking Sequence
if (ships[beingAttacked].hull > 0) {
console.log("\n"); // Console log the attack information
console.log(
`%c ${ships[attacking].name} attacked ${ships[beingAttacked].name}`,
"color: purple; border: 1px solid grey; font-size: 18px;"
);
attack = ships[attacking].attack(); // Generate the attack on the 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) { // Check if the ship being attacked is still alive
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!!!"); //If the USS Ship is being attacked alert player Game is Over
} 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;"
);
} //If USS destroys alien fleet, then alert player of victory
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 IF THEY WANT TO CONTINUE OR RETREAT
checkUserPrompt();
return;
}
} else {
temp = attacking; // Change the attacking/attacked ships
attacking = beingAttacked;
beingAttacked = temp;
}
}
}
};
【问题讨论】:
-
switch仅适用于将相同表达式与不同值进行相等比较的情况。它对于大于/小于比较或测试不同的表达式没有用。我在这里看不到任何可以用开关代替的东西。
标签: javascript arrays if-statement switch-statement