if 语句 - Javascript 石头剪刀布

if statement - Javascript Rock Paper Scissors

本文关键字:石头剪刀布 Javascript 语句 if      更新时间:2023-09-26

为什么我的程序不起作用?

我的Math.random有问题吗?

"你选择石头、纸还是剪刀?"

"你选择石头、纸还是剪刀?"

"你选择石头、纸还是剪刀?"

//

/

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()。你需要像compare(userChoice, 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.floor(Math.random() * 3)将产生一个介于 0 和 2(含)之间的数字,因此您可以使用它来访问 choices 数组中的选择并跳过大部分赋值逻辑。