有人可以帮我调试这个简单的剪刀石头布游戏吗?

我相信该错误与playgame()函数有关



function playgame() {
  let userChoice = prompt("Rock, Paper, or Scissors?").toUpperCase();
  let computerChoice = computerPlay();
  console.log(rpsgame(computerPlay, userChoice));
}

function computerPlay() {
  return Math.floor(Math.random() * (3) + 1);
  if (computerPlay == 1) {
    computerPlay = "ROCK";
  } else if (computerPlay == 2) {
    computerPlay = "PAPER";
  } else {
    computerPlay = "SCISSORS";
  }
}

最佳答案

return立即终止功能;您的computerPlay函数将永远不会超过第一行。而是,应将random调用放入变量中,然后返回ROCKPAPERSCISSORS。您也不应尝试将函数名称(computerPlay)重新分配给字符串。



function playgame() {
  let userChoice = prompt("Rock, Paper, or Scissors?").toUpperCase();
  let computerChoice = computerPlay();
  console.log(computerChoice);
}

function computerPlay() {
  const rnd = Math.floor(Math.random() * (3));
  if (rnd === 0) {
    return "ROCK";
  } else if (rnd === 1) {
    return "PAPER";
  } else {
    return "SCISSORS";
  }
}
playgame();





如果既要在playgame中使用随机数字索引又要在选项中使用名称,可以在computerPlay中立即返回所选的随机数,然后让playgame将其转换为名称。使用对象查找而不是if/else来简化描述:



function playgame() {
  const playNames = {
    0: 'ROCK',
    1: 'PAPER',
    2: 'SCISSORS'
  }
  let userChoice = prompt("Rock, Paper, or Scissors?").toUpperCase();
  let computerChoice = computerPlay();
  console.log(computerChoice + ' aka ' + playNames[computerChoice]);
}

function computerPlay() {
  return Math.floor(Math.random() * 3);
}
playgame();

10-02 00:19