Unit 7, Lesson 4: Parameters & Return Make (Rock, Paper, Scissors)

Link to the project or level: Code.org - App Lab
What I expect to happen: I expect the code to do a Rock, Paper, Scissors game, and display the winner
What actually happens: Sometimes it works great, sometimes the the computer’s choice is undefined. Which means I get the error: “setProperty() value parameter value (undefined) is not a string.” on line 39 and/or 40.
What I’ve tried: I’m pretty sure my issue is in the randomChoose function. Sometimes the random number generator is choosing something which is not an index in the list, maybe? So I’ve tried doing various combinations of list.length or list.length-1 in the for loop and in randomNumber.

This doesn’t do what you think it does

function randomChoose(list){
  //var randomItem;
    for(var i = 0; i < list.length-1; i++){
      if(i == randomNumber(0, list.length)){
        //randomItem = list[i];
        return list[i];
      }
    }
    //return randomItem;
}

What you are doing is deciding which index to use by giving each of the 3 indices a 1 in 4 chance of being chosen. That means there is also a chance no index will be chosen. Even if you change that to a 1 in 3 chance there is a possible no selection.

Why not just return a random selection instead of giving each selection an opportunity?

1 Like

Thank you! Returning a random selection didn’t even occur to me; I guess my brain is stuck on traversals!

But I still don’t really get why it would be possible for there to be no selection. If there’s a 1 in 3 chance of choosing an option, shouldn’t one of the three options always be chosen?

Each time you go through the loop, you are generating a different random number and returning a value only if the value matches the current index. So there is a chance that in each iteration through the loop, the random number selected and the index of the loop are never the same. In this case, you would get an undefined value.

1 Like