javascript - 在 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;
}
}
解决方案
您已经有了这一轮的结果,并将其传递给gameScore
with gameScore(roundResult);
,但是,您实际上并没有使用该参数,而是创建了另一轮:
function gameScore() {
let result = playRound()
相反,只需获取传递的结果:
function gameScore(result) {
推荐阅读
- node.js - 反应应用程序 - npm run build - BrowserlistError
- python - 从电报下载选定的文件?
- websocket - JMeter忽略所有接收采样器(Websocket)中的特定类型的响应
- javascript - Javascript 原型链与作用域链
- c - 使用递归打印星形图案显示多行
- bash - Bash 数学表达式
- javascript - Boolean([]) 返回 true 为什么?
- python - 使用“with open”时文件位于何处?
- jenkins - Jenkins SSH 服务器在尝试通过 SSH 插件进行设置时显示错误算法协商失败
- python-3.x - 如何创建当前日期和时间的文件夹并在python中最近创建的文件夹中复制一些其他文件夹