首页 > 解决方案 > 在 javascript Rock, Paper, Scissors Game 中记分有问题

问题描述

我一直试图弄清楚这一点,但没有骰子。我有一个名为的函数gameScore(),它应该跟踪玩家和计算机的得分,以及平局。我将分数定义为全局变量,因此从函数内部更新它们应该没有问题。

我的问题是,即使我在控制台中得到输出说谁赢了比赛,分数也没有更新,游戏无限期地继续下去。非常感谢任何帮助,我的代码如下。

let playerScore = 0;
let computerScore = 0;
let draws = 0;

//Computer choice
function computerPlay() {
  let random = Math.random();
  if (random <= 0.3333) {
    return "paper";
  } else if (random >= 0.6666) {
    return "rock";
  } else {
    return "scissors";
  }
}

//Plays one round of RPS
function playRound(playerChoice, computerSelection) {
  if (playerChoice === computerSelection) {
    return draw;
  } else if (playerChoice === "rock" && computerSelection === "scissors") {
    return playerWinRound;

  } else if (playerChoice === "paper" && computerSelection === "rock") {
    return playerWinRound;

  } else if (playerChoice === "scissors" && computerSelection === "paper") {
    return playerWinRound;

  } else {
    return computerWinRound;

  }
}

//Specifies round win/game win messages
let playerWinRound = "Player wins this round!"
let computerWinRound = "Computer wins this round!"
let draw = "Draw!"
let playerWin = "Player wins the game! Congratulations!"
let computerWin = "Computer wins the game! Congratulations!"


//For loop that plays multiple rounds
for (let i = 0; i < 1000; i++) {
  let playerChoice = prompt("Rock, paper, or scissors?").toLowerCase();
  const computerSelection = computerPlay();
  let roundResult = playRound(playerChoice, computerSelection);
  console.log(roundResult);
  gameScore(roundResult);
  console.log("Your score is " + playerScore);
  console.log("The computer's score is " + computerScore);

  if (playerScore === 5 || computerScore === 5) {
    break;
  }
}


//Keeps score and prints out correct messages based on score
function gameScore() {
  let result = playRound()

  if (result === playerWinRound) {
    playerScore++;
  } else if (result === draw) {
    draws++;
  } else {
    computerScore++;
  }


  if (playerScore === 5) {
    console.log(playerWin);
    return;
  }
  if (computerScore === 5) {
    console.log(computerWin);
    return;
  }
}

标签: javascriptfunction

解决方案


您已经有了这一轮的结果,并将其传递给gameScorewith gameScore(roundResult);,但是,您实际上并没有使用该参数,而是创建了另一轮:

 function gameScore() {
   let result = playRound()

相反,只需获取传递的结果:

function gameScore(result) {

推荐阅读