I have just recently got into coding and have chosen to learn JavaScript as my first language. I have written up code for a Rock, Paper, Scissors game but the wrong outputs come out when I run it? 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();
CodePudding user response:
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:
console.log(`player chose ${getUserChoice('scissors')}`);
console.log(`computer chose ${getComputerChoice()}`);
console.log(determineWinner(getUserChoice("scissors"), getComputerChoice()));
So you must instead call and store in variables:
let playerChose = getUserChoice('scissors');
let computerChose = getComputerChoice();
let winner = determineWinner(playerChose, computerChose);
console.log(`player chose ${playerChose}`);
console.log(`computer chose ${computerChose}`);
console.log(winner);
You can do it without variables, but be sure not invoking getComputerChoice several times.
Also userInput should be between parenthesis at:
const getUserChoice = (userInput) => {
CodePudding user response:
Every time you call getComputerChoice
you'll get a different value, you could save the values in a variable with the const keyword.
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();
More on prompt here