gpt4 book ai didi

javascript - 基本 JavaScript 石头剪刀布游戏无法正常运行

转载 作者:行者123 更新时间:2023-11-28 20:24:27 25 4
gpt4 key购买 nike

我需要一些关于我正在开发的石头剪刀布的基本 JavaScript 版本的帮助。我今天刚刚开始学习,如果可能的话,希望尽可能保持代码完整。

我遇到的主要问题是循环。尽管我将“再次”设置为“否”(通过提示),它仍然继续。另外,计算机似乎总是选择 Rock...我有一种感觉,我只是错过了一些简单的东西:

<html>
<script type="text/javascript">
var myChoice = "";
var compChoice = "";
var again;
while (again = "yes")
{
myChoice = prompt("Do you choose rock, paper or scissors?");
compChoice = Math.random();
if (compChoice < 0.33)
{
compChoice = "rock";
}
else if(compChoice < 0.67)
{
compChoice = "paper";
}
else
{
compChoice = "scissors";
}
if (compChoice = myChoice)
{
alert("It's a tie!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (compChoice = "rock")
{
if(myChoice = "scissors")
{
alert("You lose!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (myChoice = "paper")
{
alert("You win!");
again = prompt("Would you like to play again?(yes/no)");
}
}
else if (compChoice = "paper")
{
if (myChoice = "rock")
{
alert("You lose!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (myChoice = "scissors")
{
alert("You win!");
again = prompt("Would you like to play again?(yes/no)");
}
}
else if (compChoice = "scissors")
{
if (myChoice = "rock")
{
alert("You win!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (myChoice = "paper")
{
alert("You lose!");
again = prompt("Would you like to play again?(yes/no)");
}
}
};
</script>
</html>

最佳答案

您在 while 语句中使用 = 而不是 ==,在所有 if 语句中也是如此

= 是赋值运算符,而 == 是比较运算符

var myChoice = "";
var compChoice = "";
var again;
do
{
myChoice = prompt("Do you choose rock, paper or scissors?");
compChoice = Math.random();
if (compChoice < 0.33)
{
compChoice == "rock";
}
else if(compChoice < 0.67)
{
compChoice = "paper";
}
else
{
compChoice == "scissors";
}
if (compChoice == myChoice)
{
alert("It's a tie!");
}
else if (compChoice == "rock")
{
if(myChoice == "scissors")
{
alert("You lose!");
}
else if (myChoice == "paper")
{
alert("You win!");
}
}
else if (compChoice == "paper")
{
if (myChoice == "rock")
{
alert("You lose!");
}
else if (myChoice == "scissors")
{
alert("You win!");
}
}
else if (compChoice == "scissors")
{
if (myChoice == "rock")
{
alert("You win!");
}
else if (myChoice == "paper")
{
alert("You lose!");
}
}
again = prompt("Would you like to play again?(yes/no)");

}while (again == "yes");

演示:Fiddle

关于javascript - 基本 JavaScript 石头剪刀布游戏无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17646045/

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