Javascript岩石剪刀

时间:2016-07-12 14:54:57

标签: javascript if-statement

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

我的Math.random有问题吗?

"你选择Rock,Paper还是Scissors?"

"你选择Rock,Paper还是Scissors?"

"你选择Rock,Paper还是Scissors?"

//////////////////////////////

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();

2 个答案:

答案 0 :(得分:1)

你在没有任何争论的情况下调用compare()。您需要compare(userChoice, computerChoice)

之类的内容

答案 1 :(得分:0)

我认为你的整体逻辑过于复杂。如果通过创建可能选择的关联数组和它们击败的东西来简化,您可以简化许多逻辑,如下所示:

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);
  }
}

Working fiddle

当然,您仍然可以将功能分开。

让事情变得简单的另一件事是Math.floor(Math.random() * 3)将产生0到2之间的数字(包括),因此您可以使用它来访问choices数组中的选项并跳过大部分你的任务逻辑。