Javascript 岩石剪刀
为什么我的程序不起作用 我的数学有问题吗 你选择石头、布还是剪刀 你选择石头、布还是剪刀 你选择石头、布还是剪刀 //////////////////////////////Javascript 岩石剪刀,javascript,if-statement,Javascript,If Statement,为什么我的程序不起作用 我的数学有问题吗 你选择石头、布还是剪刀 你选择石头、布还是剪刀 你选择石头、布还是剪刀 ////////////////////////////// var userChoice = prompt("Do you choose Rock, Paper or Scissors?") var computerChoice = Math.random(); //====================================== if(computerChoic
var userChoice = prompt("Do you choose Rock, Paper or Scissors?")
var computerChoice = Math.random();
//======================================
if(computerChoice <= 0.33 )
{
computerChoice = "Rock";
}
else if(computerChoice <= 0.66)
{
computerChoice = "Paper";
}
else
{
computerChoice = "Scissors";
}
console.log("Computer: " + computerChoice);
//==========================================
var compare = function(choice1, choice2)
{
if(choice1 === choice2)
{
return "The result is a tie!";
}
else if(choice1 === "Rock")
{
if(choice2 === "Scissors")
{
return "Rock wins";
}
else
{
return "Paper wins";
}
}
else if(choice1 === "Paper")
{
if(choice2 === "Rock")
{
return "Paper wins";
}
else
{
return "Scissors wins";
}
}
else if(choice1 === "Scissors")
{
if(choice2 === "Paper")
{
return "Scissors wins";
}
else
{
return "Rock wins";
}
}
};
compare();
您在调用compare时没有任何参数。你需要像compareuserChoice、computerChoice这样的东西。我觉得你的逻辑太复杂了。如果您通过将可能的选择和它们击败的事物组合成一个关联数组来简化,您可以简化许多逻辑,如下所示:
var userChoice = prompt("Do you choose Rock, Paper, or Scissors?");
userChoice = userChoice.toLowerCase();
var rules = {'rock': 'scissors', 'paper': 'rock', 'scissors': 'paper'};
var choices = Object.keys(rules);
var computerChoice = choices[Math.floor(Math.random() * 3)];
// User entered an invalid option
if (choices.indexOf(userChoice) < 0) {
console.log('You entered an invalid choice');
} else if (userChoice === computerChoice) {
console.log('Tie!!');
} else {
// now actually see who won
var userBeats = rules[userChoice];
if (userBeats === computerChoice) {
console.log('User won with ' + userChoice + ' vs ' + computerChoice);
} else {
console.log('Computer won with ' + computerChoice + ' vs ' + userChoice);
}
}
当然,您仍然可以将事物划分为函数
另一个简单的方法是Math.floorMath.random*3将产生一个介于0和2之间(包括0和2)的数字,因此您可以使用该数字访问选项数组中的选项,并跳过大部分赋值逻辑