I don’t know where my mistake is. The console gives me the following output "you chose scissor. the computer chose stone. you won!"
const playerChoice = ["scissor", "stone", "paper"];
const computerChoice = function() {
let randomNumber = Math.floor(Math.random() * playerChoice.length);
if (randomNumber === 0) {
return "scissor";
}
if (randomNumber === 1) {
return "stone";
}
if (randomNumber === 2) {
return "paper";
}
};
function game() {
const computerSelectedChoice = computerChoice();
if (playerChoice[0] === computerSelectedChoice) {
return "its a draw!";
}
if (playerChoice[0] && computerSelectedChoice === "stone") {
return "the computer won!";
}
if (playerChoice[0] && computerSelectedChoice === "paper") {
return "you won!";
}
if (playerChoice[1] && computerSelectedChoice === "paper") {
return "you won!";
}
if (playerChoice[1] && computerSelectedChoice === "paper") {
return "the computer won!";
}
if (playerChoice[2] && computerSelectedChoice === "scissor") {
return "the computer won!";
}
if (playerChoice[2] && computerSelectedChoice === "stone") {
return "you won!";
}
}
console.log(`you chose ${playerChoice[0]}.`);
console.log(`the computer chose ${computerChoice()}.`);
console.log(game());
I have made some changes, I know the code could be simplified or a switch statement could be implemented. Since I am still a beginner, I have left the code as it is and focused on bug fixing.
2
Answers
I see a couple improvements/fixes that can make so let’s break it down:
computerChoice()
helper twice: Once for the display and once for the comparison. But this will cause a different result for the display vs the comparison due to it being random. So let’s call it once and store the outcome in variable.playerChoice[0] && computerSelectedChoice === "stone"
but this just checking ifplayerChoice[0]
is truthy and not necessarily comparing it to the computers choice as intended.if (playerChoice[1] && computerSelectedChoice === "paper")
Here is an example of how we can fix these issues:
This is how I would have done it.
All wins are +1 difference. In order to avoid negative values I add the number of choices and use modulas.