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.
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!
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 div
s 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.
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!
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 see exactly what the user did that led to an error.
LogRocket records console logs, page load times, stack traces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowToast notifications are messages that appear on the screen to provide feedback to users. When users interact with the user […]
Deno’s features and built-in TypeScript support make it appealing for developers seeking a secure and streamlined development experience.
It can be difficult to choose between types and interfaces in TypeScript, but in this post, you’ll learn which to use in specific use cases.
This tutorial demonstrates how to build, integrate, and customize a bottom navigation bar in a Flutter app.
12 Replies to "How to build a game with HTML, CSS, and JavaScript"
Why do you have different lines of code in your github? I`m new at programming and i`m trying to run these instructions you gave for about 2 days, i`m mixing parts of the code you have here in the page and the ones which are missing I get it from GitHub, nevertheless I didn`t succeeded in running it.
Hey it’s same as made by knife circus.
Please friends check that video on YouTube.
This is exact copy of that game. Not a single difference.
Knife Circus is Shawn Beaton — he wrote the post.
MY DINO ISNT JUMPING ON TOUCH HELP!!
code:
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”);
}
HELP ASAP
You forgot to add if(character.classList == “animate”) {return;} after function jump(){
btw i found that you need to put
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 && characterTop>=130){
alert(“Game over”);
}
}
setInterval(checkDead, 10);
in your .js folder not your .css
It’s very incredible and nice.
I didn’t know that it’s going to be that simple
this is the first time I came to know that there are certain JavaScript libraries that are pre-made for game developments. Although they are easy to create, but these games crash a lot.
good
so, I have been learning to code JavaScript in Kahn academy, I just don’t know what place to type it in. like do I open up a google doc and start typing in code? the article didn’t really explain that in depth. for example, what does this mean “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,” what does any of that stuff mean? Also, turns out I have been using some sort of Kahn academy JavaScript dialect, and I have to type something in first to use my code that I have learned, but every time I go into visual studio or something like that there is already a load of shit typed in, what does any of that do? should I just delete it? also, what is CSS or HTML, I know a little bit of JavaScript, I don’t know any of those coding languages. somebody please explain to me how I can get to the point where I can start typing in code (in the specific Kahn academy dialect that I learned) and it will run it for me. please explain EVERYTHING. I NEED HELP!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
I would recommend you use a code editor, such as VS Code, https://code.visualstudio.com. Create a folder on your computer. Open VSCode and then open that folder, within that folder create your three files.
Most websites are made up of 3 parts, the HTML File (the Markup or the structure of the Website), the .CSS file used to style the page (formats, colours, text size etc) and the .JS (Javascript) which is used on the client side (your browser) to provide a more interactive experience.
Hope this helps you get started.
As a web developer, I love the idea of recreating classic games like the Chrome dinosaur game from scratch. It’s such a fun way to deepen your understanding of HTML, CSS, and JavaScript while also creating something that’s instantly recognizable and enjoyable. The satisfaction of coding a fully functional game and seeing it come to life is unbeatable! Plus, it’s a great project to showcase to others who might not fully grasp the technical side of development.