DEV Community

Cover image for Building Your First Rock Paper Scissors Game: A Beginner's Guide
Aniket
Aniket

Posted on

Building Your First Rock Paper Scissors Game: A Beginner's Guide

Are you a budding web enthusiast looking to dip your toes into the world of web development? If you've just started your journey and want to create something fun and interactive, you're in the right place. In this beginner-friendly blog post, we'll walk you through the process of building your very own Rock Paper Scissors game using HTML, CSS, and JavaScript.


What is Rock Paper Scissors?

Ofc you're familiar with this game but if you aren't here's a quick summary :

Rock Paper Scissors is a classic hand game played between two people. The game has three possible outcomes other than a tie: Rock crushes Scissors, Scissors cuts Paper, and Paper covers Rock. It's a simple yet entertaining game that we'll bring to life on your web page.


Prerequisites

Before we dive into coding, make sure you have the following:

  • A basic understanding of HTML, CSS, and JavaScript.
  • A code editor like Visual Studio Code, Sublime Text, or any other of your choice.
  • A passion for learning and a desire to have fun while coding!

Let's Get Started!

Setting Up Your HTML

We'll begin by creating the structure of our web page using HTML. Open your code editor and follow these steps:

As we need to have all the other files connected we need to link them to our HTML file.

Furthermore we can add PRESS START 2P which is a cool font for a game which gives it a retro and gamifying feel.

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/index.css"> <!-- Link to your CSS file -->
    <script src="src/index.js" async></script> <!-- Link to your JavaScript file -->
    <link href='https://fonts.googleapis.com/css?family=Press Start 2P' rel='stylesheet'> <!-- A cool retro font -->
    <title>RPS</title>
</head>

Enter fullscreen mode Exit fullscreen mode

Now we need basic buttons that when we click the JS knows what exactly we have clicked

To do so we will have two sets of buttons, one for the Computer and other for the user, but only make the user one's clickable
Computer side has given buttons because buttons can transform their positions unlike images which can't. We will be using transform to show more interactivity.

Be sure add images to Rock Paper and Scissors in your code. I have rotated them to make the orientation of those pictures correct.

        <button  id="c1" >
            <img src="assets/paper.png" alt="paper" style="transform: rotate(90deg);" >
        </button>
        <button  id="c2" >
            <img src="assets/rock.png" alt="rock" style="transform: rotate(90deg);" >
        </button>
        <button  id="c3" >
            <img src="assets/sissors.png" alt="scissors" style="transform: rotate(90deg);" >
        </button>


        <button id="b1" >
            <img src="assets/paper.png" alt="paper" style="transform: rotate(-90deg);">
        </button>
        <button id="b2" >
            <img src="assets/rock.png" alt="rock" style="transform: rotate(-90deg);">
        </button>
        <button id="b3" >
            <img src="assets/sissors.png" alt="scissors" style="transform: rotate(-90deg);">
        </button>
Enter fullscreen mode Exit fullscreen mode

We also too need a scoreboard, other stats and a reset button.

    <div class="infocon">
        <h1>Rock Paper Scissors</h1>
        <h1 id="wl"></h1>
    </div>

    <div class="details">
        <h3 >Tries:<span id="try">0</span>/5</h3>
        <h3 >Wins :<span id="wins">0</span></h3>
        <h3 >Lose :<span id="lose">0</span></h3>
        <h3 >Ties :<span id="ties">0</span></h3>
        <h3>__________</h3>
        <h2 >WINNER:<br><br><span id="total"></span></h2><br>
        <h3>__________</h3>
        <button id="reset" onclick="reset()">RESET</button><br>
    </div>
Enter fullscreen mode Exit fullscreen mode

Adding CSS to your Html

Now, let's style our game using CSS. Create a new CSS file (e.g., index.css) and add the following styles:
CSS depends on your own taste, feel free to make it in your own style.

/* Set the font and background color */
body {
    font-family: 'Press Start 2P';
    background-color: #C8F1F3;
}

/* Style buttons */
button {
    border: 0px;
    background-color: #C8F1F3;
}

/* Add animation to selected buttons */
.selected {
    transform: translateX(0%) translateY(-175%);
    transition: transform 1.5s ease-in-out;
}
Enter fullscreen mode Exit fullscreen mode

You can take reference for CSS if you want from here

In this CSS code, we've set the font, background color, and styles for buttons. The .selected class adds a cool animation to the selected buttons.


Adding JavaScript for Interactivity

With your HTML and CSS in place, it's time to add JavaScript to make your game interactive and functional. Below, we'll break down the key JavaScript functions and their roles in your Rock Paper Scissors game.

  • Initializing Variables
let computerChoice = 0;
let a= 0;
const wl=document.getElementById("wl");
let wlt=[0,0,0];
let tries=0;
const W= document.getElementById("wins");
const L= document.getElementById("lose");
const T= document.getElementById("ties");
const Tr= document.getElementById("try");
const Total= document.getElementById("total");

Enter fullscreen mode Exit fullscreen mode

In this section, you declare and initialize various variables that will be used to keep track of game statistics and elements on your web page. These variables will store information like the user's and computer's choices, win/loss/tie counts, and references to HTML elements where you'll display game outcomes.

  • getComputerChoice() Function
function getComputerChoice() {
    return Math.floor(Math.random() * 3) + 1;
}
Enter fullscreen mode Exit fullscreen mode

This function generates a random number (1, 2, or 3) to simulate the computer's choice in the game. Each number corresponds to Rock, Paper, or Scissors, respectively.

  • AnimateComp() Function
function AnimateComp(objc) {
    console.log("anim")
    document.getElementById(objc).classList.add("selectedC");
    setTimeout(function () {
        document.getElementById(objc).classList.remove("selectedC");
    }, 3000);
}
Enter fullscreen mode Exit fullscreen mode

AnimateComp() is responsible for adding and removing a class called "selectedC" from the computer's choice button, creating an animation effect when the computer makes a selection. This function adds a class to the button and removes it after 3 seconds to reset the animation.

  • determineWinner() Function
function determineWinner(userChoice, computerChoice) {
    computerChoice= a;

    if (userChoice === computerChoice) {
        wl.innerHTML="ITS A TIE";
        wlt[2]+=1;
    } else if ((userChoice===3 && computerChoice===1)||(userChoice===2 && computerChoice===3)||(userChoice===1 && computerChoice===2)){
        wl.innerHTML="YOU WONN!";
        wlt[0]+=1;
    } else {
        wl.innerHTML="YOU LOSEE!";
        wlt[1]+=1;
    }
    // ...Above code is available on GitHub
}
Enter fullscreen mode Exit fullscreen mode

determineWinner() takes two arguments: userChoice and computerChoice. It calculates the game result and updates the display accordingly. If it's a tie, a message is shown, and the tie count is incremented. If the user wins or loses, the respective message is displayed, and the win or loss count is updated. The function also keeps track of the number of tries and calculates the overall winner after 5 tries.

  • userChoiceHandler() Function
function userChoiceHandler(userChoice) {
    setTimeout(function () {
       determineWinner(userChoice, computerChoice);
    }, 4000);
}
Enter fullscreen mode Exit fullscreen mode

userChoiceHandler() is called when the user makes a choice by clicking a button. It sets a timeout of 4 seconds (4000 milliseconds) before calling determineWinner(). This delay simulates the computer making its choice before revealing the result.

  • Event Listeners for User Choices
document.getElementById("b1").addEventListener("click", function () {
    animateSelection("b1");
    setTimeout(function () {
        userChoiceHandler(1);
    }, 1000);
});
//Same for other buttons too
Enter fullscreen mode Exit fullscreen mode
  • animateSelection() Function
function animateSelection(obj) {
    computerChoice = getComputerChoice();
    if(computerChoice===1){a= computerChoice;AnimateComp("c1")}
    else if(computerChoice===2){a=computerChoice;AnimateComp("c2")}
    else{a=computerChoice;AnimateComp("c3")} 
    document.getElementById(obj).classList.add("selected");
    setTimeout(function () {
        document.getElementById(obj).classList.remove("selected");
    }, 3000);
}
Enter fullscreen mode Exit fullscreen mode

animateSelection() is responsible for simulating the computer's choice, animating the user's choice button, and adding/removing the "selected" class to create a visual effect. The computer's choice is determined, the animation is applied to the user's choice button, and the class is removed after 3 seconds.

  • reset() Function
function reset(){
    wlt=[0,0,0];
    tries=0;
    wl.innerHTML="";
    W.innerHTML=wlt[0];
    L.innerHTML=wlt[1];
    T.innerHTML=wlt[2];
    Tr.innerHTML=tries;
    Total.innerHTML=""
}
Enter fullscreen mode Exit fullscreen mode

reset() is a function to reset the game statistics when the "RESET" button is clicked. It clears the win, loss, tie, and try counts, as well as any displayed messages.

For the above code visit my GitHub


END RESULT

Image description


Conclusion

With these JavaScript functions, your Rock Paper Scissors game is now fully functional and interactive. These code snippets handle everything from generating computer choices to determining winners and providing visual feedback to the user. You can further customize and enhance your game as you continue to explore the world of web development. Happy coding!

GITHUB for the above game


Follow and like for more such blogs.
Connect me on LinkedIn

Thanks for reading until the end.

Top comments (0)