石头剪刀布更高效的选择比较

2023-11-22

这是一个正在进行的学校项目,我想改进。重点是使代码尽可能高效(或简短)。在将计算机的选择与用户的选择进行比较时,我想通过找到所有其他条件的替代方案来减少它。

这是代码:

let weapons = ["Rock", "Paper", "Scissors"];
let random = Math.floor(Math.random()*3);
let chosenOne = weapons[random];

let rps = prompt("Welcome to Rock, Paper, Scissors. Would you like to play?" 
+ '\n' + "If you do, enter number 1." + '\n' + "If you don't, enter number 
2.");

if (rps === "1") {
    alert("Remember:" + '\n' + " - Rock beats the scissors" + '\n' + " - 
    Paper beats the rock" + '\n' + " - The scissors cut the paper");

let weapon = prompt("Make your choice:" + '\n' + "Rock, Paper, Scissors");
    weapon = weapon.charAt(0).toUpperCase() + weapon.slice(1).toLowerCase();
    alert("You chose: " + weapon + '\n' + "The computer chose: " + 
    chosenOne);
if (weapon === chosenOne) {
        alert("It's a tie! Try again to win!");
    } else if (weapon === "Rock" && chosenOne === "Paper") {
        alert("You lost! Paper beats the rock.");
    } else if (weapon === "Paper" && chosenOne === "Scissors") {
        alert("You lost! The scissors cut the paper.");
    } else if (weapon === "Scissors" && chosenOne === "Rock") {
        alert("You lost! The rock beats the scissors.");
    } else if (weapon === "Scissors" && chosenOne === "Paper") {
        alert("You won! Scissors cut the paper.");
    } else if (weapon === "Paper" && chosenOne === "Rock") {
        alert("You won! Paper beats the rock.");
    } else if (weapon === "Rock" && chosenOne === "Scissors") {
        alert("You won! The rock beats the scissors.");
    }
} else if (rps === "2") {
    alert("Thanks for visiting! See you later.");
} else if (rps !== "1" || rps !== "2") {
    alert("Invalid option. Closing game.");
}

我曾考虑过使用 switch 语句,但由于我们还是初学者,所以我还没有完全掌握这个主题。任何帮助表示赞赏。


您可以定义一个对象来定义您的动作相对于另一个动作是弱还是强。例子:

const myChoice = 'Rock'
const enemyChoice = 'Scissors' 

const weapons = {
   Rock: {weakTo: 'Paper', strongTo: 'Scissors'},
   Paper: {weakTo: 'Scissors', strongTo: 'Rock'},
   Scissors: {weakTo: 'Rock', strongTo: 'Paper'}
}

if (weapons[myChoice].strongTo === enemyChoice) {
    // I won
    return;
}

if (weapons[myChoice].weakTo === enemyChoice) {
    // I Lost
    return;
}

// tie
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

石头剪刀布更高效的选择比较 的相关文章

随机推荐