我怎样才能删除这些全局变量并在它们发生时显示增量?

How can I remove these global variables and show the increments as they happen?

我不知道如何在不使用这两个全局变量 computerScoreplayerScore 的情况下 运行 这段代码。如果我在函数中声明它们,则每次 运行s 时值都会重置为 0。

还有,如何显示return时的增量?就目前而言,这些值仅在再次调用该函数后才会更新。

const getPlayerChoice = (userChoice) => {
    userChoice = userChoice.toLowerCase();
    if (
        userChoice === "rock" ||
        userChoice === "paper" ||
        userChoice === "scissor"
    ) {
        return userChoice;
    } else {
        console.log("Invalid option.");
    }
};

const computerPlay = () => {
    let randomNumber = Math.floor(Math.random() * 3);
    if (randomNumber === 0) {
        return "scissor";
    } else if (randomNumber === 1) {
        return "rock";
    } else if (randomNumber === 2) {
        return "paper";
    }
};
let computerScore = 0;
let playerScore = 0;
let tie = 0;

const playRound = (playerSelection, computerSelection) => {
    playerSelection = playerSelection.toLowerCase();

    let currentScores =
        "Computer: " +
        computerScore +
        " Player: " +
        playerScore +
        " Tie: " +
        tie;

    if (playerSelection.toLowerCase() === computerSelection) {
        ++tie;
        return "It's a tie\n" + currentScores;
    }

    if (playerSelection.toLowerCase() === "scissor") {
        if (computerSelection === "rock") {
            ++computerScore;
            return "Computer wins!\n" + currentScores;
        } else {
            ++playerScore;
            return "You win!\n" + currentScores;
        }
    }

    if (playerSelection.toLowerCase() === "paper") {
        if (computerSelection === "scissor") {
            ++computerScore;
            return "Computer wins!\n" + currentScores;
        } else {
            ++playerScore;
            return "You win!\n" + currentScores;
        }
    }

    if (playerSelection.toLowerCase() === "rock") {
        if (computerSelection === "paper") {
            ++computerScore;
            return "Computer wins!\n" + currentScores;
        } else {
            ++playerScore;
            return "You win!\n" + currentScores;
        }
    }
};

const game = () => {
    for (let i = 0; i < 5; ++i) {
        let playerSelection = getPlayerChoice(
            prompt("Choose between rock, paper, scissor")
        );
        if (playerSelection == null) {
            alert("Invalid. Try again.");
            --i;
            continue;
        }
        const computerSelection = computerPlay();
        console.log(`You chose: ${playerSelection.toLowerCase()}`);
        console.log(`Computer chose: ${computerSelection}`);
        console.log(
            playRound(playerSelection.toLowerCase(), computerSelection)
        );
    }
    if (playerScore > computerScore) {
        console.log("Congratulations! You beat the Computer!");
    } else if (computerScore > playerScore) {
        console.log("Sorry! You lost.");
    } else {
        console.log("You tied with the Computer.");
    }
};

game();

首先,不要硬核数字,在你的for循环中使用变量。使用 var 而不是 let。 Var 在整个程序中都有定义。我明白你的问题了。您当前的分数没有更新。相反,使当前分数成为一个函数,该函数将 return 当前玩家分数和计算机分数。

Return 一个包含谁获胜的对象,并从您的 computerWins 和 playerWins 函数打印获胜消息。传入当前分数,以便您可以打印它,但可以在 game() 函数中跟踪它。这是没有全局变量的工作和测试代码

    const getPlayerChoice = userChoice => {
        const lowercaseChoice = userChoice.toLowerCase();
        const options = ['rock', 'paper', 'scissor'];
        if (options.includes(lowercaseChoice)) {
            return userChoice;
        } else {
            console.log('Invalid option.');
        }
    };

    const computerPlay = () => {
        let randomNumber = Math.floor(Math.random() * 3);

        if (randomNumber === 0) {
            return 'scissor';
        } else if (randomNumber === 1) {
            return 'rock';
        } else if (randomNumber === 2) {
            return 'paper';
        }
    };

    const computerWins = (totalComputerScore, totalPlayerScore) => {
        totalComputerScore += 1;
        console.log(`Computer wins!\nComputer: ${totalComputerScore} Player: ${totalPlayerScore}`);
        return {playerScore: totalPlayerScore, computerScore: totalComputerScore};
    };

    const playerWins = (totalComputerScore, totalPlayerScore) => {
        totalPlayerScore += 1;
        console.log(`You win!\nComputer: ${totalComputerScore} Player: ${totalPlayerScore}`);
        return {playerScore: totalPlayerScore, computerScore: totalComputerScore};
    };

    const tie = (totalComputerScore, totalPlayerScore) => {
        console.log(`It's a tie\nComputer: ${totalComputerScore} Player: ${totalPlayerScore}`);
        return {playerScore: totalPlayerScore, computerScore: totalComputerScore};
    };

    const playRound = (playerSelection, computerSelection, totalComputerScore, totalPlayerScore) => {
        const lowerCasePlayer = playerSelection.toLowerCase();

        if (lowerCasePlayer === 'scissor') {
            if (computerSelection === 'rock') {
                return computerWins(totalComputerScore, totalPlayerScore);
            } else if(computerSelection !== 'scissor') {
                return playerWins(totalComputerScore, totalPlayerScore);
            } else {
                return tie(totalComputerScore, totalPlayerScore);
            }
        }

        if (lowerCasePlayer === 'paper') {
            if (computerSelection === 'scissor') {
                return computerWins(totalComputerScore, totalPlayerScore);
            } else if(computerSelection !== 'paper') {
                return playerWins(totalComputerScore, totalPlayerScore);
            } else {
                return tie(totalComputerScore, totalPlayerScore);
            }
        }

        if (lowerCasePlayer === 'rock') {
            if (computerSelection === 'paper') {
                return computerWins(totalComputerScore, totalPlayerScore);
            } else if (computerSelection !== 'rock') {
                return playerWins(totalComputerScore, totalPlayerScore);
            } else {
                return tie(totalComputerScore, totalPlayerScore);
            }
        }
    };

    const game = () => {
        let totalPlayerScore = 0;
        let totalComputerScore = 0;

        for (let i = 0; i < 5; ++i) {
            let playerSelection = getPlayerChoice(
                prompt('Choose between rock, paper, scissor')
            );
            if (playerSelection == null) {
                alert('Invalid. Try again.');
                --i;
                continue;
            }
            const computerSelection = computerPlay();

            console.log(`You chose: ${playerSelection.toLowerCase()}`);
            console.log(`Computer chose: ${computerSelection}`);
            const scores = playRound(playerSelection.toLowerCase(), computerSelection, totalComputerScore, totalPlayerScore);
            totalPlayerScore = scores.playerScore;
            totalComputerScore = scores.computerScore;

        }
        if (totalPlayerScore > totalComputerScore) {
            console.log('Congratulations! You beat the Computer!');
        } else if (totalComputerScore > totalPlayerScore) {
            console.log('Sorry! You lost.');
        } else {
            console.log('You tied with the Computer.');
        }
    };
    game();

您好,我对您的代码进行了一些重构,这些是一些建议:

  1. 在不需要重新分配的变量中使用 const,例如 currentScores。
  2. 不要重新分配函数参数值,而是使用修改后的值创建一个新变量。
  3. 不要重复自己,例如,playerSelection 多次与 toLowerCase() 一起使用,您可以将此值以小写形式保存在变量中
  4. 使用模板文字而不是 + 来连接变量和字符串
  5. 由于您将使用此脚本中封装的变量,因此全局使用它不是问题,而且脚本中的所有方法都使用此变量,如果出于某种原因您需要将其放在一个具体作用域,可以用一个IIFE https://developer.mozilla.org/en-US/docs/Glossary/IIFE

// Rock paper or Scissors code

(function rockPaperOrScissors() {
  let computerScore = 0;
  let playerScore = 0;

  const getPlayerChoice = userChoice => {
    const lowercaseChoice = userChoice.toLowerCase();
    const options = ["rock", "paper", "scissor"];
    if (options.includes(lowercaseChoice)) {
      return userChoice;
    } else {
      console.log("Invalid option.");
    }
  };

  const computerPlay = () => {
    let randomNumber = Math.floor(Math.random() * 3);

    if (randomNumber === 0) {
      return "scissor";
    } else if (randomNumber === 1) {
      return "rock";
    } else if (randomNumber === 2) {
      return "paper";
    }
  };

  const setComputerWinner = () => {
    computerScore += 1;
    const computerWinsText = `Computer wins!\nComputer: ${computerScore} Player: ${playerScore}`;

    return computerWinsText;
  };

  const setHumanWinner = () => {
    playerScore += 1;
    const humanWinsText = `You win!\nComputer: ${computerScore} Player: ${playerScore}`;

    return humanWinsText;
  };

  const playRound = (playerSelection, computerSelection) => {
    const lowerCasePlayer = playerSelection.toLowerCase();

    const tieText = `It's a tie\nComputer: ${computerScore} Player: ${playerScore}`;

    if (lowerCasePlayer === computerSelection) {
      return tieText;
    }

    if (lowerCasePlayer === "scissor") {
      if (computerSelection === "rock") {
        return setComputerWinner();
      } else {
        return setHumanWinner();
      }
    }

    if (lowerCasePlayer === "paper") {
      if (computerSelection === "scissor") {
        return setComputerWinner();
      } else {
        return setHumanWinner();
      }
    }

    if (lowerCasePlayer === "rock") {
      if (computerSelection === "paper") {
        return setComputerWinner();
      } else {
        return setHumanWinner();
      }
    }
  };

  const game = () => {
    for (let i = 0; i < 5; ++i) {
      let playerSelection = getPlayerChoice(
        prompt("Choose between rock, paper, scissor")
      );
      if (playerSelection == null) {
        alert("Invalid. Try again.");
        --i;
        continue;
      }
      const computerSelection = computerPlay();

      console.log(`You chose: ${playerSelection.toLowerCase()}`);
      console.log(`Computer chose: ${computerSelection}`);
      console.log(playRound(playerSelection.toLowerCase(), computerSelection));
    }
    if (playerScore > computerScore) {
      console.log("Congratulations! You beat the Computer!");
    } else if (computerScore > playerScore) {
      console.log("Sorry! You lost.");
    } else {
      console.log("You tied with the Computer.");
    }
  };
  game();
})();