Shawn Beaton I create 2d games with HTML divs, CSS Animations and Javascript.

How to build a game with HTML, CSS, and JavaScript

3 min read 989

The CSS and JavaScript logos.

So you want to use your basic knowledge of web development to create something a little cooler than a to-do app. Games are one of the best projects you can create, because they are very easily enjoyed by the end user and are all around fun to make! There are JavaScript libraries that are pre-made for game development, but I prefer creating from scratch so that I can understand everything completely.

An overview of the JavaScript game.

What better game to represent web development than the Chrome dinosaur game that you play when you lose your internet connection? It’s a fun game, and it’s easy to recreate the code. It doesn’t look exactly the same, but it functions the same. If you really want, you can style it when you’re done!

A version of a JavaScript game with a dinosaur player.

To begin coding the game, create a new folder in your documents. Use your favorite text editor to open that folder, then create three new files and name them: index.html, style.css and script.js. It’s possible to do everything in one file with HTML5, but it’s more organized to keep everything separate.

Our index.html file is going to be very simple: once you have a basic HTML layout, create a div with the id “game”, and then two more divs inside of it with the ids “character” and “block”. The character will be the dinosaur, and the block will be the cactuses coming towards us.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Jump Game</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="game">
        <div id="character"></div>
        <div id="block"></div>
    </div>
<script src="script.js"></script>
</body>
</html>

Next, go over to the CSS file and start applying styles to the two divs we just created. First, we’ll start with the game div. Select the element by its id, which is represented by the hash(#) symbol.

#game{
    width: 500px;
    height: 200px;
    border: 1px solid black;
    margin: auto;
}

Next we’ll style our character div. We have to declare the position as relative, because positional attributes like “top” and “left” only apply to positioned elements.

#character{
    width: 20px;
    height: 50px;
    background-color: red;
    position: relative;
    top: 150px; //game height - character height (200 - 50)
}

Create a keyframe animation called jump. This animation will make the top position slide up 50 pixels and then slide back down.

@keyframes jump{
    0%{top: 150px;}
    30%{top: 100px;}
    70%{top: 100px;}
    100%{top: 150px;}
}

Next, we’ll create a new class called animate, which applies the jump animation.

We made a custom demo for .
No really. Click here to check it out.

.animate{
    animation: jump 300ms linear;
}

We’re going to use Javascript to add the class “animate” to our character whenever you click your mouse.

In the script.js file, create a function called jump() that adds the class “animate” to the character div. Create an event listener that listens for the user to click, and then executes the jump function.

Create another function called removeJump() that removes the animate class. Then add a timeout function to jump() that runs removeJump() when the animation ends. The animation won’t run again unless we remove it.

var character = document.getElementById("character");
document.addEventListener("click",jump);
function jump(){
    character.classList.add("animate");
    setTimeout(removeJump,300); //300ms = length of animation
};
function removeJump(){
    character.classList.remove("animate");
}

This works, but it seems to glitch if the user clicks while it’s currently jumping. To fix that, add the line below at the beginning of jump(). It will stop the function from doing anything if the animation is running.

if(character.classList == "animate"){return;}

Now, we’ll go back to our CSS file and start styling the block div.

#block{
    width: 20px;
    height: 20px;
    background-color: blue;
    position: relative;
    top: 130px; //game height - character height - block height (200 - 50 - 20)
    left: 480px; //game width - block width (500 - 20)
    animation: block 1s infinite linear;
}

We haven’t created the block animation yet, so create an animation to make the block slide from the right to the left.

@keyframes block{
    0%{left: 500px} 
    100%{left: -20px}
}

Now we’re able to jump, but we have to make the game end if we hit the block. Create a function called checkDead() that gets the position of the block and character, and then evaluates if they are on top of each other. If they are, then end the game.

Create a variable called characterTop that is equal to the top value of the character div. getComputedStyle() will return all of the CSS values associated with an element, and getPropertyValue() specifies the property you want the value from.

Now, this would return a string with a value such as 100px. We only want the numerical value, so we’re going to wrap everything inside of a parseInt() function so that it returns the value as an integer.

Create an if statement that checks if blockLeft’s value is between -20px and 20px, and characterTop’s value is greater than 130px. If they are, that means they’re overlapping each other and the game is over. Alert “game over”.

Create an interval function that runs the checkDead function every 10 milliseconds.

var block = document.getElementById("block");
function checkDead(){
    let characterTop = parseInt(window.getComputedStyle(character).getPropertyValue("top"));
    let blockLeft = parseInt(window.getComputedStyle(block).getPropertyValue("left"));
    if(blockLeft<20 && blockLeft>-20 && characterTop>=130){
        alert("Game over");
    }
}

setInterval(checkDead, 10);

Now you have a fully functioning game. This is a great project for sharing with non-developers, because they’ll be able to better appreciate what you’ve learned!

There is a link to my GitHub if you want to copy the code. You can also check out my YouTube video if you learn better visually!

 

: Debug JavaScript errors easier by understanding the context

Debugging code is always a tedious task. But the more you understand your errors the easier it is to fix them.

LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to find out exactly what the user did that led to an error.

LogRocket records console logs, page load times, stacktraces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!

.
Shawn Beaton I create 2d games with HTML divs, CSS Animations and Javascript.

Leave a Reply