I don't know why it gives me wrong results, it shows that I have lost when the machine uses scissors and I use stone, it also shows a tie when it is not, etc.. sometimes it is right and other times it is not, I do not understand what is happening to my code and/or also if it can be made more clear.
my code
const getUserChoice = function getUserChoice(userInput) {
userInput = userInput.toLowerCase();
if (
userInput === "rock" ||
userInput === "paper" ||
userInput === "scissors"
) {
return userInput;
} else {
console.log("Error");
}
};
const getComputerChoice = function getComputerChoice() {
let randomNumber = Math.floor(Math.random() * 3);
switch (randomNumber) {
case 0:
return "rock"
break;
case 1:
return "paper"
break;
case 2:
return "scissors"
break;
default:
"Error";
break;
}
};
const determineWinner = (userChoice, computerChoice) => {
if (userChoice === computerChoice) {
return "The game is a tie!";
}
if (userChoice === "rock") {
if (computerChoice === "paper") {
return "Has perdido!";
} else {
return "Has ganado!";
}
}
if (userChoice === "paper") {
if (computerChoice === "scissors") {
return "Has perdido!";
} else {
return "Has ganado!";
}
}
if (userChoice === 'scissors') {
if (computerChoice === 'rock') {
return 'Has perdido!';
} else {
return 'Has ganado!';
}
}
};
const playGame = () => {
userChoice = getUserChoice("rock");
computerChoice = getComputerChoice();
console.log(getUserChoice("rock"));
console.log(getComputerChoice());
console.log( determineWinner(userChoice, getComputerChoice) );
};
playGame();
You have almost everything right. The
if
's, although they can be rewritten in a simpler way, are fine. Your problem is in the methodplayGame()
You're getting the computer's choice on the line:
This line gets a random value each time it is executed. So the first thing you do is store that value in the variable
computerChoice
.Then you print a second execution of that method at the line:
This value that you print to the console may be different from the one you have stored in the variable
computerChoice
. Here is the first problem . The value may or may not be the same and you can't trust what theconsole.log()
.Your second problem is when you call
The second argument you're passing isn't a value, it's a reference to the function. If you look closely, you are missing the parentheses. So, on the first evaluation:
Solution
You have two options:
determineWinner(userChoice, computerChoice)
determineWinner(userChoice, getComputerChoice())
;If you go with option 2, remember that the result of the function is random, so don't trust the
console.log
one above.