How to make a simple game using HTML
Hello! In this tutorial, I going to teach how to make a simple game using HTML, JavaScript, and CSS.
Here we are going to make a simple 8-bit Snake Game.
The important point is that our snake is formed by a chain of small squares.
The snake is moving with the help of an illusion wherein the last square is brought to the front.
This is built using a module pattern for code structure.
I am using Sublime Text for editing, you can use any editor of your wish.
Also read: 3D Photo/Image Gallery (on space) Using HTML5 CSS JS
How to make a simple game using HTML
Let’s begin by creating a canvas element first.
Proceed by creating a button.
Follow the code for the procedure.
<canvas id='canvas1' width='350' height='350'> </canvas>
I have created a canvas of id=’canvas1′.
For button:-
<button id='btn'>START</button>
Now I have added instructions for the game.
<div id="instructions"> <b>Instructions : </b> <span>Use the arrow keys to move the snake.</span> </div>
Now we make the settings javascript file for our game.
//This is the setting file for the game var canvas1 = document.getElementById('canvas1'); var ctx = canvas1.getContext('2d'); var snakeSize = 10; var w = 350; var h = 350; var score = 0; var snake; var snakeSize = 10; var food;
The getElementById() method returns the element that has the ID attribute with the specified value.
The variable ctx stores the content of the canvas
Create some global variables.
The parameter of getContext() tells that canvas is in the 2d plane.
Now to draw the elements in canvas, create a javascript file and name it drawing.
Let’s draw the snake and its food.
// Module Pattern var drawModule = (function () { var bodySnake = function(x, y) { //single square of snake ctx.fillStyle = 'darkgreen'; ctx.fillRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize); //border color of snake ctx.strokeStyle = 'lightgreen'; ctx.strokeRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize); } var cookie = function(x, y) { //colr of the cookie ctx.fillStyle = 'brown'; ctx.fillRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize); //border color of the cookie ctx.fillStyle = 'brown'; ctx.fillRect(x*snakeSize+1, y*snakeSize+1, snakeSize-2, snakeSize-2); } var scoreText = function() { // Total score is the number of cookies the snake eats var total_score = "Score: " + score; ctx.fillStyle = 'blue'; ctx.fillText(total_score, 145, h-5); }
The scoreText() function keeps the track of the score.
The cookie() function creates the food for the snake.
The bodySnake() function creates the head of the snake.
var draw_snake = function() { //Initial Length of snake is 8 squares var l = 7; snake = []; //the for loop pushes the 8 squares of the snake for (var i = l-1; i>=0; i--) { snake.push({x:0, y:i}); } }
The above function creates the structure of the snake for our game. Initially, the length of the snake is 8 squares.
Create the structure of the food at random places inside the canvas using the following function:-
var createFood = function() { // size of the cookie is 1 square and this creates food at random places every time food = { x: Math.floor((Math.random() * 30) + 1), y: Math.floor((Math.random() * 30) + 1) } for (var i=0; i>snake.length; i++) { var snakeX = snake[i].x; var snakeY = snake[i].y; if (food.x===snakeX && food.y === snakeY || food.y === snakeY && food.x===snakeX) { food.x = Math.floor((Math.random() * 30) + 1); food.y = Math.floor((Math.random() * 30) + 1); } } }
Now, we have to check whether the snake collides with itself or not.
var checkCollision = function(x, y, array) { //this checks for collision of the snake with it's body and if collided , the game restarts. for(var i = 0; i < array.length; i++) { if(array[i].x === x && array[i].y === y) return true; } return false; }
Its time for the main function of our game.
var paint = function(){ //space where the snake is moving ctx.fillStyle = 'lightgrey'; ctx.fillRect(0, 0, w, h); //border of the space ctx.strokeStyle = 'black'; ctx.strokeRect(0, 0, w, h); //disable the START button while playing btn.setAttribute('disabled', true); var snakeX = snake[0].x; var snakeY = snake[0].y; if (direction == 'right') { snakeX++; } else if (direction == 'left') { snakeX--; } else if (direction == 'up') { snakeY--; } else if(direction == 'down') { snakeY++; } if (snakeX == -1 || snakeX == w/snakeSize || snakeY == -1 || snakeY == h/snakeSize || checkCollision(snakeX, snakeY, snake)) { //restart game btn.removeAttribute('disabled', true); //START button enable again ctx.clearRect(0,0,w,h); //clean up the canvas gameloop = clearInterval(gameloop); return; } if(snakeX == food.x && snakeY == food.y) { var tail = {x: snakeX, y: snakeY}; //Create a new head instead of moving the tail score ++; createFood(); //Create new food } else { var tail = snake.pop(); //pops out the last cell tail.x = snakeX; tail.y = snakeY; } //The snake can now eat the food. snake.unshift(tail); //puts back the tail as the first cell for(var i = 0; i < snake.length; i++) { bodySnake(snake[i].x, snake[i].y); } cookie(food.x, food.y); scoreText(); }
Now, in the end we call the inint() function.
Don’t forget to close your module
var init = function(){ direction = 'down'; draw_snake(); createFood(); gameloop = setInterval(paint, 80); } return { init : init }; //close your module }());
Now, to add the controls we create a new file called application.js
The onekeydown event occurs when the user presses the arrow key.
The key bindings for the arrow keys are 37,38,39,40.
If the snake is facing left, then it cannot directly turn right because it would collide with itself.
We start by using a self-invoking anonymous function with drawModule() as a parameter.
// self invoking function (function (window, document, drawModule, undefined) { var btn = document.getElementById('btn'); btn.addEventListener("click", function(){ drawModule.init();}); document.onkeydown = function(event) { keyCode = window.event.keyCode; keyCode = event.keyCode; switch(keyCode) { case 37: if (direction != 'right') { direction = 'left'; } console.log('left'); break; case 39: if (direction != 'left') { direction = 'right'; console.log('right'); } break; case 38: if (direction != 'down') { direction = 'up'; console.log('up'); } break; case 40: if (direction != 'up') { direction = 'down'; console.log('down'); } break; } } })(window, document, drawModule);
Next, link your javascript file to the HTML document.
To add styling to your page use CSS.
/* design for our game */ #instructions { display: inline-block; } span { visibility: hidden; color: #000080; } header { text-decoration: underline; } #instructions:hover >span { visibility: visible; } #home { width: 355px; height: 355px; background-image: url('snakecookie.png'); background-size: auto 350px; background-repeat: no-repeat; background-color: #66CDAA ; background-position: center center; padding: 0; margin: 0; } button { background-color: #556B2F; color: #FFFFFF; border: none; bottom: 0; height: 30px; font-size: 12pt; float: left; width: 90px; margin: 10px 0 0 0; } button:hover { background-color: #1E90FF; } button:disabled { background-color: #808080; } p { font-family: Helvetica; font-weight: bold; width: 250px; margin: 18px 0 5px 8px; float: left; } .game { margin: 0 auto; border-radius: 5px; } canvas { margin: 0; border: 2px solid #000000; border-radius: 3px; }
I hope you enjoyed this tutorial.
Go ahead and make your own game and play!
Also, read JavaScript mousemove Event | Execute on moving the mouse pointer
Leave a Reply