How to Make a Simple Chrome Dino Game in JavaScript?

If you are a Google Chrome user, most likely you’ve seen the game above. I’m going to show you how to make a simple version of it. I’m focusing on the most basic features which are pressing any key to start, pressing space to jump and stop the game when it crashes the cactus as shown in this demo game I’ve prepared. You can also see my code on my GitHub repo.

These are the steps we’ll use to make the Chrome Dino game :

  1. Display the game
  2. Make the cactus move
  3. Make the dino jump
  4. Detect crashing

1. Display the game

Let’s make the interface of our game. This will be the structure of our folder.

File Structure

Now, let’s start with our index.html and lay out some basic structure.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css">
    <title>Chrome Dino</title>
</head>
<body>

    <script src="./script.js"></script>
</body>
</html>

Now, let’s display our game, inside the body, insert a div with the dinosaur and the cactus inside. You can download the images in my GitHub repo.

HTML
<main class="game">
    <img id="dino" class="dino" src="./images/dino.png" alt="dino">
    <img id="cactus" class="cactus" src="./images/cactus.png" alt="cactus">
</main>

And we’re done with the HTML. Your page should look something like this.

HTML Result

And to finish the interface, we’ll ad some CSS

CSS
/* center the game and remove margin */
body {
    margin: 0;
    height: 100vh;
    display: flex;
    align-items: center;
}

/* displaying the game with full screen with and bottom border as the ground */
.game {
    width: 100vw;
    border-bottom: 1px solid black;
    position: relative;
}

/* sticking the dino and the cactus to the floor */
.dino, .cactus {
    position: absolute;
    bottom: 0;
}

.dino {
    left: 50px;
}

.cactus {
    right: 0;
    height: 50px;
}

And your game should look like this

CSS Result

2. Make the cactus move

As you can see, we are not making the dino run, but we make the cactus moves toward the dino instead. So, let’s make our cactus move. We do it by giving the cactus a CSS animation when any key is pressed.

Let’s make our CSS animation and class. We make our cactus loop infinitely moving from the rightmost side of the screen to the leftmost side of the screen. If move class is added to the cactus, it’ll move like we wanted it to.

CSS
.move {
    animation: cactus-move 6s infinite;
}

@keyframes cactus-move {
    0% {
        right: 0;
    }

    100% {
        right: 100%;
    }
}

Now we get into the JavaScript. To make the cactus move after we press any key, we have to add a listener to it and and the move class if it doesn’t already have one. After adding the code below, your cactus will move if you press any key.

JavaScript
const cactus = document.querySelector('#cactus');

document.addEventListener('keydown', event => {
    move();
});

function move() {
    if (!cactus.classList.contains('move')) {
        cactus.classList.add('move');
    }
}

3. Make the dino jump

Aside from making the cactus move, we also want to make the dino jump when we press space. The way we do this is very similar with how we make the cactus move.

In the CSS, instead of just 0% and 100%, we want to add 50% as well because we want the dino to jump and reach its peak at 50% and land back to the ground at 100%. Feel free to experiment with the numbers (height and duration) to find your own sweet spot (well, with the numbers I used, it might be a bit hard to play the game).

CSS
.jump {
    animation: dino-jump 2s;
}

@keyframes dino-jump {
    0% {
        margin-bottom: 0;
    }

    50% {
        margin-bottom: 150px;
    }

    100% {
        margin-bottom: 0;
    }
}

Now let’s add the function and listener to JS. In the jump function, we first check if the key pressed is space since we only want the dino to jump when space is pressed. Id the key is not space, it will not execute the lines below. If it is space, the function will add the jump class enabling the dino to jump if it doesn;t already have one and remove it after the animation is done (in this case, it’s 2 seconds). After that, our dino should be able to jump.

JavaScript
const dino = document.querySelector('#dino');

document.addEventListener('keydown', event => {
    jump(event);
});

function jump(event) {
    if (!(event.code === 'Space')) {
        return;
    }
    if (!dino.classList.contains('jump')) {
        dino.classList.add('jump');
        setTimeout(function() {dino.classList.remove('jump')}, 2000);
    }
}

4. Detect crashing

Now we’re getting into the cream of the crop. We want to stop the game if the dino runs into the cactus. This is the part that needs the most thinking.

First, we’ll make a function to detect if they crashed.

We use getBoundingClientRect() to get the positions (top, left, right, bottom) of the cactus and dino.

Then we check if they crashed. The return statement might seem confusing, but think about this :

  • If the dino’s right side passes the cactus’ left side
  • If the dino’s left side doesn’t pass the cactus’ right side
  • If the dino’s bottom is greater than the cactus’ top (that means dino is under or overlaps witch cactus)

If all those points happen, that means the dino and the cactus overlaps or crashes. It might be a bit hard to digest, but try thinking it over. If it helps, this thread from StackOverflow is my inspiration.

JavaScript
function isCrashed() {
    let dinoPosition = dino.getBoundingClientRect();
    let cactusPosition = cactus.getBoundingClientRect();

    return dinoPosition.right > cactusPosition.left && dinoPosition.left < cactusPosition.right && dinoPosition.bottom > cactusPosition.top;
}

Then we want the function to run continuously to check if they crashed. To do that, we use setInterval. To stop the game, I use alert but you can substitute it as you improve the game.

JavaScript
setInterval(() => {
    if (isCrashed()) {
        alert('Game Over!');
    }
})

Conclusion

Congrats! By now, you should be able to make the dino avoid the cactus and stops if they crashed. Well, it still lacks features of the complete game but it should be enough foundation for you to improve on since we’ve covered the important part of the logic which is stopping the game if they crashed.

Here are some things you can improve on :

  • Adding the birds
  • Adding the score
  • Making the ground look better
  • Making the obstacles pattern more random

If you want to host your result, you can do it on GitHub Pages for free or if you want it to look more professional, you can host it on Cloudways. It is a compatible, fast and reliable managed cloud hosting. Go ahead and check it out!

For you who want to brush up your JavaScript skills, whether to deepen or learn form zero, I recommend you try Codecademy. There are tons of JavaScript lessons that you can learn in a structured and interactive way. You can learn from the most basic materials to advanced stuffs and even preparing for technical interviews. Go try it now!

If you are interested to practice JavaScript by building other games, you can try my other posts :

Now, go explore! What should I build next?

Leave a Comment