Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App

Rock Paper and Scissor Game using JavaScript

Last Updated : 18 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Rock, paper, and scissors game is a simple fun game in which both players have to make a rock, paper, or scissors. It has only two possible outcomes a draw or a win for one player and a loss for the other player.

Screenshot-2023-12-19-193228

Prerequisites:

  • HTML
  • CSS
  • JavaScript

Approach

  • Start by creating the HTML structure for your Rock, Paper, and Scissor Game
  • Style your website using CSS to enhance its visual appeal and responsiveness.
  • In JavaScript, Create a function game() that will contain all the logic of the game.
  • Inside the function declare three variables playerScore, computerScore, and moves which will keep the record of the player's score, computer's score, and moves completed respectively.
  • Create a function playGame() and inside the function use DOM manipulation to get hold of all the three buttons we created in HTML for player input. Create an array playerOptions which will contain all three buttons as its elements. Similarly, create an array for computer options.
  • Use forEach() loop on playerOptions so that we can add an event listener on all buttons with a single piece of code. Inside the loop increment moves counter by 1 display moves left on the screen by subtracting moves from 10. Generate a random value for the computer option and compare it with the player's input.
  • Create a function winner() which will receive two arguments one the player's input and the other the computer's option  The function will decide who wins the point among the player and computer.
  • Create a function gameOver() which will display the final result with reload button. The function will be called when moves will become equals to 10.
  • Call the playGame() function inside the game() function.

Example: This example shoes the implementation of the above-explained appraoch.

HTML
<!-- index.html -->  <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width,                     initial-scale=1.0">     <link rel="stylesheet" href="styles.css">     <title>Rock Paper Scissor</title> </head> <body>     <section class="game">         <!--Title -->         <div class="title">Rock Paper Scissor</div>                    <!--Display Score of player and computer -->         <div class="score">               <div class="playerScore">                 <h2>Player</h2>                 <p class="p-count count">0</p>              </div>                    <div class="computerScore">                 <h2>Computer</h2>                 <p class="c-count count">0</p>              </div>         </div>                <div class="move">Choose your move</div>                    <!--Number of moves left before game ends -->         <div class="movesleft">Moves Left: 10 </div>                    <!--Options available to player to play game -->         <div class="options">             <button class="rock">Rock</button>             <button class="paper">Paper</button>             <button class="scissor">Scissors</button>             </div>                    <!--Final result of game -->         <div class="result"></div>                    <!--Reload the game -->         <button class="reload"></button>      </section>      <script src="app.js"></script> </body> </html> 
CSS
/* styles.css */ /* universal selector - Applies to whole document */ *{     padding: 0;     margin: 0;     box-sizing: border-box;     background: #082c6c;     color: #fff; } /* To center everything in game */ .game{     display: flex;     flex-direction: column;     height: 100vh;     width: 100vw;     justify-content: center;     align-items: center; }  /* Title of the game */ .title{     position: absolute;     top: 0;     font-size: 4rem;     z-index: 2; }  /* Score Board */ .score{     display: flex;     width: 30vw;     justify-content: space-evenly;     position: absolute;     top: 70px;     z-index: 1; }  /* Score  */ .p-count,.c-count{     text-align: center;     font-size: 1.5rem;     margin-top: 1rem; }  /* displaying three buttons in one line */ .options{     display: flex;     width: 50vw;     justify-content: space-evenly;     margin-top: 2rem; }  /* Styling on all three buttons */ .rock, .paper, .scissor{     padding: 0.8rem;     width: 100px;     border-radius: 10px;     background: green;     outline: none;     border-color: green;     border: none;     cursor: pointer; }  .move{     font-size: 2rem;     font-weight: bold; }  /* Reload button style */ .reload {     display: none;     margin-top: 2rem;     padding: 1rem;     background: green;     outline: none;     border: none;     border-radius: 10px;     cursor: pointer; }  .result{     margin-top: 20px;     font-size: 1.2rem; }  /* Responsive Design */ @media screen and (max-width: 612px) {       .title{         text-align: center;     }     .score{         position: absolute;         top: 200px;         width: 100vw;     }     .options{         width: 100vw;     } 
JavaScript
// app.js  // Complete logic of game inside this function const game = () => {     let playerScore = 0;     let computerScore = 0;     let moves = 0;       // Function to      const playGame = () => {         const rockBtn = document.querySelector('.rock');         const paperBtn = document.querySelector('.paper');         const scissorBtn = document.querySelector('.scissor');         const playerOptions = [rockBtn, paperBtn, scissorBtn];         const computerOptions = ['rock', 'paper', 'scissors']          // Function to start playing game         playerOptions.forEach(option => {             option.addEventListener('click', function () {                  const movesLeft = document.querySelector('.movesleft');                 moves++;                 movesLeft.innerText = `Moves Left: ${10 - moves}`;                   const choiceNumber = Math.floor(Math.random() * 3);                 const computerChoice = computerOptions[choiceNumber];                  // Function to check who wins                 winner(this.innerText, computerChoice)                  // Calling gameOver function after 10 moves                 if (moves == 10) {                     gameOver(playerOptions, movesLeft);                 }             })         })      }      // Function to decide winner     const winner = (player, computer) => {         const result = document.querySelector('.result');         const playerScoreBoard = document.querySelector('.p-count');         const computerScoreBoard = document.querySelector('.c-count');         player = player.toLowerCase();         computer = computer.toLowerCase();         if (player === computer) {             result.textContent = 'Tie'         }         else if (player == 'rock') {             if (computer == 'paper') {                 result.textContent = 'Computer Won';                 computerScore++;                 computerScoreBoard.textContent = computerScore;              } else {                 result.textContent = 'Player Won'                 playerScore++;                 playerScoreBoard.textContent = playerScore;             }         }         else if (player == 'scissors') {             if (computer == 'rock') {                 result.textContent = 'Computer Won';                 computerScore++;                 computerScoreBoard.textContent = computerScore;             } else {                 result.textContent = 'Player Won';                 playerScore++;                 playerScoreBoard.textContent = playerScore;             }         }         else if (player == 'paper') {             if (computer == 'scissors') {                 result.textContent = 'Computer Won';                 computerScore++;                 computerScoreBoard.textContent = computerScore;             } else {                 result.textContent = 'Player Won';                 playerScore++;                 playerScoreBoard.textContent = playerScore;             }         }     }      // Function to run when game is over     const gameOver = (playerOptions, movesLeft) => {          const chooseMove = document.querySelector('.move');         const result = document.querySelector('.result');         const reloadBtn = document.querySelector('.reload');          playerOptions.forEach(option => {             option.style.display = 'none';         })           chooseMove.innerText = 'Game Over!!'         movesLeft.style.display = 'none';          if (playerScore > computerScore) {             result.style.fontSize = '2rem';             result.innerText = 'You Won The Game'             result.style.color = '#308D46';         }         else if (playerScore < computerScore) {             result.style.fontSize = '2rem';             result.innerText = 'You Lost The Game';             result.style.color = 'red';         }         else {             result.style.fontSize = '2rem';             result.innerText = 'Tie';             result.style.color = 'grey'         }         reloadBtn.innerText = 'Restart';         reloadBtn.style.display = 'flex'         reloadBtn.addEventListener('click', () => {             window.location.reload();         })     }       // Calling playGame function inside game     playGame();  }  // Calling the game function game(); 

Output:


P

pritishnagpal
Improve
Article Tags :
  • Technical Scripter
  • JavaScript
  • Web Technologies
  • Technical Scripter 2020
  • JavaScript-Questions

Similar Reads

    Create a snake game using HTML, CSS and JavaScript
    Snake Game is a single-player game where the snake gets bigger by eating the food and tries to save itself from the boundary of the rectangle and if the snake eats their own body the game will be over.Game Rules:If the snake goes out of the boundary or eats its own body the game will be over.Prerequ
    4 min read
    Design Dragon's World Game using HTML CSS and JavaScript
    Project Introduction: "Dragon's World" is a game in which one dragon tries to save itself from the other dragon by jumping over the dragon which comes in its way. The score is updated when one dragon saves himself from the other dragon.  The project will contain HTML, CSS and JavaScript files. The H
    6 min read
    Word Guessing Game using HTML CSS and JavaScript
    In this article, we will see how can we implement a word-guessing game with the help of HTML, CSS, and JavaScript. Here, we have provided a hint key & corresponding total number of gaps/spaces depending upon the length of the word and accept only a single letter as an input for each time. If it
    4 min read
    Build a Memory Card Game Using HTML CSS and JavaScript
    A memory game is a type of game that can be used to test or check the memory of a human being. It is a very famous game. In this game, the player has some cards in front of him and all of them facing down initially. The player has to choose a pair of cards at one time and check whether the faces of
    6 min read
    Create a Simon Game using HTML CSS & JavaScript
    In this article, we will see how to create a Simon Game using HTML, CSS, and JavaScript. In a Simon game, if the player succeeds, the series becomes progressively longer and more complex. Once the user is unable to repeat the designated order of the series at any point, the game is over.Prerequisite
    5 min read
    Create a Minesweeper Game using HTML CSS & JavaScript
    Minesweeper is a classic puzzle game that challenges your logical thinking and deduction skills. It's a great project for developers looking to improve their front-end web development skills. In this article, we'll walk through the steps to create a Minesweeper game using HTML, CSS, and JavaScript.
    4 min read
    Whack-a-Mole Game using HTML CSS and JavaScript
    Whack-A-Mole is a classic arcade-style game that combines speed and precision. The game is set in a grid of holes, and the objective is to "whack" or hit the moles that randomly pop up from these holes. In this article, we are going to create Whack-a-Mole using HTML, CSS and JavaScript.Preview Image
    3 min read
    Simple HTML CSS and JavaScript Game
    Tap-the-Geek is a simple game, in which the player has to tap the moving GeeksForGeeks logo as many times as possible to increase their score. It has three levels easy, medium, and hard. The speed of the circle will be increased from level easy to hard. I bet, it is very difficult for the players to
    4 min read
    Design Hit the Mouse Game using HTML, CSS and Vanilla Javascript
    In this article, we are going to create a game in which a mouse comes out from the holes, and we hit the mouse with a hammer to gain points. It is designed using HTML, CSS & Vanilla JavaScript.HTML Code:First, we create an HTML file (index.html).Now, after creating the HTML file, we are going to
    5 min read
    Create a 2D Brick Breaker Game using HTML CSS and JavaScript
    In this article, we will see how to create a 2D Brick Breaker Game using HTML CSS & JavaScript. Most of you already played this game on your Mobile Phones where you control a paddle to bounce a ball, aiming to demolish a wall of bricks arranged at the top of the screen. 2D Brick Breaker Game is
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences