1

Heyy

I want to program a "Rock Paper Scissors" with a computer. Now, when I choose one of the 3 options, I want the computer to put in a random object - but how? I came up with something like this

jQuery ( when i click #rock, put in a random div from below)

$('#rock').on('click',function() {
           $('#putHere').text($("#rock" || "#paper" || "#scissors").text());
          });

HTML

 <div id="rock">rock</div>
 <div id="paper">paper</div>
 <div id="scissors">scissors</div>

May be misunderstandable but yeah.. I tried my best.. Thaks for the help though

Syno
  • 1,056
  • 10
  • 25
  • 1
    @Manishh i was searching for so long but i saw it right after i asked the question.. so yeah it is – Syno Jan 05 '17 at 11:50

2 Answers2

1

You can try this thing

var myArray = ['#rock', '#paper', '#scissors']; 
$('#putHere').text(myArray[Math.floor(Math.random() * myArray.length)]);
Manishh
  • 1,444
  • 13
  • 23
1

Use an array to hold the selectors and generate index randomly using Math.random method.

var sel = ["#rock", "#paper", "#scissors"];

$('#rock').on('click', function() {
  $('#putHere').text($(sel[Math.floor(Math.random() * sel.length)]).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rock">rock</div>
<div id="paper">paper</div>
<div id="scissors">scissors</div>


<div id="putHere"></div>

Or use collection of elements instead of array of selectors.

var $el = $("#rock,#paper,#scissors");

$('#rock').on('click', function() {
  $('#putHere').text($el.eq([Math.floor(Math.random() * $el.length)]).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rock">rock</div>
<div id="paper">paper</div>
<div id="scissors">scissors</div>


<div id="putHere"></div>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188