JavaScript Project: Rock Paper Scissor Game and the Right Way to make it

JavaScript Project: Rock Paper Scissor Game and the Right Way to make it

·

5 min read

I recently started learning JavaScript (Join me on my #100DaysOfCode Challenge). Just when reading MDN docs was getting tiresome, I stumbled upon this simple project: Game of Rock Paper & Scissor. While the coding part was easy, this project helped me learn something more important - approaching a problem like a programmer. I realised that solving a problem like a programmer involves multiple steps and coding isn't the first one! This blog will help you understand these steps with the help of simple Rock, Paper & Scissor game. Let's start.

This was my first project so I chose a simple one. This project does not involve GUI and we are going to play the game through browser console only. Apart from the coding part, we are going to focus on learning to 'think like a programmer.'

So, how does a programmer approach a problem? Here are the steps:

  • Understanding the problem
  • Planning
  • Dividing the problem into smaller sub-problems
  • Coding

Let us understand each of these steps while we build our project:

  1. Understanding the problem
    You should have absolute clarity about the problem (You might want to check out Rock Paper Scissor: Step by step guide). To check if you have understood the problem, try explaining the problem statement to someone else. You understand the best while teaching!
  2. Planning It is tempting to start coding right away, but hold on! Plan it first. Ask yourself questions. For eg.

    • Is there an input?
    • What is the desired output?
    • How am I processing the input to arrive at the desired output?

    Let us try answering these questions for our project

    Is there an input?
    First input will come from the user. User will enter either rock, paper or scissor. Another implicit input is random item (rock or paper or scissor). This will be computer's pick.

    What is the desired output?
    User's choice, computer's choice, user's score, computer's score and the winner.

    How am I processing the input to arrive at the desired output?
    This needs us to think through the algorithm. Writing the logic down step by step in plain language is called 'Pseudocode'. This is very important, it helps us think algorithmically devoid of all the clutter.

  3. Pseudocode

    
     - User enters a choice from rock, paper or scissor
     - Computer generates a random choice from rock, paper or scissor
     - Compare two inputs
         - rock and paper (paper wins)
         - rock and scissor (rock wins)
         - rock and rock (tie)
         - paper and rock (paper wins)
         - paper and scissor (scissor wins)
         - paper and paper (tie)
         - scissor and rock (rock wins)
         - scissor and paper (scissor wins)
         - scissor and scissor (tie)
     - Two Counter variables for scores of user and computer. Increment either of them in case of a win and none of them in case of a tie.
     - Repeat these steps five times for five rounds
     - Display the final scores on console along with the winner.
    

If you have noticed, we inadvertently divided the problem into smaller sub-problems and made it easier. In fact, approaching a big problem right away is almost a sure shot way to mess it up. Dividing a problem into smaller, easier ones is the right approach. Now let us solve the sub-problems one by one:

Create a blank HTML doc with <script>. We don't need HTML code yet since we are going to use console to play the game.

  • First, declare the required variables
      let userScore = 0;  
      let compScore = 0;  
      let winMsg = "You Won!";  
      let loseMsg = "You lost to Computer!";  
      let drawMsg = "It's a draw!";
    
  • User inputs a choice from rock, paper or scissor:
    We can do this with a prompt to the user.

    prompt("Rock or Paper or Scissor?","");
    
  • Computer generates a random choice from rock, paper or scissor:
    This would need a function which randomly generates a number between 0 and 2. 0 = rock, 1 = paper, 2 = scissor

    function computerPlay() {
      let compChoice = Math.floor(Math.random() * 3);
      switch (compChoice) {
          case 0:
              return "rock";
              break;
          case 1:
              return "paper";
              break;
          case 2:
              return "scissor";
              break;
      }
    }
    
  • Comparing the inputs:
    This needs another function. It will compare the inputs, handle the counters and return the result.

    function result(playerSelection, computerSelection) {
      while (playerSelection === "rock") {
          if (computerSelection === "paper") {
              compScore++;
              return `Your score: ${userScore}   Computer's score: ${compScore}`;
          } else if (computerSelection === "scissor") {
              userScore++;
              return `Your score: ${userScore}   Computer's score: ${compScore}`;
          } else {
              return `Your score: ${userScore}   Computer's score: ${compScore}`;
          }
      }
    

    Try and do this for other input combinations

  • Repeat these steps five times for five rounds:
    What comes to mind when you see 'Repeat', 'five times'? Yes, a for loop. We need a function which calls the above functions five times and at the end of five rounds, returns the final result.

    function game() {
      for (let i = 0; i < 5; i++) {
          let computerSelection = computerPlay();
          let playerSelection = prompt("Rock or Paper or Scissor?", "");
          console.log(`Your Selection: ${playerSelection.toUpperCase()} Computer Selection: ${computerSelection.toUpperCase()}
      ${result(playerSelection.toLowerCase(),computerSelection)}`);
      }
      if (userScore > compScore) {
          return winMsg;
      } else if (userScore < compScore) {
          return loseMsg;
      } else {
          return drawMsg;
      }
    }
    

Call the game() function and you are ready to play. That's it, you just built a Rock Paper Scissor game!