[SOLVED] Rock paper scissors- Adding validation to while loop

Hi everyone,

I am trying to add validation for the Players choice so that “rock” "paper or “scissors” are the only valid choices. The player should have to re-enter the value until it matches one of these options. I have created a function to test this but I realise this isn’t actually being used at all.
While function is:

function playerSelection(){
pHand = prompt(“Rock, paper or scissors?”).toLowerCase();
while (pHand != “rock” && pHand != “paper” && pHand != “scissors”) {
pHand = prompt(“Rock, paper or scissors?”).toLowerCase();
}
return pHand;
};
I understand that in the game function below, the playerSelection function is not being used at all but I can’t figure out how to add validation otherwise. If I try and add the function into the game function I get the error: Cannot access ‘playerSelection’ before initialization at game.

Any help on how I can add validation on input would be appreciated- I hope everything made sense.

Thanks :slight_smile:

function game(){
chooseNumRounds();

for (let i = 0; i < num; i++){
let playerSelection = prompt(“Rock, paper or scissors?”);
let computerSelection = computerPlay();

console.log(playRound(playerSelection, computerSelection), "You have " + win + " wins " + lose + " losses " + draw + " draws." );

}
determineWinner();
playAgain();

}


if you need to see the whole code

Hi, in this line

probably you must do

let playerSelection = playerSelection();

but i belive this it what you do before and gives you problem. Maybe you should change the name of the playerSelection variable.

1 Like

Thanks fernando!

I made the change you suggested and also changed the variable name- this seemed to do the trick.

1 Like