How to Build a Rock Paper Scissors Game in Vanilla Javascript | Javascript Project

5 min read 5 months ago
Published on Aug 02, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will create a Rock Paper Scissors game using Vanilla JavaScript. This application will be mobile-friendly, feature animations, maintain persistent data for scores, and include accessibility considerations. Let’s get started by building the foundation for our game.

Chapter 1: HTML Structure

  1. Create Project Structure

    • Create a folder named dist for distribution.
    • Inside dist, create an index.html file.
  2. Set Up Basic HTML

    • Use Emmet abbreviation by typing ! and pressing Enter to generate a basic HTML structure.
    • Change the document title to "Rock Paper Scissors".
  3. Link Google Fonts

    • Visit Google Fonts and select the Montserrat font (600 weight).
    • Copy the link and paste it in the <head> section of your HTML:
      <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@600&display=swap" rel="stylesheet">
      
  4. Define HTML Structure

    • Use semantic HTML elements instead of generic <div> elements for better accessibility.
    • Add a <main> element with sections for scoreboard, player board, and computer board.
    • Example structure:
      <main>
        <h1 class="center" tabindex="0">Rock Paper Scissors</h1>
        <section id="scoreboard" class="scoreboard">
          <h2 class="off-screen">Scoreboard</h2>
          <!-- Add scoreboard content here -->
        </section>
        <section id="player-board" class="player-board">
          <h2 id="p1-msg" class="center" aria-label="Player one chooses" tabindex="0">Player One Chooses...</h2>
          <!-- Add player game board here -->
        </section>
        <section id="computer-board" class="computer-board">
          <h2 id="cp-msg" class="center" aria-label="Computer chooses" tabindex="0">Computer Chooses...</h2>
          <!-- Add computer game board here -->
        </section>
        <form>
          <button id="play-again" type="submit" class="play-again hidden">Play Again?</button>
        </form>
      </main>
      

Chapter 2: SCSS Compiler Setup

  1. Install SCSS Compiler

    • Install the Live Sass Compiler extension by Glenn Marks in Visual Studio Code.
  2. Create SCSS Folder Structure

    • Inside dist, create a folder named scss.
    • Inside the scss folder, create the following folders:
      • abstracts
      • base
      • components
      • layout
    • Create SCSS partials in their respective folders, starting with:
      • abstracts/_colors.scss
      • abstracts/_mixins.scss
      • base/_base.scss
      • components/_animations.scss
      • components/_utility.scss
      • layout/_gameboard.scss
      • layout/_scoreboard.scss
  3. Define Variables and Mixins

    • In _colors.scss, define color variables:

      $background-color: #000000;
      $text-color: #ffffff;
      
    • In _mixins.scss, create reusable mixins:

      @mixin flex-center {
        display: flex;
        justify-content: center;
        align-items: center;
      }
      
  4. Import SCSS Files

    • In main.scss, import all partials:
      @import 'abstracts/colors';
      @import 'abstracts/mixins';
      @import 'base/base';
      @import 'components/animations';
      @import 'components/utility';
      @import 'layout/gameboard';
      @import 'layout/scoreboard';
      

Chapter 3: SCSS Styles and Design

  1. Style the Body and Main Elements

    • Set global styles in _base.scss:
      body {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        background-color: $background-color;
        color: $text-color;
        font-family: 'Montserrat', sans-serif;
      }
      
  2. Scoreboard Styles

    • In _scoreboard.scss, create flex containers and styles for scoreboard elements:
      .scoreboard {
        width: 100%;
        max-width: 500px;
        margin: 0 auto;
        @include flex-center;
        flex-wrap: wrap;
      }
      
  3. Game Board Styles

    • In _gameboard.scss, style the game board and squares:
      .game-board {
        width: calc(100% - 5px);
        display: flex;
        justify-content: space-evenly;
      }
      .game-board__square {
        width: 30%;
        cursor: pointer;
      }
      
  4. Animations

    • Define animations in _animations.scss using keyframes for visual effects during gameplay.

Chapter 4: JavaScript Functionality

  1. Setup JavaScript Files

    • Inside dist, create a folder named js and create main.js and Game.js.
  2. Game Class Structure

    • In Game.js, define the game logic and player scores:
      export default class Game {
        constructor() {
          this.active = false;
          this.p1AllTime = 0;
          this.cpAllTime = 0;
          this.p1Session = 0;
          this.cpSession = 0;
        }
        startGame() { this.active = true; }
        endGame() { this.active = false; }
        // Add more methods as needed
      }
      
  3. Main JavaScript Logic

    • In main.js, initialize the app and add event listeners for gameplay:
      import Game from './Game.js';
      const game = new Game();
      document.addEventListener('DOMContentLoaded', initApp);
      function initApp() {
        // Initialize game and event listeners
      }
      
  4. Handling Player Choices

    • Add functionality to listen for player choices and update the display:
      function listenForPlayerChoice() {
        const playerImages = document.querySelectorAll('.player-board__square');
        playerImages.forEach(image => {
          image.addEventListener('click', (event) => {
            const playerChoice = event.target.id; // Get the player's choice
            // Handle game logic
          });
        });
      }
      

Chapter 5: Debugging

  • Test all functionalities to ensure the game works as expected.
  • Watch for common issues such as incorrect element IDs, missing event listeners, or CSS styles not applying.

Chapter 6: Testing Accessibility

  1. Install ChromeVox

    • Enable the ChromeVox screen reader extension to test the app’s accessibility.
  2. Keyboard Navigation

    • Ensure players can navigate using the keyboard and that all interactive elements are accessible.
  3. Verify Aria Labels

    • Check that all aria labels and messages are read correctly by the screen reader.

Conclusion

In this tutorial, you have learned to build a fully functional Rock Paper Scissors game using Vanilla JavaScript. You created an accessible, styled application with persistent data storage for scores. As a next step, consider enhancing the game further by adding new features or improving the UI. Happy coding!