How do you code a javascript game?

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.

How do you code a 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!

How do you code a javascript game?

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 50px 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.

.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 "animate" class 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.


More great articles from LogRocket:

  • Don't miss a moment with The Replay, a curated newsletter from LogRocket
  • Use React's useEffect to optimize your application's performance
  • Switch between multiple versions of Node
  • Learn how to animate your React app with AnimXYZ
  • Explore Tauri, a new framework for building binaries
  • Compare NestJS vs. Express.js
  • Discover popular ORMs used in the TypeScript landscape

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. So w’ll set an 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!

LogRocket proactively surfaces and diagnoses the most important issues in your JavaScript apps.

How do you code a javascript game?

Thousands of engineering and product teams use LogRocket to reduce the time it takes to understand the root cause of technical and usability issues in their JS apps. With LogRocket, you'll spend less time on back-and-forth conversations with customers and remove the endless troubleshooting process. LogRocket allows you to spend more time building new things and less time fixing bugs.

Proactively fix your JS apps — try LogRocket today.

Can you make games with only JavaScript?

The answer is yes, and it's not very surprising. There are several platforms, tools, and 2D and 3D libraries that programmers can use to make video games with JS. These include WebGL, Phaser, Impact. js, and Melonjs.

Can JavaScript be used for gaming?

JavaScript can be used to make games using a variety of platforms and tools. Both 2d and 3d libraries can be used in combination with JavaScript to create fully-fledged games in the browser or external game engine platforms.