-2

I'm currently in the process of learning to do Javascript, with the help of the ever so useful website www.codecademy.com. I've recently managed to make a simple Rock, Paper, Scissors game, and I've decided to try and improve on it.

The basic idea is that the script prompts for an input, and if it is "Rock", "Paper", or "Scissors", then it randomises a response, and so forth.

I'm currently trying to add a system that makes it so that if the user types anything other than "Rock", "Paper" or "Scissors" in the prompt window, they get an error and get asked to answer again. Is there an if statement or anything similar that will allow me to do this?

Basically

if(userInput isNot "Rock","Paper" or "Scissors"){

prompt again;

} else {
continue;
}

Sorry if I'm incompetent, I'm new to this.

Thanks for your help.

  • I think add a question here was harder than fix that on your own, the site gives you enough, you are learning to code try harder or you wont last on this industry...give a man a fish... – Rayweb_on Nov 13 '13 at 21:23
  • You might want to use a `do { input = prompt(); } while(condition)` construction to repeatedly prompt the user while some condition holds. – apsillers Nov 13 '13 at 21:25
  • Why people answering this garbage? The title is _almost literally_ "gimme teh codez." OP did not try! – Evan Davis Nov 13 '13 at 21:28

3 Answers3

2

You could simply do check each valid input like this:

if(!(userInput == "Rock" || userInput == "Paper" || userInput == "Scissors")) {
   ...
}

Which, by De Morgan's Law is equivalent to:

if(userInput != "Rock" && userInput != "Paper" && userInput != "Scissors") {
   ...
}

Or could store the valid inputs in an array and check to see if userInput is in that array:

var validInputs = [ "Rock", "Paper", "Scissors" ];
if(validInputs.indexOf(userInput) == -1) {
   ...
}

Note that .indexOf is not supported by some older browsers. See ECMAScript 5 compatibility table. If you happen to be using jQuery you can use inArray (many other JavaScript toolkits have a similar feature):

var validInputs = [ "Rock", "Paper", "Scissors" ];
if($.inArray(validInputs, userInput)) {
   ...
}
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
0

Basically:

if(userInput != "Rock" && userInput != "Paper" && userInput != "Scissors") {
    .....   
} else {
    .....
}
James Gaunt
  • 14,631
  • 2
  • 39
  • 57
0

Create an array and test to see if the answer exists in the array.

var ans = ["Rock","Paper","Scissors"];
if(ans.indexOf(userInput) == -1) {
    // prompt again to user
} 
else {
    // continue...
}
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736