0

我是js新手,我只是根据石头剪刀布游戏写了下面的基本功能。由于某种原因,比较函数的结果总是显示为“平局”而不是其他结果。我在这里做错了什么?

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

choice1 = userChoice;
choice2 = computerChoice;

var compare = function (choice1, choice2) {
if (choice1 == choice2) {
        return "draw!";
}

if (choice1 == "rock") {
    if (choice2 == "scissors") {
        return "rock wins!";
    } else {
        return "paper wins!";
    }
}

if (choice1 == "paper") {
    if (choice2 == "scissors") {
        return "scissors wins!";
    } else {
        return "paper wins!";
    }
}

    if (choice1 == "scissors") {
        if (choice2 == "rock") {
            return "rock wins!";
        } else {
            return "scissors wins!";
        }
    }
};

compare();

谢谢,我们

4

3 回答 3

4

您正在调用不带参数的比较:

compare();

因此choice1choice2两者都相等undefined,您的游戏将始终以平局告终。您应该尝试像这样调用您的比较函数:

compare(userChoice, computerChoice);

如果定义函数,参数列表定义函数范围给定变量的名称。这不是函数本身应该可用的变量的命名约定。

于 2013-06-24T10:12:41.223 回答
0

您已经使用两个参数定义了函数:

var compare = function (choice1, choice2) 

但是你已经用 0 调用了它。

尝试指定选项:

compare("rock", "paper");
于 2013-06-24T10:11:23.617 回答
0

您不能仅通过键入不带参数的 func_name() 来打开功能,就像“干炮”一样。阅读函数声明

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";
}
choice1 = userChoice;
choice2 = computerChoice;
function compare (choice1, choice2) {
  if (choice1 == choice2) {
    return "draw!";
  };
  if (choice1 == "rock") {
    if (choice2 == "scissors") {
      return "rock wins!";
    } else {
      return "paper wins!";
    }
  }
  if (choice1 == "paper") {
    if (choice2 == "scissors") {
      return "scissors wins!";
    } else {
      return "paper wins!";
    }
  }
  if (choice1 == "scissors") {
    if (choice2 == "rock") {
      return "rock wins!";
    } else {
      return "scissors wins!";
    }
  }
};
compare(choice1, choice2);
于 2013-06-24T10:22:51.540 回答