在这个奥丁课程中有一个任务是制作“石头、剪刀、布”游戏。当尝试添加计分计数器时,即使通过程序正确跟踪了玩家和计算机的分数,分数也会返回为“未定义”。关于如何解决这个问题有什么建议吗?
代码:
let Choices = ["Rock", "Paper", "Scissors"];
let playerScore = 0;
let computerScore = 0;
function getComputerChoice() {
let random = Math.floor(Math.random() * Choices.length);
return Choices[random];
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return "Draw!";
}
else if (playerSelection.toLowerCase() === "rock" && computerSelection === "Paper") {
computerScore++;
return ("Computer Wins!");
}
else if (playerSelection.toLowerCase() === "rock" && computerSelection === "Scissors") {
playerScore++;
return ("You Win!");
}
else if (playerSelection.toLowerCase() === "paper" && computerSelection === "Rock") {
playerScore++;
return ("You Win!");
}
else if (playerSelection.toLowerCase() === "paper" && computerSelection === "Scissors") {
computerScore++;
return ("Computer Wins!");
}
else if (playerSelection.toLowerCase() === "scissors" && computerSelection === "Rock") {
computerScore++;
return ("Computer Wins!");
}
else {
return ("You Win!");
}
}
function playGame(playerScore, computerScore) {
for (let i = 0; i < 5; i++){
let computerSelection = getComputerChoice();
let playerSelection = "Rock";
console.log(playRound(playerSelection, computerSelection));
console.log(`Player: ${playerScore}\nComputer: ${computerScore}`);
}
}
console.log(playGame());
我已经通过在“if 语句”中的“return 语句”之前使用“console.log()”检查了“playerScore”和“computerScore”是否被正确跟踪。然而,当尝试在“for循环”中正确输出代码时,它只是说“未定义”。
playerScore
和 computerScore
是全局定义的。
通过在
playGame
函数中使用相同名称的参数,您可以隐藏全局参数。由于您调用函数时没有传递这些参数的值,因此它们隐式地 undefined
。
删除这些参数,你应该没问题:
function playGame() {
// Here ----^