5

I am learning JavaScript and I want to make a simple rock paper scissors game. I want to make the computer choose the number 1, 2, or 3 at random and make the answer a variable called computerResponse. How do I do this?

var computerResponse = ???;

If this question is unclear please tell me and I will try to make it better.

Thanks in advance.

Pancake_Senpai
  • 915
  • 5
  • 12
  • 19
  • 1
    [Math.random()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random); try it and see how far you get. – Evan Davis Sep 25 '13 at 19:19
  • Also, if you search SO for `javascript rock paper scissors` you'll find a bunch of similar questions. – Barmar Sep 25 '13 at 19:20
  • 1
    Why would anyone downvote this? It's a duplicate, sure, but the asker is obviously new to this site, and doesn't deserve a hostile downvote right off the bat... – Bobby Jack Sep 25 '13 at 19:21
  • I didn't downvote, but perhaps because the asker has apparently made no effort to try to solve the problem himself. – Barmar Sep 25 '13 at 19:21
  • @Barmar: maybe they came here and just asked a question before even thinking about searching. maybe their search term wasn't the best, and they didn't get great results. sure, we should be encouraging 'the correct' behaviour, but I just think a downvote here is a bit heavy-handed – Bobby Jack Sep 25 '13 at 19:22
  • Sorry guys I'm a complete newbie to JavaScript and this is the first time I've attempted to do something like a game. I have looked (I looked for several hours) but didn't find anything. I'll look more thoroughly next time. Sorry for any inconvenience and special thanks to those who answered. :) – Pancake_Senpai Sep 25 '13 at 19:25

3 Answers3

15
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

var computerResponse = getRandomInt(1, 3);

Taken from MDN's documentation on Math.random().

theftprevention
  • 5,083
  • 3
  • 18
  • 31
0

Try:

 Math.ceil(Math.random()*3);
Justin Godesky
  • 1,019
  • 1
  • 10
  • 17
mipmap
  • 221
  • 1
  • 13
0

You can go with this below javascriptscript code that would be fetched random numbers...

var randomnumber = Math.floor(Math.random()*3)