Building a Rock - Paper - Scissors Game with HTML, CSS, and JavaScript

Rock - Paper - Scissors is a classic hand - game that has been around for ages. In the digital world, we can recreate this simple yet engaging game using web technologies like HTML, CSS, and JavaScript. HTML provides the structure of the game, CSS is used to style the game for an appealing look, and JavaScript adds the interactivity to make the game functional. This blog will guide you through the process of building a Rock - Paper - Scissors game step by step, covering fundamental concepts, usage methods, common practices, and best practices.

Table of Contents

  1. Fundamental Concepts
  2. Usage Methods
  3. Common Practices
  4. Best Practices
  5. Conclusion
  6. References

Fundamental Concepts

HTML Basics

HTML (HyperText Markup Language) is the standard markup language for creating web pages. It uses tags to define different elements on a page, such as headings, paragraphs, buttons, and images. For our Rock - Paper - Scissors game, we’ll use HTML to create the basic layout, including buttons for the user to select their choice and a display area for the game results.

CSS Basics

CSS (Cascading Style Sheets) is used to style HTML elements. It allows us to control the appearance of our web page, including colors, fonts, sizes, and layout. With CSS, we can make our Rock - Paper - Scissors game look more professional and visually appealing.

JavaScript Basics

JavaScript is a programming language that adds interactivity to web pages. It can be used to handle user input, perform calculations, and update the content of a web page dynamically. In our game, JavaScript will be responsible for determining the winner based on the user’s and the computer’s choices.

Usage Methods

Setting up the HTML Structure

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rock Paper Scissors</title>
    <link rel="stylesheet" href="styles.css">
</head>

<body>
    <h1>Rock Paper Scissors</h1>
    <div id="choices">
        <button id="rock">Rock</button>
        <button id="paper">Paper</button>
        <button id="scissors">Scissors</button>
    </div>
    <div id="result">
        <p>Make your choice!</p>
    </div>
    <script src="script.js"></script>
</body>

</html>

In this HTML code, we have a title for the game, a set of buttons for the user to choose from, and a div to display the game result. We also link an external CSS file for styling and an external JavaScript file for interactivity.

Styling with CSS

body {
    font-family: Arial, sans-serif;
    text-align: center;
    background-color: #f4f4f4;
}

h1 {
    color: #333;
}

#choices {
    margin-top: 20px;
}

button {
    padding: 10px 20px;
    margin: 0 10px;
    font-size: 16px;
    background-color: #007BFF;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}

#result {
    margin-top: 20px;
    font-size: 18px;
}

This CSS code styles the body, heading, buttons, and result display area. It gives the game a clean and modern look.

Adding Interactivity with JavaScript

const choices = ['rock', 'paper', 'scissors'];
const buttons = document.querySelectorAll('#choices button');
const resultDisplay = document.getElementById('result');

buttons.forEach(button => {
    button.addEventListener('click', () => {
        const userChoice = button.id;
        const computerChoice = choices[Math.floor(Math.random() * choices.length)];

        let outcome;
        if (userChoice === computerChoice) {
            outcome = 'It\'s a tie!';
        } else if (
            (userChoice === 'rock' && computerChoice === 'scissors') ||
            (userChoice === 'paper' && computerChoice === 'rock') ||
            (userChoice === 'scissors' && computerChoice === 'paper')
        ) {
            outcome = 'You win!';
        } else {
            outcome = 'You lose!';
        }

        resultDisplay.innerHTML = `You chose ${userChoice}, the computer chose ${computerChoice}. ${outcome}`;
    });
});

In this JavaScript code, we first define the possible choices. Then we select all the buttons and add a click event listener to each of them. When a button is clicked, we get the user’s choice and randomly select the computer’s choice. We then determine the outcome of the game and update the result display area.

Common Practices

Separation of Concerns

Separation of concerns means keeping different aspects of your code (HTML for structure, CSS for styling, and JavaScript for interactivity) in separate files. This makes the code easier to maintain and understand. In our game, we have an HTML file for the structure, a CSS file for styling, and a JavaScript file for the game logic.

Event Delegation

Event delegation is a technique where you attach a single event listener to a parent element instead of multiple listeners to individual child elements. In our game, we attach a click event listener to the parent #choices div instead of attaching separate listeners to each button. This reduces the number of event listeners and makes the code more efficient.

Best Practices

Code Readability

Use meaningful variable and function names. In our JavaScript code, we use names like userChoice, computerChoice, and outcome which clearly indicate what they represent. Also, add comments to your code to explain the purpose of different sections.

Error Handling

Although our simple game doesn’t have many error - prone areas, in more complex applications, it’s important to handle errors properly. For example, if there’s an issue with getting the user’s choice or generating the computer’s choice, you can use try - catch blocks to handle the errors gracefully.

Conclusion

Building a Rock - Paper - Scissors game with HTML, CSS, and JavaScript is a great way to learn the fundamentals of web development. By understanding the basic concepts, using proper usage methods, following common practices, and applying best practices, you can create a functional and visually appealing game. This project can also serve as a starting point for more complex web applications.

References