I’m doing an Odin Porject (Javascript Basic): Rock, Paper, Scissor only in the browser console and I’m having trouble keeping score. I’m still a beginner so excuse my messy code. I’ve tried adding another function to keep the score but it didn’t work either.
choices = ['rock', 'paper', 'scissors']
let playerScore = 0
let computerScore = 0
function getComputerChoice() {
return choices[Math.floor(Math.random() * choices.length)]
}
function getPlayerChoice() {
let input = prompt('Pick Rock, Paper, or Scissor?')
input = input.toLowerCase()
return input
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === 'paper' && computerSelection === 'scissors' ||
playerSelection === 'scissors' && computerSelection === 'rock' ||
playerSelection === 'rock' && computerSelection === 'paper') {
computerScore++
return `You lose! ${computerSelection} beats ${playerSelection}`
} else if (playerSelection === 'rock' && computerSelection === 'scissors' ||
playerSelection === 'paper' && computerSelection === 'rock' ||
playerSelection === 'scissors' && computerSelection === 'paper') {
playerScore++
return `You win! ${playerSelection} beats ${computerSelection}`
} else
return `It's a tie!`
}
function game() {
for (let i = 1; i <= 5; i++) {
const playerSelection = getPlayerChoice();
const computerSelection = getComputerChoice();
console.log(playRound(playerSelection, computerSelection));
}
if (playerScore > computerScore) {
return 'You beat the computer! You are a genius'
} else if (playerScore < computerScore) {
return `You got beat by the computer. Practice your throws!`
} else {
return `You tied with the computer!`
}
}
game();
2
Answers
The issue is you are using a single
&
as part of your conditional statements. This is not how you say "logical this AND that" in JavaScript. A single&
is a bitwise AND which is very different from a logical AND (also known as a ‘logical conjunction’).You should use two
&
characters within your conditional statements. Example:It’s also worth noting that you had a logical error in your
if
/else
structure. They way you have it, entering something that isn’t within'rock'
,'paper'
,'scissors'
would result in returning "You win…"I’ve addressed that error in my example code above. Now if either user enters something invalid, neither players score is incremented and the game will print an error message.
Note that you can greatly simplify the test to see who wins. There is a circular order: Rock < Paper < Scissors < Rock…
Therefore, you win if the index of the computer’s choice in the choices array is exactly one less than the index of your choice in the choices array. To account for the fact that it must loop around, so that Rock beats Scissors, you can turn a -2 result of the subtraction into +1 by using the mod
%
operator.