I am attempting to create a rock paper scissors game with vanilla JS. I am getting an incorrect result when pressing the button associated with a choice. The choice itself is correct (if I choose "rock", the console is logging "rock" correctly), but the result is incorrect (if I choose "rock" and the computer chooses "paper" I get anything from "it's a tie" or "you lose" for example. Here's the code:
const gameChoices = ["rock", "paper", "scissors"];
function getComputerChoice() {
const randomIndex = Math.floor(Math.random() * gameChoices.length);
const randomChoice = gameChoices[randomIndex];
return randomChoice;
}
const choiceButton = document.querySelectorAll(".choiceButton");
choiceButton.forEach((button) =>
button.addEventListener("click", () => {
playerSelection = button.textContent.toLowerCase();
console.log(playerSelection);
computerSelection = getComputerChoice();
console.log(getComputerChoice());
console.log(playRound(playerSelection, computerSelection));
})
);
function playRound(playerSelection, computerSelection) {
if (playerSelection == "rock" && computerSelection == "paper") {
++computerScore;
console.log("You lose");
} else if (playerSelection == "rock" && computerSelection == "scissors") {
console.log("You win");
++playerScore;
} else if (playerSelection == "scissors" && computerSelection == "rock") {
console.log("You lose");
++computerScore;
} else if (playerSelection == "scissors" && computerSelection == "paper") {
console.log("You win");
++playerScore;
} else if (playerSelection == "paper" && computerSelection == "scissors") {
console.log("You lose");
++computerScore;
} else if (playerSelection == "paper" && computerSelection == "rock") {
console.log("You win");
++playerScore;
} else if (playerSelection == computerSelection) {
console.log("It's a tie");
} else {
return console.log(wrongSelection());
}
}
function wrongSelection(playerSelection) {
if ((playerSelection != "rock", "paper", "scissors")) return "try again";
}
I think the code is running the getComputerChoice function multiple times. So it runs it and logs it as one value, but then when I call playRound, it runs getComputerChoice again and produces a different value. Thus making it look like it's not following the logic. I'm not quite sure how to fix this issue though.