Unleash Your Inner Game Developer
Getting Started
To begin, create a new folder in your documents and open it with your favorite text editor. Inside, create three new files: index.html
, style.css
, and script.js
. This will help keep your code organized and easy to manage.
Building the Game
In index.html
, set up a basic HTML layout and add a div
with the ID “game”. Inside this div
, create two more div
s with IDs “character” and “block”. The character will be our dinosaur, and the block will represent the cactuses.
<html> <body> <div id="game"> <div id="character"></div> <div id="block"></div> </div> </body> </html>
Next, head over to style.css
and start applying styles to the two div
s. First, target the game div
and add some basic styling. Then, focus on the character div
, declaring its position as relative and creating a keyframe animation called “jump”. This animation will make the character jump up and down.
#game { width: 800px; height: 600px; border: 1px solid black; } #character { position: relative; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 50px; height: 50px; background-color: green; animation: jump 2s infinite; } @keyframes jump { 0% { top: 50%; } 50% { top: 30%; } 100% { top: 50%; } }
Adding Interactivity
In script.js
, create a function called jump()
that adds the “animate” class to the character div
. Then, add an event listener that listens for mouse clicks and executes the jump()
function. To ensure the animation doesn’t glitch, add a timeout function that removes the “animate” class when the animation ends.
function jump() { document.getElementById("character").classList.add("animate"); setTimeout(function() { document.getElementById("character").classList.remove("animate"); }, 2000); } document.addEventListener("click", jump);
The Block Animation
Now, let’s style the block div
and create an animation to make it slide from right to left. This will simulate the cactuses moving towards our dinosaur.
#block { position: absolute; top: 50%; right: 0; transform: translateY(-50%); width: 50px; height: 50px; background-color: brown; animation: slide 5s infinite; } @keyframes slide { 0% { right: 0; } 100% { right: 100%; } }
Game Over
To make the game more engaging, create a function called checkDead()
that checks if the character and block are overlapping. If they are, display an “Game over” alert. Use an interval function to run the checkDead()
function every 10 milliseconds.
function checkDead() { var character = document.getElementById("character"); var block = document.getElementById("block"); if (character.getBoundingClientRect().x + character.offsetWidth >= block.getBoundingClientRect().x) { alert("Game over"); } } setInterval(checkDead, 10);
Showcase Your Skills
Congratulations! You now have a fully functional game that you can share with friends and family. This project is perfect for demonstrating your web development skills to non-developers.