[英]im a new learner and cant figure out why my code is not working
I have just recently got into coding and have chosen to learn JavaScript as my first language.我最近刚开始编码,并选择学习 JavaScript 作为我的第一语言。 I have written up code for a Rock, Paper, Scissors game but the wrong outputs come out when I run it?我已经为 Rock, Paper, Scissors 游戏编写了代码,但是当我运行它时会出现错误的输出? for example I would put my answer as scissors and the computer would choose rock and the game will come out as a tie.例如,我会将我的答案设置为剪刀,而计算机会选择摇滚,游戏会以平局的形式出现。
const getUserChoice = userInput => { if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') { return userInput } else { return 'Error!' } } var getComputerChoice = () => { const randomNumber = Math.floor(Math.random() * 3); switch (randomNumber) { case 0: return 'rock' break; case 1: return 'paper' break; case 2: return 'scissors' break; } }; const determineWinner = (userChoice, computerChoice) => { if (userChoice === computerChoice) { return 'its a tie!'; }; if (userChoice === 'rock') { if (computerChoice === 'paper') { return 'computer won'; } else { return 'user won'; } } if (userChoice === 'paper') { if (computerChoice === 'scissors') { return 'computer won'; } else { return 'user won' } } if (userChoice === 'scissors') { if (computerChoice === 'rock') { return 'computer won'; } else { return 'user won' } } }; const playGame = () => { console.log(`player chose ${getUserChoice('scissors')}`); console.log(`computer chose ${getComputerChoice()}`); console.log(determineWinner(getUserChoice("scissors"), getComputerChoice())); } playGame();<\/code><\/pre>
"
Maybe there are more issues, but here are some of them:也许还有更多问题,但这里有一些:
Each time you execute getComputerChoice you get a different value because a random value is picked inside:每次执行 getComputerChoice 时都会得到一个不同的值,因为在其中选取了一个随机值:
console.log(`player chose ${getUserChoice('scissors')}`);
console.log(`computer chose ${getComputerChoice()}`);
console.log(determineWinner(getUserChoice("scissors"), getComputerChoice()));
Every time you call getComputerChoice<\/code> you'll get a different value, you could save<\/strong> the values in a variable<\/strong> with the const<\/em> keyword.
每次调用
getComputerChoice<\/code>都会得到不同的值,您可以使用const<\/em>关键字将值保存<\/strong>在变量<\/strong>中。
const playGame = () => {
// It would be nice if you request this to the user, with prompt
const userChoice = getUserChoice('scissors');
// Save the random value
const computerChoice = getComputerChoice();
console.log(`player chose ${userChoice}`);
console.log(`computer chose ${computerChoice}`);
// This will work
console.log(determineWinner(userChoice, computerChoice));
}
playGame();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.