JS Tutorial – Math.random() Rock Paper Scissors


Rengga Dev Math.random() is an API in JavaScript. It is a function that gives you a random number. The number returned will be between 0 (inclusive, as in, it’s possible for an actual 0 to be returned) and 1 (exclusive, as in, it’s not possible for an actual 1 to be returned).

$(window).load(function() {
  
  var movesContainer = $('#moves'),
      playerCount = $('.Player-count'),
      computerCount = $('.Computer-count');
  
  $('#moves li').on("click", function() {
    var yourMove = $(this).data('move');
    processMoves(yourMove);
    
    var icon = $(this).find('.fa');
    icon.addClass('animating');
    
    var s = setTimeout(function(icon) {
      $('#moves li .fa').removeClass('animating');
      clearTimeout();
    }, 5000);
  });
  
});

function processMoves(yourMove) {
  var opponentMove = generateRandomOpponentMove();
  calculateWinner(yourMove,opponentMove);
}

function generateRandomOpponentMove() {
  var availableMoves = ['rock','paper','scissors'],
      randomNumber = Math.floor(Math.random() * availableMoves.length),
      opponentMove = availableMoves[randomNumber];
  
  return opponentMove;
}

function calculateWinner(yourMove, opponentMove) {
  switch(yourMove) {
    case 'rock':
      if(opponentMove === 'rock') {
        return 'draw';
      } else if (opponentMove === 'scissors') {
        youWin();
      } else {
        youLose();
      }
      break;
    case 'paper':
      if(opponentMove === 'paper') {
        return 'draw';
      } else if (opponentMove === 'rock') {
        youWin();
      } else {
        youLose();
      }
      break;
    case 'scissors':
      if(opponentMove === 'scissors') {
        return 'draw';
      } else if (opponentMove === 'paper') {
        youWin();
      } else {
        youLose();
      }
      break;
  }
}

function youWin() {
  var playerScore = $('.Player-count');
  var playerScoreUpdated = parseInt(playerScore.text()) + 1;
  playerScore.text(playerScoreUpdated);
}

function youLose() {
  var computerScore = $('.Computer-count');
  var computerScoreUpdated = parseInt(computerScore.text()) + 1;
  computerScore.text(computerScoreUpdated);
}

In this childhood classic game of Rock Paper Scissors, Math.random is used to generate a randomized move for the computer playing as the opponent. It makes a pick from the three available moves.

Nandemo Webtools

Leave a Reply