Hello.
I am working on the JS rock paper scissors game and I am stuck on a concept that I think has to do with my getComputerChoice function. Everything appeared to be working until I finished the project. When I run the game, it appears as though the computer is choosing 'UNDEFINED" every time. I have confirmed that my number generator is working as intended so I think it must have to do with my return statements. I cannot figure out what is going wrong. I originally had an “else” statement in the determine winner function that would accidentally allow “UNDEFINED” as an option for the computer choice so the game would say the user lost. I fixed that problem and it narrowed down to this. Any feedback is appreciated. My game’s code looks like this:
//////////////////////////////////////////////////////
const getUserChoice = userInput =>{
userInput = userInput.toLowerCase();
if (userInput != 'rock' && userInput != 'paper' && userInput != 'scissors'){
console.log('Error: Please use rock, paper, or scissors.')}
else{
return userInput
}
};
/////////////////////////////////////////////////////////
function getComputerChoice() {
let rng = Math.floor(Math.random()*3);
switch (rng)
{
case rng === 0:
return 'rock'
break
case rng === 1:
return 'paper'
break
case rng === 2:
return 'scissors'
break
}
}
/////////////////////////////////////////////////////
function determineWinner(userChoice,computerChoice){
if (userChoice === computerChoice){
console.log('the game was a tie.')
}
else if (userChoice === 'paper'){
if (computerChoice === 'rock')
{console.log('USER WINS!')}
else if(computerChoice === 'scissors') {console.log ('USER LOSES')}
}
else if (userChoice === 'scissors'){
if (computerChoice === 'rock')
{console.log('USER LOSES!')}
else if (computerChoice === 'paper')
{console.log ('USER WINS')}
}
else if (userChoice === 'rock'){
if (computerChoice === 'scissors')
{console.log('USER WINS!')}
else if (computerChoice === 'paper')
{console.log ('USER LOSES')}
}
}
/////////////////////////////////////////////////////////
function playGame(){
let userChoice = getUserChoice('rock')
console.log(`The player choses ${userChoice}`)
let computerChoice = getComputerChoice()
console.log (`Computer choses ${computerChoice}`)
determineWinner(userChoice, computerChoice)
}
playGame()
in your switch statement block:
case rng === 0:
should be
case 0:
and similarly for the other cases.
(because rng === 0
would give you true
or false
, and it would check whether rng
matches that, instead of checking whether rng
is 0
).
You are the bomb!!!
thank you for this.
This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.