gpt4 book ai didi

javascript - Rock, Paper, Scissors Game - userChoice 未定义,但已定义...我认为?

转载 作者:行者123 更新时间:2023-11-29 22:59:58 28 4
gpt4 key购买 nike

当我执行 playGame();我想展示这个:您已选择 ${userChoice),计算机已选择 ${computerChoice}。获胜者是 ${determineWinner}。根据我的理解,userchoice 定义在我的代码顶部,computerChoice 定义在 computerChoice 部分。所以我不明白。感谢您的帮助。

相反,我只是收到一条错误消息:ReferenceError: userChoice is not defined 在玩游戏。

已修复:这就是我所做的,但不确定它是如何或为什么起作用的:

function playGame(){
userChoice = "rock";
computerChoice = getComputerChoice();
console.log(`The user chose ${userChoice}. The computer chose ${computerChoice}. ${determineWinner(userChoice,computerChoice)}`)
}
playGame();


//We're taking the userInput and converting it to lowercase letters and storing it within userChoice
function getUserChoice(userInput){
let userChoice = userInput.toLowerCase();
if(userChoice === "rock" || userChoice === "paper" || userChoice === "scissors"){return userChoice;}
else{return "That hand doesn't exist.";}
}

//We're making a number and converting it to an eqvivalent string
function getComputerChoice(){
let computerChoice = Math.floor(Math.random()*3);
if(computerChoice === 0){return "rock";}
else if(computerChoice === 1){return "scissors";}
else if(computerChoice === 2){return "paper";}
else{return "Input not valid.";}
}

//Determining the winner based upon the input and the computer's choice
function determineWinner(userChoice, computerChoice){
//Having a tie
if (userChoice === computerChoice){return "It's a tie!";}
//If the user types in scissors
else if(userChoice === "scissors"){
if(computerChoice === "rock"){return "Computer wins! Rock kills scissors.";}
else if(computerChoice ==="paper"){return "User wins! Scissors kill paper.";}
}
//If the user types in paper
else if(userChoice === "paper"){
if(computerChoice === "rock"){return "User wins! Paper kills rock.";}
else if(computerChoice === "scissors"){return "Computer wins! Scissors kill paper.";}
}
//If the user types in rock
else if(userChoice === "rock"){
if(computerChoice === "paper"){return "Computer wins! Paper kills rock.";}
else if(computerChoice === "scissors"){return "User wins! Rock kills scissors."};
}
}

//Function that embodies the other functions and executes the game.
function playGame(){
console.log(`You chose ${userChoice}`);
}
playGame();


最佳答案

您的变量 userChoice 未在函数 playGame 的上下文中定义,这就是您看到引用错误的原因:

function playGame() {
console.log(`You chose ${userChoice}`); // this is not defined
}

playGame();

关于javascript - Rock, Paper, Scissors Game - userChoice 未定义,但已定义...我认为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55885305/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com