更有效的岩石剪刀选择比较 [英] More efficient choice comparison for Rock Paper Scissors
本文介绍了更有效的岩石剪刀选择比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一个正在进行的学校项目,我想改进。关键是要使代码尽可能高效(或简短)。在将计算机的选择与用户的选择进行比较时,我希望通过找到所有其他ifs的替代方案来减少它。
This is an ongoing school project that I would like to improve. The point is to make the code as efficient (or short) as possible. I would like to reduce it by finding an alternative to all the else ifs when comparing the computer's choice with the user's choice.
以下是代码:
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语句,但由于我们还是初学者,我没有完全掌握这个主题。任何帮助都表示赞赏。
I have thought about using switch statements, but since we are still beginners, I haven't grasped the subject fully. Any help is appreciated.
推荐答案
您可以定义一个对象来定义您的移动是弱还是强。示例:
You can define an object that define if your move is weak or strong against another. Example:
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
这篇关于更有效的岩石剪刀选择比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文