Coding classic

html, css, javascript, react, python

Step-by-Step Guide: How to Build a Rock Paper Scissors Game Using HTML, CSS, and JavaScript

Get ready to code your own classic game! This tutorial will guide you through building a digital version of Rock, Paper, Scissors using HTML, CSS, and JavaScript. Whether you’re a coding expert or just starting out, this step-by-step guide will empower you to create a fun and interactive game experience.

This tutorial will walk you through the process of bringing Rock, Paper, Scissors to life. You’ll use HTML to build the game’s structure, CSS to style it with an appealing design, and JavaScript to add the interactive gameplay. You’ll learn how to capture user choices, calculate the results, and create an engaging experience that captures the excitement of this classic game.

By the end of this tutorial, you’ll have a fully functional Rock, Paper, Scissors game ready to play. But that’s not all! You’ll also gain valuable knowledge about front-end development, using HTML, CSS, and JavaScript. Get ready to unleash your creativity and coding skills as you build your own interactive game!

This HTML file lays the groundwork for our Rock, Paper, Scissors game. It includes sections to display the game’s results, show the player’s and computer’s choices, and provide buttons for Rock, Paper, and Scissors. The structure is enhanced by a separate CSS file (style.css) for styling and a JavaScript file (script.js) to handle the game’s logic.

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Sets the character encoding for the document -->
  <meta charset="UTF-8">
  <!-- Title of the webpage as it appears in the browser tab -->
  <title>CodePen - Rock Paper Scissors Game</title>
  <!-- Links to an external CSS file for styling the page -->
  <link rel="stylesheet" href="./style.css">
</head>
<body>

<!-- Main container for the Rock Paper Scissors game -->
<section class="container">
  
  <!-- Container for displaying the results of the game -->
  <div class="result_field">
    
    <!-- Container for the result images of the user and CPU -->
    <div class="result_images">
      
      <!-- Span for displaying the user's result image -->
      <span class="user_result">
        <!-- Placeholder image for user's choice (e.g., Rock) -->
        <img src="http://codingstella.com/wp-content/uploads/2024/01/download.png" alt="Rock Image" />
      </span>
      
      <!-- Span for displaying the CPU's result image -->
      <span class="cpu_result">
        <!-- Placeholder image for CPU's choice (e.g., Rock) -->
        <img src="http://codingstella.com/wp-content/uploads/2024/01/download.png" alt="Rock Image" />
      </span>
    </div>
    
    <!-- Div to display the result message (e.g., Let's Play, You Win, You Lose) -->
    <div class="result">Let's Play!!</div>
  </div>

  <!-- Container for the player's options: Rock, Paper, Scissors -->
  <div class="option_images">
    
    <!-- Option for Rock -->
    <span class="option_image">
      <!-- Image and label for Rock -->
      <img src="http://codingstella.com/wp-content/uploads/2024/01/download.png" alt="Rock Image" />
      <p>Rock</p>
    </span>
    
    <!-- Option for Paper -->
    <span class="option_image">
      <!-- Image and label for Paper -->
      <img src="http://codingstella.com/wp-content/uploads/2024/01/download-1.png" alt="Paper Image" />
      <p>Paper</p>
    </span>
    
    <!-- Option for Scissors -->
    <span class="option_image">
      <!-- Image and label for Scissors -->
      <img src="http://codingstella.com/wp-content/uploads/2024/01/download-2.png" alt="Scissors Image" />
      <p>Scissors</p>
    </span>
  </div>
</section>

<!-- Link to the external JavaScript file that contains the game logic -->
<script src="./script.js"></script>

</body>
</html>

css

This CSS code creates the visual style for a Rock, Paper, Scissors game. It uses the Poppins font, centers the layout, and styles elements like the result displays, hand animations, and choice buttons. The design focuses on making the game visually engaging and easy to understand.

/* Import Google font - Poppins */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap");

* {
  margin: 0; /* Remove default margin */
  padding: 0; /* Remove default padding */
  box-sizing: border-box; /* Include padding and border in the element's width and height */
  font-family: "Poppins", sans-serif; /* Apply the Poppins font to all elements */
}

body {
  height: 100vh; /* Set the body's height to 100% of the viewport height */
  display: flex; /* Use Flexbox for layout */
  align-items: center; /* Vertically center the content */
  justify-content: center; /* Horizontally center the content */
  background: #14171e; /* Set a dark background color */
}

::selection {
  color: #fff; /* Text color when selected */
  background-color: #000; /* Background color when selected */
}

.container {
  padding: 2rem 7rem; /* Padding inside the container */
  border-radius: 10px; /* Rounded corners */
  background: #fff; /* White background color */
  box-shadow: 0 5px 10px rgba(255, 255, 255, 0.1); /* Subtle shadow around the container */
}

.result_images {
  display: flex; /* Use Flexbox to align images */
  column-gap: 7rem; /* Space between user and CPU images */
}

.container.start .user_result {
  transform-origin: left; /* Set the origin point for transformations to the left side */
  animation: userShake 0.7s ease infinite; /* Apply a shaking animation to the user's result */
}

@keyframes userShake {
  50% {
    transform: rotate(10deg); /* Rotate the image by 10 degrees at the midpoint of the animation */
  }
}

.container.start .cpu_result {
  transform-origin: right; /* Set the origin point for transformations to the right side */
  animation: cpuShake 0.7s ease infinite; /* Apply a shaking animation to the CPU's result */
}

@keyframes cpuShake {
  50% {
    transform: rotate(-10deg); /* Rotate the image by -10 degrees at the midpoint of the animation */
  }
}

.result_images img {
  width: 100px; /* Set the width of the result images */
}

.user_result img {
  transform: rotate(90deg); /* Rotate the user's result image by 90 degrees */
}

.cpu_result img {
  transform: rotate(-90deg) rotateY(180deg); /* Rotate the CPU's result image by -90 degrees and flip it horizontally */
}

.result {
  text-align: center; /* Center the result text */
  font-size: 2rem; /* Set the font size of the result text */
  color: #de0d64; /* Set the text color */
  margin-top: 1.5rem; /* Add space above the result text */
}

.option_image img {
  width: 50px; /* Set the width of the option images */
}

.option_images {
  display: flex; /* Use Flexbox to align option images */
  align-items: center; /* Vertically align option images */
  margin-top: 2.5rem; /* Add space above the option images */
  justify-content: space-between; /* Distribute space between the option images */
}

.container.start .option_images {
  pointer-events: none; /* Disable pointer events when the game is in progress */
}

.option_image {
  display: flex; /* Use Flexbox to align image and text vertically */
  flex-direction: column; /* Stack image and text vertically */
  align-items: center; /* Center the content horizontally */
  opacity: 0.5; /* Set initial opacity for inactive state */
  cursor: pointer; /* Change the cursor to a pointer on hover */
  transition: opacity 0.3s ease; /* Smooth transition for opacity change */
}

.option_image:hover {
  opacity: 1; /* Increase opacity on hover */
}

.option_image.active {
  opacity: 1; /* Set full opacity for the active option */
}

.option_image img {
  pointer-events: none; /* Disable pointer events on the image itself */
}

.option_image p {
  color: #3477eb; /* Set text color for option labels */
  font-size: 1.235rem; /* Set font size for option labels */
  margin-top: 1rem; /* Add space above the option labels */
  pointer-events: none; /* Disable pointer events on the text */
}

JavaScript :

This browser-based JavaScript implementation brings the classic Rock, Paper, Scissors game to life. The code sets up an interactive user interface where players can click on their preferred option. Upon selection, the program captures the user’s choice and simultaneously generates a random move for the computer opponent.

The game’s core logic is then executed, comparing the player’s selection against the computer’s random choice. Based on the traditional rules of Rock, Paper, Scissors, the code determines the winner of each round.

As the game progresses, the interface dynamically updates to reflect the current state. It displays both the player’s and computer’s choices, and promptly announces the outcome of each round. This creates an engaging and responsive gaming experience, where each interaction leads to a unique result.

The combination of user input handling, randomized computer decisions, and real-time display updates results in a fully functional and entertaining digital version of the timeless Rock, Paper, Scissors game.

// Get DOM elements
const gameContainer = document.querySelector(".container"), // The container holding the game
  userResult = document.querySelector(".user_result img"), // Image element showing the user's choice
  cpuResult = document.querySelector(".cpu_result img"), // Image element showing the CPU's choice
  result = document.querySelector(".result"), // Element displaying the result of the game
  optionImages = document.querySelectorAll(".option_image"); // All the option images (Rock, Paper, Scissors)

// Loop through each option image element
optionImages.forEach((image, index) => {
  // Add a click event listener to each option image
  image.addEventListener("click", (e) => {
    // Add "active" class to the clicked image
    image.classList.add("active");

    // Reset user and CPU result images to default Rock image
    userResult.src = cpuResult.src =
      "http://codingstella.com/wp-content/uploads/2024/01/download.png";
    result.textContent = "Wait..."; // Display waiting text

    // Loop through each option image again
    optionImages.forEach((image2, index2) => {
      // Remove "active" class from all option images except the clicked one
      index !== index2 && image2.classList.remove("active");
    });

    // Add "start" class to container to trigger animations
    gameContainer.classList.add("start");

    // Set a timeout to delay the result calculation
    let time = setTimeout(() => {
      // Remove "start" class from container to stop animations
      gameContainer.classList.remove("start");

      // Get the source of the clicked option image
      let imageSrc = e.target.querySelector("img").src;
      // Set the user image to the clicked option image
      userResult.src = imageSrc;

      // Generate a random number between 0 and 2
      let randomNumber = Math.floor(Math.random() * 3);
      // Create an array of CPU image options
      let cpuImages = [
        "http://codingstella.com/wp-content/uploads/2024/01/download.png", // Rock
        "http://codingstella.com/wp-content/uploads/2024/01/download-1.png", // Paper
        "http://codingstella.com/wp-content/uploads/2024/01/download-2.png" // Scissors
      ];
      // Set the CPU image to a random option from the array
      cpuResult.src = cpuImages[randomNumber];

      // Assign a letter value to the CPU option (R for Rock, P for Paper, S for Scissors)
      let cpuValue = ["R", "P", "S"][randomNumber];
      // Assign a letter value to the clicked option (based on index)
      let userValue = ["R", "P", "S"][index];

      // Create an object with all possible outcomes
      let outcomes = {
        RR: "Draw", // Rock vs Rock
        RP: "Cpu", // Rock vs Paper
        RS: "User", // Rock vs Scissors
        PP: "Draw", // Paper vs Paper
        PR: "User", // Paper vs Rock
        PS: "Cpu", // Paper vs Scissors
        SS: "Draw", // Scissors vs Scissors
        SR: "Cpu", // Scissors vs Rock
        SP: "User" // Scissors vs Paper
      };

      // Look up the outcome value based on user and CPU options
      let outComeValue = outcomes[userValue + cpuValue];

      // Display the result
      result.textContent =
        userValue === cpuValue ? "Match Draw" : `${outComeValue} Won!!`;
    }, 2500); // 2.5 seconds delay before showing result
  });
});

In summary, this Rock, Paper, Scissors game, built using HTML, CSS, and JavaScript, transforms the traditional game into an interactive digital experience. It provides an engaging platform where players can make their selections and challenge the CPU.

Step-by-Step Guide: How to Build a Rock Paper Scissors Game Using HTML, CSS, and JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top