Help on Rock, paper, scissors

const getUserChoice = userInput => {
userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
    return  userInput;
  }
  else {
    console.log('error')
  }
};
let getComputerChoice = () => {
  (Math.random(Math.floor()) * 3 );
}
let randomNumber = ''
switch (randomNumber) {
  case 0:
    return 'rock';
    break;
  case 1:
    return 'paper'
    break;
  case 2:
    return 'scissors'
    break;
}
console.log(getComputerChoice());
let determineWinner = (userChoice, computerChoice) => {
  if(userChoice === computerChoice) {
    return 'The game is a tie!';
  }
}
if(userChoice === 'rock') {
  if (computerChoice === 'paper') {
    return 'The computer won!';
  } else{
   return 'You won!'; 
  }
}
if (userChoice === 'paper') {
  if (computerChoice === 'scissors') {
    return 'The computer won!';
  } else {
    return 'You won!';
  }
}
if (userChoice === 'scissors') {
  if (computerChoice === 'rock') {
    return 'The computer won!';
  } else {
    return 'You won!';
  }
}

const playGame = () => {
  const userChoice = getUserChoice('scissors');
  const computerChoice = getComputerChoice();
  console.log('You threw: ' + userChoice);
  console.log('The computer threw:' + computerChoice);
 console.log(determineWinner(userChoice,computerChoice));
};
playGame();

This is the code i came up with on rock, paper, scissors cant seem to get it working it is saying userChoice is defined but I cant figure out what it means by that.

1 Like

First off, and be sure that this sinks in…

    return 'rock';
    break;

’break’ after ‘return’ is unreachable.

As it turns out, there are other problems in this same function. Can you suss them out?

3 Likes

Aside from some formatting mistakes overall, turns out a simple switch statement can’t be used just like that when it’s got return in its cases.

I can’t tell you exactly why - since I’m still a JS rookie myself - but it does work with console.logs and breaks instead of return. OR when putting the whole switch with its returns into a function and calling that function afterwards with a case for the parameter of the function, something like console.log(myFunction(<VARIABLE HERE>));

Please have a look at these parts of your code and think about what this actually does (mind the formatting i.e. semicolons):
let randomNumber = ''

case 0:
    return 'rock';
    break;
  case 1:
    return 'paper'
    break;
  case 2:
    return 'scissors'
    break;

Some logic mistakes can be easier to find when drawing a flow chart of your algorithm yourself, on a piece of paper for example.

These are some useful symbols to use for that: basic-symbols

In case you wonder what the whole thing might look like drawn out, you can google for pictures of flow charts and algorithms.

One last tip, cut your code into single pieces (as far as possible) and test them on their own first before putting them together, this makes for easier debugging.

2 Likes

I needed to put let randomNumber = ' ' because when I put switch (randomNumber)
without the let randomNumber = ' ' it gives me ReferenceError: randomNumber is not defined at Object.<anonymous>

Edit:
So when fixing it up Instead of console.log(userChoice); I put `console.log(‘userChoice’); and fixed the error code but know Im left with: userChoice undefined You threw: scissors The computer threw:undefined undefined

1 Like

There are 2 things wrong here.

First you cant use break; after a return. Because return already stops that part of the code the break would never be executed.

Secondly. A return only works if used in a function. Since this switch statement does not belong to a function you cant use return because where would the switch return its value to ?

I believe this switch statement should be part of the function getComputerChoice().

Here we have a similar problem as the switch statement. These if statements return something, but since they are not part of a function where would they return their values to ?

I believe these if statements should be part of the function determineWinner()

After this you should have fixed you’re errors.

Now you will keep a problem where the computer choice is 99% of the time undefined. This is because the use of Math.random(Math.floor()) * 3.
This usage is not correct yet.
I added a console.log so you can see what this returns. Hope you can see why it does not work yet.

let getComputerChoice = () => {
	let randomNumber = (Math.random(Math.floor()) * 3 );
	console.log("comp chooses nr: " + randomNumber);
	switch (randomNumber) {
	  case 0:
		return 'rock';
	  case 1:
		return 'paper'
	  case 2:
		return 'scissors'
	}
}

Hope it is usefull.

3 Likes

So i added the console.log but I still can not make out what exactly I am to fix I read what you said a couple of times but cant figure out what I am suppose to change. I understand what your saying just cant figure it out when i added the console.log i got userChoice rock: undefined rock: You threw: scissors The computer threw:undefined undefined
If u could tell me specifically what I need to do that would be helpful (sorry for the misconfusion)

1 Like

Could you add your code so we can see what you changed after our comments ?

I would rather having you understand what is happening instead of knowing how to fix this specific error.

2 Likes

alright

const getUserChoice = userInput => {
userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
    return  userInput;
  }
  else {
    console.log('error')
  }
};
let getComputerChoice = () => {
  (Math.random(Math.floor()) * 3 );
  console.log("rock: " + randomNumber);

let randomNumber = ''
let userChoice = ''
console.log('userChoice');
switch (randomNumber) {
  case 0:
    return 'rock';
  case 1:
    return 'paper'
  case 2:
    return 'scissors'
}
console.log(getComputerChoice());
let determineWinner = (userChoice, computerChoice) => {
  if(userChoice === computerChoice) {
    return 'The game is a tie!';
  }
}
if(userChoice === 'rock') {
  if (computerChoice === 'paper') {
    return 'The computer won!';
  } else{
   return 'You won!'; 
  }
}
if (userChoice === 'paper') {
  if (computerChoice === 'scissors') {
    return 'The computer won!';
  } else {
    return 'You won!';
  }
}
if (userChoice === 'scissors') {
  if (computerChoice === 'rock') {
    return 'The computer won!';
  } else {
    return 'You won!';
  }
}
}

const playGame = () => {
  const userChoice = getUserChoice('scissors');
  const computerChoice = getComputerChoice();
  console.log('You threw: ' + userChoice);
  console.log('The computer threw:' + computerChoice);
 console.log(determineWinner(userChoice,computerChoice));
};
playGame();

Giving me a error aswell

/home/ccuser/workspace/javascript_101_Unit_3/Unit_3/rockPaperScissors.js:12
  console.log("rock: " + randomNumber);
                         ^

ReferenceError: randomNumber is not defined
    at getComputerChoice (/home/ccuser/workspace/javascript_101_Unit_3/Unit_3/rockPaperScissors.js:12:26)
    at playGame (/home/ccuser/workspace/javascript_101_Unit_3/Unit_3/rockPaperScissors.js:56:26)
    at Object.<anonymous> (/home/ccuser/workspace/javascript_101_Unit_3/Unit_3/rockPaperScissors.js:61:1)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)

1 Like

Since I’m a rookie myself analyzing this and fixing it turned out to be a good practice for me.
The following is just one of many ways to fix this, though. I’d appreciate you read carefully in order to understand what’s going on, putting this together took quite some time.
(Maybe copy paste it into some document or program that makes reading it easier.)

/* formatting: I'm adding ; where they seem to be missing for consistency in code style
(even though they might not be needed for functionality)

"//TEMP" <- this will help you find (debug) code you can remove or comment later

*/

const getUserChoice = userInput => { 
userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
    return  userInput;
  }
  else {
    console.log('error'); // added missing ;
  }
};

//TEMP
let testVar = 'ROCK'; /* test variable, change for different debug test results
in case this becomes userChoice (read below) maybe invoke .toLowerCase() on it
like so: let userChoice = <get user input somehow here>.toLowerCase();
*/

//TEMP
console.log(getUserChoice(testVar)); /* invoking the function getUserChoice() to see if it works
output is rock -> function is working
*/

let getComputerChoice = () => {
  return Math.floor(Math.random() * 3); /* added return, so this function actuallly returns a random number

  the function (Math.random(Math.floor()) * 3) didn't return whole numbers
  so I fixed it by swapping random and floor and putting the * 3 inside the random step
  */
}; // added missing ;

//TEMP
console.log(getComputerChoice()); /* testing the function
 
 note the () after the function name
 
 this means I'm invoking the function rather than returning the contents of the function body
 */
 
let randomNumber = ''; /* added missing ; also this line does nothing for the whole code
and can be removed
*/
 
checkRandomNumber = (paramInput) => { // new function to make return work
  switch (paramInput) { // parameter input can be any name, paramInput here
    case 0:
      return 'rock';
      // removed break;
    case 1:
      return 'paper'; // added missing ;
      // removed break;
    case 2:
      return 'scissors'; // added missing ;
      // removed break;
    default:
      return 'error: checkRandomNumber did not work.'; // added a default, this helps with debugging
  }
} // new function end

//TEMP
console.log(checkRandomNumber(getComputerChoice())); /* testing the new function with whatever
getComputerChoice() returns -> outputs rock, paper or scissor -> code is working so far
*/

console.log(getComputerChoice());
// displaying the computer's choice, this line is OK for debugging but not needed in the end

let determineWinner = (userChoice, computerChoice) => { // redundant later on, see below
  if(userChoice === computerChoice) {
    return 'The game is a tie!';
  }
}

//TEMP
console.log(determineWinner(testVar, getComputerChoice()));/* testing determineWinner(),

userChoice is not defined up until this point so I'm using the debug testVar defined earlier

to fix this just rename the testVar to userChoice and find a way to receive the user's input
like with readline() for example or a prompt window, testVar is a static variable for now
don't forget to replace all testVar code with userChoice or with whatever you name it

note the tie result will not be returned unless the user writes the input as expected
this can be fixed by normalizing the user input after receiving it using .toLowerCase()
before passing it to the functions
*/

winOrLose = () => {
  /* var assignment for readability
  the variables will be assigned with content from the global scope
  (scope is part of the JS course content)
  */
  let userInput = testVar.toLowerCase(); /* var assignment for readability,
  making it lowercase for consistent values
  */
  let computerChoice = checkRandomNumber(getComputerChoice()); 
  
  console.log('You threw: ' + userInput); /* moved from playGame
  changed to userInput
  */
  console.log('The computer threw: ' + computerChoice);
  /* moved from playGame
  changed to run the function that returns whatever  the Computer chose
  */
  
  /* In order for two parameters to be put into a conditional statement an if statement
  makes the most sense, a switch is not easy to use here in order to evaluate two parameters
  
  I believe the following if statement can be shortened to save identical console.log()s
  but would make for harder reading
  */
  if (userInput !== computerChoice) {
    if (userInput === 'rock' && computerChoice === 'paper') {
      console.log('The computer won!');
    } else if (userInput === 'rock' && computerChoice === 'scissors') {
      console.log('You won!');
    } else if (userInput === 'paper' && computerChoice === 'scissors') {
      console.log('The computer won!');
    } else if (userInput === 'paper' && computerChoice === 'rock') {
      console.log('You won!');
    } else if (userInput === 'scissors' && computerChoice === 'rock') {
      console.log('The computer won!');
    } else if (userInput === 'scissors' && computerChoice === 'paper') {
      console.log('You won!');
    } else {
      console.log('error: winOrLose did not work.'); // error message for debugging
    }
  } else {
    console.log('The game is a tie!');
    /* putting the check for a tie here makes the code shorter
      
      don't forget to remove the previous - now redundant - tie check above (determineWinner())
      */
  }
  
}

const playGame = () => { // this function has become redundant with winOrLose()
  const userChoice = getUserChoice('scissors'); 
  const computerChoice = getComputerChoice(); 
  console.log('You threw: ' + userChoice);
  console.log('The computer threw:' + computerChoice);
  console.log(determineWinner(userChoice,computerChoice));
};

// invoking winOrLose() which can be renamed to playGame(when deleting the old playGame function above)
winOrLose();

/* the debug test codes labelled //TEMP can be removed for the final javascript

the comments in the final version should explain WHAT the code is doing and not
WHY the code does what it does, like I did for this one
*/
1 Like

Hmm… is my post unclear in anyway ? if so what exactly do you not understand ?

I believe everything i have talked about in my previous post has been handled in the lessons that come before the rock,paper,siccors project.

If it makes no sence what i have been talking about it might be a good idea to start chapter 3 of introduction to javascript again. Try to understand this lesson and than try the rock,paper,siccor project again.

1 Like

I just dont understand stuff that is complicated like

I need to know where to put stuff exactly if that makes any sense, Basically stuff in simple terms like : “You need to put ________ there and ______ there.” You understand?
I just have a hard time understanding multiple stuff without detailed step by step instruction

Bottom line, be sure that all the code that is meant to be inside the function body is actually inside.

function getComputerChoice() {
    let randomNumber = Math.floor(Math.random() * 3);
    switch (randomNumber) {
        // cases
    }
}
2 Likes

Also you said

While I understand what your saying for the most part your not telling me where to put so im not going to know what to do

1 Like