Saturday, October 5, 2024
Google search engine
HomeLanguagesJavascriptRock, Paper and Scissor Game using Javascript

Rock, Paper and Scissor Game using Javascript

Introduction:

Rock, paper, and scissors game is a simple fun game in which both the 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. We will be designing the game using JavaScript where a player will be playing against the computer. In total there will be 10 moves. The player has to choose one option among the rock, paper, and scissors. A random option will be generated from the computer’s side and the one who wins will get one point every time. After 10 moves are over the final result will be displayed on the screen with a button to restart the game. The game will be completely responsive so that it can be played on every device.

The HTML Layout:

HTML gives the basic structure of the game. styles.css file is linked in the head tag which will be used for styling the HTML.

Description of elements use in code is below:

  • A div with the class title is used to display the title on the screen.
  • A div with a class score contains two more div which will display the score of the player and computer.
  • Div with the class move just displays a text and div with class movesleft will show the number of moves left before the game ends.
  • A div with a class option contains three button rock, paper, and scissors which the user can use to give the input.
  • A div with the class result will display the result of every move and the final result after 10 moves and the button with class reload will allow reloading the game.

CSS Styling: This styling is used for the game. You can change the styles as per your needs.

The logic using JavaScript:

The main logic of the game is created by using JavaScript. We will be performing DOM manipulation so basic knowledge of JavaScript is enough to build the game.

Follow steps 

  • Create a function game() that will contain all the logic of the game.
  • Inside the function declare three variables playerScore, computerScore, 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.
  • Now call the game() function at the end of the file.

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: Click here to see live code output

RELATED ARTICLES

Most Popular

Recent Comments