A Simple Game using HTML, CSS and JavaScript
Let us learn how to make a simple game using nothing but only HTML CSS and JavaScript.
Working:
This is a simple obstacle game. The main idea for the working of the game is quite simple ,we have to avoid the red square from touching the green obstacles.
Take a look at the code below:
Output:
Explanation:
Game Canvas
The HTML <canvas>
element is displayed as a rectangular object on a web page. It is perfect for making games in HTML and offers all the functionality you need for making games.
Game Components
To add new components in the game area, we will have to make a component constructor.
- Red square
The object constructor is called component
, and we make our first component, called myGamePiece.
2. Game Controller
The “MOVE UP” button in our game is the Game Controller.
3. Obstacles
Add a new component to the gaming area. Make it green, 10px wide, 200px high, and place it 300px to the right and 120px down.
Also update the obstacle component in every frame.
4. Hit The Obstacle = Game Over
Create a new method in the component constructor, that checks if the component crashes with another component. This method should be called every time the frames updates, 50 times per second.
Also add a stop()
method to the myGameArea
object, which clears the 20 milliseconds interval.
5. Moving Obstacle
The obstacle is of no danger when it is static, so we want it to move.
Change the property value of myObstacle.x
at every update.
6. Multiple Obstacles
How about adding multiple obstacles?
For that we need a property for counting frames, and a method for execute something at a given frame rate.
7. Obstacles of Random Size
To make the game a bit more difficult, and fun, we will send in obstacles of random sizes, so that the red square must move up and down to not crash.
And finally we have created our own obstacle game using only HTML, CSS and JavaScript!! You can download the code from my GitHub and try it out.
Thank You!! 😀