To see what we will be building today, check this out. Use ASDW keys and Arrow keys to move the cars, and shoot bullets. Hit the obstacles and collect money. Keep in mind, lanes and hand controls are switched.

Let’s begin!!

First, let’s create a index.html page which will load our game.

As you see, there is only one div with id main-wrapper. Every other component will be created with javascript. Create cargame.js file as mentioned in the script tag. This is where the logic for the game will be stored.

Get body and main-wrapper divs.

Create wrapper for the game space with createElement(). And style it as follows. Give it height and width, the background with an image background.png by placing the image on the same directory as the other files we created. (Link for these images will be provided at the end of this)
Then append it to the mainWrap division from index.html with appendChild().

Now, let’s create a component to show score. This should always be on the top. So its position is absolute. The zIndex value determines which absolute position component is shown on top of the other. Higher value takes precedence.

We also need a reset button to restart the game. The onclick() function executes when the resetButton is clicked. In this instance, we just refresh the page instead of resetting all the components. (Simple, right? Probably not the best way of doing this, though.)

Now, we need obstacles. For this we will use random numbers to position them in the game.

Let’s define a car now.

Use similar logic to create obstacles.

Use similar logic for creating food.

Time to create bullets to destroy obstacles.

Now that we have everything we need, we need a system to check if bullet hits either obstacles or food.

We also need a mechanism for doing things when the game ends.

Initialize the game.

Set background interval. setInterval(function(){ alert("Hello"); }, 3000); displays “Hello” every 3000 ms i.e, 3 secs. clearInterval() used above clears this interval.

Load obstacles randomly.

Now controlling the cars.

That is it. If you have any confusion, don’t hesitate to get in touch with us.

The final code and the images used for this game are available here.