0

我刚开始学习 JS,我写了一段石头剪刀布游戏的代码。所以我在接下来的步骤中遇到了麻烦:如果第一次用户的选择和计算机的选择相同 - 功能再次启动。但是第二次用户的选择是什么并不重要,因为程序使用第一次的值输入而忽略了第二次。请解释我的错误在哪里。代码如下。

function compare(choice1,choice2) {
  choice1=prompt("Make your choice!");
  console.log("You're choosing "+choice1);

  choice2=Math.random();
  console.log("Computer rolls the dice and the result is "+choice2);

  if (choice2 < 0.333) {
    choice2="rock";
  } else if (choice2 < 0.666) {
    choice2="paper";
  } else {
    choice2="scissors";
  }

  console.log("That means "+choice2+".");
  if (choice1===choice2) {
    console.log("Ooops!Tie!");
    compare();
  }
  if(choice1==="rock") {
    if(choice2==="scissors"){
        return("Your rock wins");
    } else {
        return("Computer's paper wins");
    }  
  } else if (choice1==="paper") {
    if(choice2==="rock") {
        return("Your paper wins");
    } else {
        return("Computer's scissors wins");
    }
  } else if (choice1==="scissors") {
    if(choice2==="rock") {
        return("Computer's rock wins");
    } else {
        return("Your scissors wins");
    }
  } else {
    return("Nice try smirky!");
  }
}
compare(); 
4

2 回答 2

2

我对全局变量的评论并不真正成立,因为我错过了您将它们声明为参数,这确实在本地范围内创建它们。它实际上并没有创建全局,但您仍应删除参数并使用var.

无论我打多少次电话compare或打成平手,我每次都会得到适当的回应。

你想要改变的是你的变量分配:

choice1=prompt("Make your choice!");生成 的全局变量choice1,而

var choice1=prompt("Make your choice!");在函数的“范围”中创建一个局部变量,即每次运行时都隔离。

您需要添加var初始化变量的时间(第一次分配它)。这似乎不会导致您的错误,但无论如何都是一个好习惯。

此外,compare()如果出现平局,您的调用不会返回结果。您应该确保它也返回:

if (choice1===choice2) {
    console.log("Ooops!Tie!");
    return compare();
}

这也可以防止您返回“Nice try smirky!” 在平局的情况下,因为这是return它遇到的第一个语句。

于 2013-09-02T15:10:57.773 回答
0

构建代码的更好方法是这样的:

var choices = ['rock', 'paper', 'scissors']
function startGame(){
    var choiceHuman = prompt('Make your choice!');
    var choiceComp = choices[Math.floor(Math.random() * 3)];
    console.log(determineResult(choiceHuman, choiceComp));
}
function determineResult(choiceHuman, choiceComp){
    if (choiceHuman === choiceComp){
        return 'Ooops!Tie!';
    } else if (choiceHuman === 'rock') {
        if (choiceComp === "scissors") {
            return("Your rock wins");
        } else {
            return("Computer's paper wins");
        }
    } else if (choiceHuman === "paper") {
        if (choiceComp === "rock") {
            return("Your paper wins");
        } else {
            return("Computer's scissors wins");
        }
    } else if (choiceHuman === "scissors") {
        if (choiceComp === "rock") {
            return("Computer's rock wins");
        } else {
            return("Your scissors wins");
        }
    } else {
        return("Nice try smirky!");
    }
}
var userInput = true;
while(userInput) {
    startGame();
    userInput = prompt('Play again? (Y/N)') === 'y';
}

对 compare() 的递归调用没有任何目的,它会阻止内存被释放。诚然,对于这个示例,您可能永远不会为此惹上麻烦,但对于更复杂的情况,它最终可能会损害您的性能。

于 2013-09-02T15:12:41.260 回答