gpt4 book ai didi

javascript - 石头剪刀布游戏

转载 作者:行者123 更新时间:2023-12-03 08:12:09 25 4
gpt4 key购买 nike

我刚刚在 Codecademy 上制作了一款 rps 游戏,还有一些额外的任务,包括在用户输入错误信息时生成结果。基本上,如果您没有输入“石头”、“布”或“剪刀”,它会再次询问您,直到您输入正确的内容为止。

我如何调用 userChoice 变量,直到它得到正确的答案。我这样尝试过,但它只询问两次,然后发布你写的任何内容。

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

This fiddle一切正常。

关于javascript - 石头剪刀布游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34099370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com