How to Code Your Own Dino-Game:

John Murphy Fleenor
6 min readFeb 14, 2022

--

Using CSS @keyframe Animation

Note: This article uses Javascript, HTML, and CSS with a focus on how to use @keyframe animation. It’s written by a beginner programmer for beginner programmers to be a simple starter guide. For more complex fully implemented examples consider checking out some of these articles and repos:

So you want to write your own Dino Game…

Chrome Dino-Game 101

If you are spending time coding, even the simplest of projects, you’re going to be spending a good bit of that time googling. And every so often the internet clips out on you, and you get that dreaded no connection message. The true internet savvy of us knows this message actually means your one click away from a welcome respite known as…. the Dino-Game (or the T-Rex runner if you prefer).

Press the space bar when you get this screen and all of a sudden you’ll be transported to a minimalist dessert, with cactus, bird, and cloud silhouette whipping in from the right of the screen. On the left of the screen stands a cute charming, albeit clearly reckless, dinosaur sprinting full speed at the vicious cacti. If your quick, with a click of a button you can jump the poor dino from his own demise! I know I’ve spent many quite a bit of time after the internet kicks back in, and I’d bet I’m not alone.

For newbies getting into coding, building your own Dino-Game clone s a great way to introduce yourselves to the ins and outs of javascript, HTML, and CSS without getting too deep into the weeds.

Getting Started: The HTML

To begin you’ll need to start with a black repo and create an index.html, a style.css, and a script.js file. If you’re not already familiar with this structure, this will be a common starting place for many of your javascript coding projects. Next, you need to add some basic structure to your index.html file. A good trick for speeding this process up is to simply hit “!” and enter. Other than the basics, you’ll need to add script tag links for script.js and style.css along with the “game” div with two nested “character” and “block” divs.

<!DOCTYPE html>
<html lang='en' >
<head>
<meta charset='UTF-a'>
<title>Example Dino 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>

Adding Some Style: The CSS

Next, you’ll need to build out the style.css file. Add any basics you like, then be sure to include a style component for the “game”, “character”, and ”block” divs. The game will need a simple border, but the character and block divs will need the be set absolute to the bottom left and right of the game div respectively. (Note: Be sure to set the game’s location to relative.) This is where you add your own flair so have fun with it. For the sake of this demonstration, we’re going to keep the elements as simple blocks for now.

#game {
width: 500px;
height: 200px;
border: 1px solid black;
position: relative;
}
#character {
width: 20px;
height: 50px;
background-color: red;
position: absolute;
top: 150px;
}
#block {
width: 20px;
height: 20px;
background-color: blue;
position: absolute;
bottom: 0px;
left: 480px;
}

Make Some Moves: keyframes

Next comes the fun part… @keyframe animation. This tool allows you to take any CSS rule, from color, size, or position (as in this instance) and provide it a time frame to execute upon making a set of sequential changes. In this instance, we’re going to use it to move the block to the right and the character up and down. First, you’ll need the add the named @keyframe rule set. I’ve shared my implementation below using the name ‘slide’. The percent values, before the CSS rule(s), are set when in the sequence to initiate the CSS rule. 0% here being the being and 100% the end. To tie the keyframes into your block you need to add an ‘animation’ rule set to your block id and set it to your newly created slide. (The 1s sets the time the sequence takes to run and the ‘infinite’ makes the loop run continuously.

#block {
width: 20px;
height: 20px;
background-color: blue;
position: absolute;
bottom: 0px;
left: 480px;
animation: slide 1s infinite;
}
@keyframes slide {
0%{left: 480px;}
100%{left: -40px;}
}

Next well demonstrate another way to implement the @keyframes tool. For the character, we need the animation to respond to a click, so instead of putting it into our character CSS ruleset, we going to create a new class with the animation assigned to it. Then we can add the class to the character anytime a click happens in our javascript file.

.animate{
animation: jump 500ms;
}
@keyframes jump {
0%{top: 150px;}
30%{top: 100px;}
70%{top: 100px;}
100%{top: 150px;}
}

Make it Run: The Javascript

Now we’ve finally made it to the script.js file. Here we need to create character and block variables assigned to their corresponding DOM elements. Next, you need to add a jump function that adds and removes the jump animation class to the character element. The function will need to check if the class is already assigned so as to not cause the jumps to back up infinitely. Then all you need to get your character jumping is to add an event handler set to call jump when the page is clicked. WALA! You’ve got a jumping block!

let character = document.getElementById('character');
let block = document.getElementById('block');
const jump = function() {
if(character.classList !== 'animate'){
character.classList.add('animate');
}
setTimeout(function(){
character.classList.remove('animate');
}, 500);
}
document.addEventListener('click', jump);

Last but not least, you’ll need the Game Over function. This test if the block edge has hit the character edge. The game over function, which we called “checked” in the example below, will need to be called at set intervals to check regularly. You’ll need to access the current character height (either by accessing its bottom or top) and the block’s current left position (since its height remains stable). In the code below the methods, getComputedStyle() and ggetPropertyValue are used the access these elements CSS values. They are great tools in their own right that deserve their own article for beginners, so I’ve attached MDN documentation for both below. Once we’ve accessed both property values, we can check if they overlap. If so remove the jump animation style control, the display in general, and alert the player with a prompt that this game is over.

let checkDead = setInterval(function(){
let characterTop = parseInt(window.getComputedStyle(character).getPropertyValue('top'));
let blockLeft =
parseInt(window.getComputedStyle(block).getPropertyValue('left'));
if(blockLeft<20 && blockLeft > 0 && characterTop >= 130){
block.style.animation = 'none';
block.style.display = 'none';
alert('Game Over');
};
}, 10);

Dun and Dusted!

And that's it. You’ve got yourself a working, albeit minimal, Dino-game clone. Now that you’ve got the structure for the basic elements and the know-how to use @keyframes and CSS to make those elements come to life the sky is the limit. Change the look, add obstacles (like a bird), and functionality (like a restart game button). There are some really great tools below including a keyframe building tool to help you build out more exciting and specialized web pages. From one beginner to another, don’t be afraid to jump in and have fun!

Sources & Related Material

A GitHub starter repo of this project to get you started

- https://github.com/Jmfleeno/Example-Dino-Game

Really great app for building keyframes

- https://keyframes.app/animate/

An Interactive Guide to Keyframe Animations

- https://www.joshwcomeau.com/animation/keyframe-animations/

Video of this Dino-Game implementation on youtube:

- https://www.youtube.com/watch?v=bG2BmmYr9NQ

History of Chrome Dinosaur Game:

- https://dino-chrome.com/en

MDN Web Docs: keyframes

- https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes

W3 Schools

- https://www.w3schools.com/cssref/css3_pr_animation-keyframes.asp

MDN Web Docs: Window.getComputedStyle()

- https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

--

--