Sling Academy
Home/JavaScript/Building a Simple Browser Game with Basic JavaScript DOM Logic

Building a Simple Browser Game with Basic JavaScript DOM Logic

Last updated: December 12, 2024

Creating a simple browser game is a great project for anyone looking to deepen their understanding of JavaScript and the Document Object Model (DOM). This guide will walk through the steps of building a basic interactive game where the player controls an element to catch falling objects.

Setting Up the HTML Structure

We’ll start by setting up a basic HTML structure. This structure will contain elements to hold our game screen, the player character, and the falling objects.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Browser Game</title>
    <style>
        #gameContainer {
            width: 400px;
            height: 400px;
            border: 1px solid black;
            position: relative;
            overflow: hidden;
        }

        .player {
            width: 40px;
            height: 40px;
            background-color: blue;
            position: absolute;
            bottom: 0;
        }

        .fallingObject {
            width: 20px;
            height: 20px;
            background-color: red;
            position: absolute;
            top: 0;
        }
    </style>
</head>
<body>
    <div id="gameContainer">
        <div class="player" id="player"></div>
    </div>
    <script src="game.js"></script>
</body>
</html>

The above HTML code creates a game container in which the player and falling objects will interact. The styles ensure that the player stays at the bottom and allows for easy identification of game elements.

Setting Up JavaScript for Movement

Next, we will implement basic JavaScript logic to control the player's movement using the arrow keys. Add the following script to your game.js file.

document.addEventListener('DOMContentLoaded', () => {
    const player = document.getElementById('player');
    let leftPosition = 0;

    function moveLeft() {
        if (leftPosition > 0) {
            leftPosition -= 10;
            player.style.left = leftPosition + 'px';
        }
    }

    function moveRight() {
        if (leftPosition < 360) { // 400px (container width) - 40px (player width)
            leftPosition += 10;
            player.style.left = leftPosition + 'px';
        }
    }

    document.addEventListener('keydown', event => {
        if (event.key === 'ArrowLeft') {
            moveLeft();
        } else if (event.key === 'ArrowRight') {
            moveRight();
        }
    });
});

This script listens for keydown events and moves the player left or right within the game boundaries when the respective arrow key is pressed.

Implementing Falling Objects

Now, let's implement the logic for the falling objects. We need to create a new falling object at random positions at the top of the game container continuously. We'll use JavaScript intervals for this purpose.

function createFallingObject() {
    const gameContainer = document.getElementById('gameContainer');
    const object = document.createElement('div');
    object.className = 'fallingObject';
    object.style.left = Math.random() * 380 + 'px'; // Adjusted to fit within 400px width

    gameContainer.appendChild(object);
    let topPosition = 0;

    function drop() {
        if (topPosition < 380) { // 400px (container height) - 20px (object height)
            topPosition += 5;
            object.style.top = topPosition + 'px';
            requestAnimationFrame(drop);
        } else {
            gameContainer.removeChild(object);
        }
    }

    drop();
}

setInterval(createFallingObject, 2000); // Create a new object every 2 seconds

Here, createFallingObject is responsible for creating and animating the falling objects. A new object is added to the game container every two seconds.

Collision Detection

The next step is to detect collisions between the player and falling objects. We can do this by checking if the bounding boxes of the player and any falling object overlap.

function detectCollision(player, object) {
    const playerRect = player.getBoundingClientRect();
    const objectRect = object.getBoundingClientRect();

    return !(
        playerRect.top > objectRect.bottom ||
        playerRect.bottom < objectRect.top ||
        playerRect.right < objectRect.left ||
        playerRect.left > objectRect.right
    );
}

function checkCollisions() {
    const objects = document.querySelectorAll('.fallingObject');
    objects.forEach(object => {
        if (detectCollision(player, object)) {
            // Handle what happens on collision
            console.log('Collision!');
            object.remove(); // Remove object upon collision
        }
    });
}

setInterval(checkCollisions, 100); // Check for collisions every 0.1 seconds

The detectCollision function compares the positions of the player and falling objects to determine overlap. Upon collision, we handle it by removing the object from the DOM, and this happens every 100 milliseconds.

Conclusion

With these steps, you've created a basic yet fully functioning browser game using JavaScript DOM manipulation. This game covers a range of essential JavaScript concepts, including event handling, intervals, DOM manipulation, and collision detection. Try extending the game by adding scoring, improving graphics, or incorporating more complex mechanics to continue your learning journey.

Next Article: Creating Reusable DOM Snippets for Faster Prototyping in JavaScript

Previous Article: Animating Width and Height with JavaScript Updates

Series: JavaScript: Document Object Model Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration