Rock, Paper, Scissors frustration :|

Hi all, I feel like i’ve taken way too much time on the Rock, Paper, Scissors project its really frustrating me.
I think i have successfully gotten up to part 11 but my code does not seem to be printing to console upon checking…
I wish there was a way to tell whether or not your code is correct or not during the projects because this one has me ripping my hair out.

Here’s my code, can someone enlighten me why it isn’t printing literally anything after “hi” to console.

console.log(‘hi’);

const UserChoice = userInput => {
userInput = userInput.toLowerCase();
if (userInput === ‘rock’ || userInput === ‘paper’ || userInput === ‘scissors’){
return userInput;
} else {
console.log(‘ERROR!’);
}
}
function ComputerChoice (randomNumber) {}
const randomNumber = Math.floor(Math.random() *3)
switch (randomNumber) {
case 0:
return ‘rock’;
break;
case 1:
return ‘paper’;
break;
case 2:
return ‘scissors’;
break;
}
let determineWinner = (userChoice , computerChoice) => {
if (userChoice === computerChoice){
return ‘The game was a tie.’;
}
if (userChoice === ‘rock’){
return ‘The user is the winner!’;}
else if (computerChoice === ‘paper’){
return ‘The computer has won’;
}
if (userChoice === ‘paper’){
return ‘The user is the winner!’;}
else if (computerChoice === ‘scissors’){
return ‘The computer has won’;
}
if (userChoice === ‘scissors’){
return ‘The user is the winner!’;}
else if (computerChoice === ‘rock’){
return ‘The computer has won’;
}
}
console.log(‘***********anything I place in here will not print to console **********’);

The sum total output of this function will be, undefined. Can you see why?

1 Like

I realise that the { } doesn’t have the Math.random inside of it but when ever i try to move the closing curly bracket anywhere after it i get a syntax error.
Apart from that can you see any other errors i may have made because there’s no indication for mistakes on the projects apart from syntax error and i’m not understanding why :confused:
thank you for your reply, I appreciate it.

There’s a few things here. First of all, none of the functions are ever called/invoked - meaning you’ve defined them, but you haven’t told the interpreter to actually do anything with them.

As mtf helpfully noted, the ComputerChoice function, which should be (by convention) computerChoice, does not wrap the function that actually determines its value in curly brackets appropriately.

function computerChoice() {
    const randomNumber...
    switch (randomNumber) {
        case 0:
            return 'rock'
        ...
    }
}

Above I demonstrate how the curly brackets should wrap the function. In addition, I removed the randomNumber as a parameter because when we call the function, we don’t provide any number to it, we generate the number within the function independent of any parameter. I also removed the 'break’s because when you return from a switch, you don’t also need to break out of the function.

Finally, your determineWinner function’s conditional logic doesn’t operate properly. To get you on the right track, you can try something like:

if (userChoice === computerChoice) return 'The game was a tie.'
if (userChoice === 'rock' && computerChoice === 'scissors') return 'You won!'
if (userChoice === 'rock' && computerChoice === 'paper') return 'The computer won.'

Then, you could test your functions by invoking them like:

console.log(determineWinner(userChoice('Rock'), computerChoice())

Also, please use the code button in the text editor here to wrap your code. It makes it easier for us to parse what you’ve written and help you. You can also provide a link to the thing you’re working on to get faster and more accurate support.

1 Like

Thank you for your help, I have edited my if else statements to just ifs now and that seems to work a lot better.
i can not wrap my head around the getComputerChoice though. I think i realise why you said it makes sense to just use computerChoice but whilst following the instructions it’s asking me to do it

(
5. Now we need to have the computer make a choice.

Create a new function named getComputerChoice with no parameters. Inside its block, utilize Math.random() and Math.floor() to get a whole number between 0 and 2. Then, depending on the number, return either 'rock', 'paper', or 'scissors'.
)

I feel like its mostly correct now but it still is not logging the determineWinner correctly, its now printing as UNDEFINED. I’ve changed it from a function to a variable function to see if that helps but still no joy. I have been working on this for 2 days now which I feel is far too long for what some people can probably write out within 5 minutes. I’m staying positive about it because apparently you learn from your mistakes :rofl:

here is my code again, I don’t want to just watch the video and copy the instructor. I want to understand why and how its working.

If you’re going to write if-statements without {}'s, I’d put the return statement inline. And this is ok to do as long as it’s just a one-line if-return statement.

The problem now lies in your use of the playGame function and the determineWinner function. For example, you’re logging the result of the playGame function, but there is no result because you never return anything from it. You could instead just invoke the playGame function, but you need to use the determineWinner function inside it and currently you’re just passing it in as a parameter which isn’t necessary.

It could instead look like this:

const playGame = () => {
    let userChoice = getUserChoice('ROCK')
    let computerChoice = getComputerChoice()
    console.log(determineWinner(userChoice, computerChoice))
}

And then at the end of all that, you just invoke the playGame function and it should print out the appropriate game result.
I’m not sure if it’s part of the challenge or whatever you’re doing, but you could also use the prompt function to get an actual user choice if you want. Again, please link the actual challenge or set of instructions you’re working on because I can’t remember all the steps required.

Thank you for your reply once again,
I just tried your code and it threw up a syntax error for me. probably due to my structure which your commands are referring to.
From my understanding I think my problem lies within the ‘determineWinner’ block of code containing the ‘if’ and ‘return’ statements. I’m so close to throwing my laptop out of the window at this point, its probably something really simple and stupid which I cant seem to figure out. I’ve been playing with it for the last hour and cant seem to make a difference, I get both results for the computer and user when I console.log(playGame()) butits just not fetching the ‘determineWinner’.
Here is the link to the instructions. The way its asked me to do it is different from your advice so maybe if you check it out you can understand my problem a bit better. Thankyou again :slight_smile:

https://www.codecademy.com/courses/introduction-to-javascript/projects/rock-paper-scissors-javascript

One might ideate this project as a number of functions which I’ll give symbol, rather than verbose names. In a table we can describe those variables:

a, b  =>  user, computer
u, v  =>  get functions
f     =>  compare function
g     =>  control function
const u = function (x) {

}
const v = function () {

}
const f = function (a, b) {

}
const g = function () {
  return f(u('rock'), v())
}

Now, wrap you head around that. The whole game is right there.

1 Like
const u = x => 'rockpaperscissors'.includes(x) && x || 'bomb';

const v =()=> ['rock','paper','scissors'][Math.floor(Math.random() * 3)]

I squished it to get rid of the scroll, not because I’m a lazy code typist.

console.log('hi');

const getUserChoice = (userInput) => {
  userInput = userInput.toLowerCase()
  if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors' || userInput === 'bomb') {
    return userInput
  } else {
    console.log('Invalid user input.')
  }
}

const getCpuChoice = () => {
  const cpuChoice = Math.floor(Math.random() * 3)
  switch (cpuChoice) {
    case 0:
      return 'rock'
    case 1:
      return 'paper'
    case 2:
      return 'scissors'
  }
}

const determineWinner = (userChoice, cpuChoice) => {
  if (userChoice === 'bomb') return 'Win'
  if (userChoice === cpuChoice) return 'Tie'

  if (userChoice === 'rock') {
    if (cpuChoice === 'scissors') {
      return 'Win'
    } else {
      return 'Loss'
    }
  }

  if (userChoice === 'paper') {
    if (cpuChoice === 'rock') {
      return 'Win'
    } else {
      return 'Loss'
    }
  }

  if (userChoice === 'scissors') {
    if (cpuChoice === 'paper') {
      return 'Win'
    } else {
      return 'Loss'
    }
  }
}

const playGame = () => {
  const userChoice = getUserChoice('BOMB')
  const cpuChoice = getCpuChoice()
  console.log(userChoice, cpuChoice)
  console.log(determineWinner(userChoice, cpuChoice))
}

playGame()

I redid the game following the instructions on the page. You can compare your code to mine.

Also, mtf’s solution for randomly assigning the cpuChoice is fantastic. I was thinking of using an object or map, but with smaller amounts of data like for rock, paper, scissors, arrays are great. And it all fits on one line without being unreadable!

Recognize that as an induced side effect. The example is ignorant of that and goes with the exact match. We do not need to massage the data, and neither should we, ever.

1 Like

Recognizing that if you assigned rock, paper, and scissors with unique values from 1-3 and then subtracted the corresponding values from each other you would get unique values that would always correspond to a win, tie, or loss, I rewrote the game, for fun and for the challenge, in a very succinct way:

// rock: 3, scissors: 2, paper: 1
// Results = user - cpu
// 1, -2, 1 - wins
// 0 - tie
// 2, -1, -1 - losses

const choicesToValues = {
  'rock': 3,
  'scissors': 2,
  'paper': 1,
  'bomb': Infinity,
}

const resultsMap = {
  '1': 'win',
  '-2': 'win',
  '2': 'loss',
  '-1': 'loss',
  '0': 'tie',
  'Infinity': 'win'
}

const getUserChoice = userInput => 'rockpaperscissorsbomb'.includes(userInput.toLowerCase()) ? choicesToValues[userInput.toLowerCase()] : console.log('Invalid user input.')

const getCpuChoice = () => choicesToValues[['rock', 'paper', 'scissors'][Math.floor(Math.random() * 3)]]

const determineWinner = (userChoice, cpuChoice) => resultsMap[userChoice - cpuChoice]

const playGame = () => `The result is a ${determineWinner(getUserChoice('rock'), getCpuChoice())}.`

console.log(playGame())

Because programming is every bit, if not more, about reading code as it is about writing code, try reading and trying to understand what I did as an extra challenge after you’re finished your project (if you want to).

Thank you for taking your time out to do this for me, as of yet though I don’t quite understand how this way works because there are things there I haven’t come across before. Once I have progressed further into the course I will be sure to come back and try to understand why this works :smiley:
I have eventually completed it, my motivation was high but I was losing hope for a minute. I wish you @mtf and @javaace96747 all the best and kudos for being there for somebody who is just starting out !

If for what ever reason i need a little support again i would be grateful for any to cross paths with you two again !

1 Like

I’m not quite sure what you mean by this probably due to my little experience with this language but I’ll be sure to revisit it once I have a better understanding.

1 Like
const u = x => 'rockpaperscissors'.includes(x) && x || 'bomb';

Is the above only for illustrative purposes and brevity?

Consider the cases:

console.log(u("ock"));
// "ock"

console.log(u("papersci"));
// "papersci"
1 Like

Yes to both. We can see the obvious weakness that would need to be addressed.

1 Like

In any case, you could just use an array for an easy and modular fix:

const choices = ['rock', 'paper', 'scissors', 'bomb']
const getUserChoice = userInput => choices.find(choice => choice === userInput.toLowerCase()) ? userInput.toLowerCase() : console.log('Invalid user input')

Hi its me again guys, I wish I understood what you was talking about but I haven’t quite made it up to the arrays ect yet.
just a quick question from me though, I have now completed the next project “sleep debt calculator” but I have some strange results when running some of the code. I have managed to complete the project and am happy to move on but I was just curious as to why I cant run my last function properly without adding “console.log()”.
I have // the code which is making it act strange and commented what it is or isn’t doing if that helps.

Take a look if you wish to and let me know why its wrong :grimacing:

This should have been new topic. If you mean there is nothing on the display, that is not an indication it is not working. We need to log out the result if we are to see what it is.

Please make a separate post next time.

The problem is that you have a console.log() which logs the result of calling a function from within that same function. It’s a recursive loop where everytime calculateSleepDebt is called it logs the result of calling itself, thereby causing it to run again and so on for until the browser can’t handle it anymore.

The rest of it works just fine.