繁体   English   中英

剪刀石头布游戏

[英]Rock paper, scissors game

我刚刚在codecademy上完成了一个rps游戏,还有一些额外的任务,其中包括如果用户输入了错误的信息则要产生结果。 基本上,如果您不输入“ rock”,“ paper”或“ scissors”的输入,它将再次询问您,直到您输入正确的输入为止。

我如何调用userChoice变量,直到得到正确的答案。 我这样尝试过,但是它只问了2次,然后发布了您所写的内容。

var userChoice = prompt("Do you choose rock, paper or scissors?");

if (userChoice != "rock", "paper", "scissors") {
    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";
}

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 === "rock") {
            return "rock wins";
        }
        else {
            return "scissors wins";    
        }
    }
}

console.log("Human: " + userChoice);
console.log("Computer: " + computerChoice);
compare(userChoice, computerChoice); 

使用引用自身的函数:

var userChoice = function () {
  var choice = prompt("Do you choose rock, paper or scissors?");

  if (choice !== "rock" && choice !== "paper" && choice !== "scissors") {
    return userChoice();
  } else {
    return choice;
  }
};

这个小提琴使整个事情起作用。

使用以下

do  {
    userChoice = prompt("Do you choose rock, paper or scissors?");
} while (userChoice != "rock", "paper", "scissors")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM