Javascript岩石,纸,剪刀游戏

Javascript Rock, Paper, Scissors game

本文关键字:游戏 岩石 Javascript      更新时间:2023-09-26

我一直在用JavaScript开发这个Rochabeau游戏,到目前为止,当我运行它时,它会提示用户输入,但无论你输入什么,结果总是平局。这是我的代码:

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
} console.log("Computer: " + computerChoice);
function compare(userChoice, computerChoice){
    if(userChoice === computerChoice){
        alert("The result is a tie!");
    }
    else if(computerChoice === "scissors"){
        alert("rock wins!");
        if(computerChoice === "paper"){
            alert("paper wins!");
            }
        }
    else if(computerChoice === "rock"){
        alert("rock wins!");
        if(computerChoice === "scissors"){
            alert("scissor wins!");
            }
        }
    else if(computerChoice === "rock"){
        alert("rock wins!");
        if(computerChoice === "paper"){
            alert("scissors wins!");
            }
        }
}
compare();

知道为什么这不符合其他条件吗?

您没有向函数传递任何参数。函数中的参数将默认为undefined。所以undefined === undefined等于真。你应该这样做:

compare(userChoice, computerChoice);

compare();

你没有遗漏参数吗?