如何删除这些全局变量并在发生增量时显示它们的增量?

问题描述 投票:0回答:3

我不知道如何在不使用这两个全局变量computerScoreplayerScore的情况下运行此代码。如果我在函数中声明它们,则每次运行时值都将重置为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();
javascript function arrow-functions
3个回答
1
投票

嗨,我在您的代码中做了一些重构,以下是一些建议:

  1. 在不需要重新分配的变量中使用const,例如currentScores。
  2. 不要重新分配函数参数值,而是使用修改后的值创建一个新变量。
  3. 例如,不要重复使用playerSelection和toLowerCase()多次,而是可以将此值保存在lowerCase中的变量中
  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();
})();

1
投票

返回赢家的对象,并从计算机的Wins和playerWins功能中打印赢消息。传递当前分数,以便您可以打印它但可以在game()功能中对其进行跟踪。这是工作和经过测试的代码,没有您的全局变量

(function rockPaperOrScissors() {
    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();
})();

0
投票

首先,请不要使用硬核数字,请在for循环中使用变量。使用var代替let。 Var在整个程序中定义。我明白你的问题。您当前的分数未更新。而是使当前分数成为可以返回当前玩家分数和计算机分数的函数。

© www.soinside.com 2019 - 2024. All rights reserved.