

{"id":81097,"date":"2020-08-21T16:44:45","date_gmt":"2020-08-21T11:14:45","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=81097"},"modified":"2021-08-25T14:03:57","modified_gmt":"2021-08-25T08:33:57","slug":"javascript-snake-game-project","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/","title":{"rendered":"JavaScript Snake Game Tutorial &#8211; Develop a Simple Snake Game"},"content":{"rendered":"<p><strong>Work on real-time JavaScript Snake game project and become a pro<\/strong><\/p>\n<p>Snake game is an interesting JavaScript project for beginners. Snake game is a single-player game, which we\u2019ve been playing for a very long time. The game mainly consists of two components \u2013 snake and fruit. And we just need to take our snake to the food so that it can eat and grow faster and as the number of fruits eaten increases, the length of snake increases which makes the game more interesting. While moving if the snake eats its own body, then the snake dies and the game ends. Now let\u2019s see how we can create this.<\/p>\n<h3>JavaScript Project Prerequisites<\/h3>\n<p>To implement the snake game in JavaScript you should have basic knowledge of:<\/p>\n<p>1. Basic concepts of JavaScript<br \/>\n2. HTML<br \/>\n3. CSS<\/p>\n<h3>Download Project Code<\/h3>\n<p>Before proceeding ahead please download source code of Snake Game: <a href=\"https:\/\/data-flair.training\/blogs\/download-javascript-snake-game-project-code\/\"><strong>Snake Game in JavaScript<\/strong><\/a><\/p>\n<h2>Steps to Build the Project &#8211; JavaScript Snake game<\/h2>\n<h3>1. Create Html file<\/h3>\n<p>HTML builds the basic structure. This file contains some basic HTML tags like div, h1, title, etc. also we\u2019ve used bootstrap (CDN is already included).<\/p>\n<p><strong>index.html:<\/strong><\/p>\n<p>Code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&lt;!DOCTYPE\u00a0html&gt;\r\n&lt;html\u00a0lang=\"en\"&gt;\r\n&lt;head&gt;\r\n\u00a0\u00a0\u00a0\u00a0&lt;meta\u00a0charset=\"UTF-8\"&gt;\r\n\u00a0\u00a0\u00a0\u00a0&lt;meta\u00a0name=\"viewport\"\u00a0content=\"width=device-width,\u00a0initial-scale=1.0\"&gt;\r\n\u00a0\u00a0\u00a0\u00a0&lt;title&gt;DataFlair Snake\u00a0game&lt;\/title&gt;\r\n\u00a0\u00a0\u00a0\u00a0&lt;link\u00a0rel=\"stylesheet\"\u00a0href=\"https:\/\/stackpath.bootstrapcdn.com\/bootstrap\/4.5.0\/css\/bootstrap.min.css\"\u00a0integrity=\"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk\"\u00a0crossorigin=\"anonymous\"&gt;\r\n\u00a0\u00a0\u00a0\u00a0&lt;link\u00a0rel=\"stylesheet\"\u00a0href=\"static\/style.css\"&gt;\r\n&lt;\/head&gt;\r\n&lt;body&gt;\r\n\u00a0\u00a0\u00a0\u00a0&lt;div\u00a0class=\"container\"&gt;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;div\u00a0class\u00a0=\"Jumbotron\"&gt;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;h1&gt;DataFlair\u00a0Snake\u00a0game\u00a0using\u00a0vanilla\u00a0JavaScript&lt;\/h1&gt;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;h2\u00a0class=\"btn\u00a0btn-info\"&gt;\u00a0\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0Score:\u00a0&lt;span\u00a0class\u00a0=\"score\"&gt;\u00a00\u00a0&lt;\/span&gt;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;\/h2&gt;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;div\u00a0class=\"containerCanvas\"&gt;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;canvas\u00a0id=\"canvas\"\u00a0width=\"500\"\u00a0height=\"500\"\u00a0class=\"canvasmain\"&gt; &lt;\/canvas&gt;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;\/div&gt;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;\/div&gt;\r\n\u00a0\u00a0\u00a0\u00a0&lt;\/div&gt;\r\n\u00a0\u00a0\u00a0\u00a0&lt;script\u00a0src=\"static\/fruit.js\"&gt;&lt;\/script&gt;\r\n\u00a0\u00a0\u00a0\u00a0&lt;script\u00a0src=\"static\/snake.js\"&gt;&lt;\/script&gt;\r\n\u00a0\u00a0\u00a0\u00a0&lt;script\u00a0src=\"static\/draw.js\"&gt;&lt;\/script&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;\r\n<\/pre>\n<p>We have used simple HTML tags except &lt;canvas&gt; tag. This new tag was introduced in HTML5, which is used to draw graphics, via JavaScript. It is nothing without JavaScript so we will use it in our JavaScript file to actually draw the board and the objects required. We\u2019ll see its implementation in JS files.<\/p>\n<h3>2. Creating JavaScript file &#8211; snake.js<\/h3>\n<p>All work will be done by the canvas, so firstly we need to access the &lt;canvas&gt; in our JS file which we can easily do with querySelector.<\/p>\n<p>&lt;canvas&gt; is blank initially, and to display anything, we need to access its context and draw, which is done by the getContext method. This method takes just one parameter, the type of context which is \u20182D\u2019. Then we have created a background for the game using linear-gradient on canvas. Now we define block and calculate the number of rows &amp; columns.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">const canvas = document.querySelector('.canvasmain')\r\nconst ctx = canvas.getContext(\"2d\");\r\nconst eatSound = new Audio('static\/eat.wav')\r\nconst hitSound = new Audio('static\/hit.wav')\r\nconst dirSound = new Audio('static\/dir.wav')\r\n\r\n\/\/providing bg color\r\nvar grd = ctx.createLinearGradient(0,0,500,0)\r\ngrd.addColorStop(0,'green');\r\ngrd.addColorStop(1,'lightgreen');\r\nctx.fillStyle = grd;\r\nctx.fillRect(0,0,500,500); \r\n\r\n\/\/size of one unit or one box\r\nconst boxScale = 20; \r\n\r\n\/\/no of rows and columns\r\nconst rows = canvas.height\/boxScale;\r\nconst columns = canvas.width\/boxScale;\r\n\r\nvar snake;\r\n\r\n\/\/this calls itself\r\n(function InitialSetUP() {\r\n    snake = new snake();\r\n    fruit = new fruit();\r\n    fruit.locate();\r\n    initialInterval = 200;\r\n\r\n    window.setInterval( function(){\r\n        ctx.clearRect(0,0, canvas.width, canvas.height);\r\n        ctx.fillStyle = grd;\r\n        ctx.fillRect(0,0,500,500); \r\n        fruit.drawFruit();\r\n        snake.move();\r\n        snake.drawSnake();\r\n\r\n        if(snake.eat(fruit)){\r\n            fruit.locate();\r\n            initialInterval-=5;\r\n        }\r\n\r\n        snake.collision();\r\n        document.querySelector('.score').innerText=snake.score;\r\n    },initialInterval);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             \r\n}());\r\n\r\nwindow.addEventListener('keydown', function(event){\r\n    dirSound.play();\r\n    var dir = event.key;\r\n    snake.changeDirection(dir);\r\n});\r\n<\/pre>\n<p>First function InitialSetUP() calls itself and creates a snake and fruit object which is declared in snake.js and fruit.js files respectively. Then, it calls locate method on fruit which provides a random location to the fruit.<\/p>\n<p>window.setInterval executes its code after every \u201c<strong>initialInterval<\/strong>\u201d. We can change this to change the difficulty level of the game. It does all major tasks like moving the snake after the unit time (initialInterval) and checking if the snake eats the fruit and if it does, then locating its new position and checking collision, updating score all these functions are defined in other JS files.<\/p>\n<p>If the snake eats fruit we will decrease the initialInterval by 5 so that the difficulty keeps increasing. And last, we add an event listener to change the direction of the snake on key-down.<\/p>\n<h3>3. Creating our next JavaScript file &#8211; snake.js<\/h3>\n<p>It contains just one function which is a constructor function. A constructor is a function that initializes an object. Similarly, in JavaScript, we have a special constructor function, which is used to initialize an object.<\/p>\n<p>Code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">function\u00a0snake(){\r\n\r\n\u00a0\u00a0\u00a0\u00a0\/\/initial\u00a0position,\u00a0velocity\u00a0of\u00a0snake\r\n\u00a0\u00a0\u00a0\u00a0this.x\u00a0=\u00a00;\r\n\u00a0\u00a0\u00a0\u00a0this.y\u00a0=\u00a00;\r\n\u00a0\u00a0\u00a0\u00a0this.xVelocity\u00a0=\u00a0boxScale;\r\n\u00a0\u00a0\u00a0\u00a0this.yVelocity\u00a0=\u00a00;\r\n\u00a0\u00a0\u00a0\u00a0this.score=0;\r\n\u00a0\u00a0\u00a0\u00a0this.tail\u00a0=\u00a0[];\r\n\r\n\u00a0\u00a0\u00a0\u00a0\/\/drawing\u00a0snake\u00a0of\u00a0size\u00a0boxScale*boxScale\r\n\u00a0\u00a0\u00a0\u00a0this.drawSnake\u00a0=\u00a0function(){\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0ctx.fillStyle\u00a0=\u00a0\"#fff\";\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0for(let\u00a0i=0;\u00a0i&lt;this.tail.length;\u00a0i++){\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0ctx.fillRect(this.tail[i].x,\u00a0this.tail[i].y,\u00a0boxScale,\u00a0boxScale);\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0ctx.fillRect(this.x,\u00a0this.y,\u00a0boxScale,\u00a0boxScale);\r\n\u00a0\u00a0\u00a0\u00a0}\r\n\r\n\u00a0\u00a0\u00a0\u00a0this.move\u00a0=\u00a0function()\u00a0{\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0for(let\u00a0i=0;i&lt;this.tail.length-1;i++){\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.tail[i]=this.tail[i+1];\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.tail[this.score\u00a0-\u00a01]\u00a0=\u00a0{x:this.x,\u00a0y:this.y};\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.x\u00a0+=\u00a0this.xVelocity;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.y\u00a0+=\u00a0this.yVelocity;\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\/\/x\u00a0overfow\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0if(this.x\u00a0&gt;=columns\u00a0*\u00a0boxScale\u00a0)\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.x=0;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0else\u00a0if(this.x\u00a0&lt;\u00a00\u00a0)\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.x=(columns-1)\u00a0*\u00a0boxScale;\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\/\/y\u00a0overfow\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0if(this.y\u00a0&gt;=\u00a0rows\u00a0*\u00a0boxScale)\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.y=0;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0else\u00a0if(this.y\u00a0&lt;\u00a00\u00a0)\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.y=(rows-1)\u00a0*\u00a0boxScale;\r\n\u00a0\u00a0\u00a0\u00a0}\r\n\r\n\u00a0\u00a0\u00a0\u00a0this.changeDirection\u00a0=\u00a0function(dir)\u00a0{\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0switch(dir)\u00a0{\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0case\u00a0'ArrowRight':\u00a0\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.xVelocity\u00a0=\u00a0boxScale;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.yVelocity\u00a0=\u00a00;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0break;\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0case\u00a0'ArrowLeft':\u00a0\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.xVelocity\u00a0=\u00a0-1*boxScale;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.yVelocity\u00a0=\u00a00;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0break;\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0case\u00a0'ArrowUp':\u00a0\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.xVelocity\u00a0=\u00a00;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.yVelocity\u00a0=\u00a0-1*boxScale;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0break;\r\n\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0case\u00a0'ArrowDown':\u00a0\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.xVelocity\u00a0=\u00a00;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.yVelocity\u00a0=\u00a0boxScale;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\r\n\u00a0\u00a0\u00a0\u00a0}\r\n\r\n\u00a0\u00a0\u00a0\u00a0this.eat\u00a0=\u00a0function(fruit)\u00a0{\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0if(this.x\u00a0==\u00a0fruit.x\u00a0&amp;&amp;\u00a0this.y\u00a0==\u00a0fruit.y){\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.score++;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0eatSound.play();\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return\u00a0true;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return\u00a0false;\r\n\u00a0\u00a0\u00a0\u00a0}\r\n\r\n\u00a0\u00a0\u00a0\u00a0this.collision\u00a0=\u00a0function()\u00a0{\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0for(let\u00a0i=0;i&lt;this.tail.length;i++)\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0{\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0if(this.x\u00a0==\u00a0this.tail[i].x\u00a0&amp;&amp;\u00a0this.y\u00a0==\u00a0this.tail[i].y)\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0{\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.score=0;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.tail=[];\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0hitSound.play();\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\r\n\u00a0\u00a0\u00a0\u00a0}\r\n}\r\n\r\n<\/pre>\n<p>The constructor function has 6 variables, x and y coordinates of the snake, their velocity, score, and an array storing the snake&#8217;s body. Let\u2019s discuss all functions one by one:<\/p>\n<p><strong>1. drawSnake function:<\/strong> It draws the block(s) of the rectangle which we call a snake of white color.<\/p>\n<p><strong>2. move function:<\/strong> It shifts all the elements towards front by one and then adds new head (obtained by adding velocity) which gives the visual effect of moving snake and then, it also checks overflow, and if overflow occurs then it again brings the snake to starting position. If you want you may end the game in case of overflow.<\/p>\n<p><strong>3. changeDirection function:<\/strong> It is a very simple function which just uses a switch statement to identify which key was pressed by the user. It updates the velocities as per the direction, as and when the direction pressed is left y-coordinate will not change and x will move backwards that\u2019s why the \u2018-\u2018 sign and similar in other cases.<\/p>\n<p><strong>4. eat function:<\/strong> It just checks the head of snake and fruit\u2019s location if both coincide, then it updates the score, plays the required sound, and returns true, otherwise false.<\/p>\n<p><strong>5. collision function:<\/strong> It checks if the snake at any point eats its own body and if so it resets the score, snake body, and plays game over sound. It checks this by running a loop and checking the position of every block of the body with the snake&#8217;s head.<\/p>\n<h3>4. Creating last JavaScript file &#8211; fruit.js<\/h3>\n<p>This file also contains just one function which is a constructor function which creates a fruit object.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">function\u00a0fruit()\u00a0{\r\n\u00a0\u00a0\u00a0\u00a0this.x;\r\n\u00a0\u00a0\u00a0\u00a0this.y;\r\n\r\n\u00a0\u00a0\u00a0\u00a0this.locate=\u00a0function(){\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.x\u00a0=\u00a0(Math.floor(Math.random()\u00a0*\u00a0columns-1)\u00a0+\u00a01)*boxScale;\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.y\u00a0=\u00a0(Math.floor(Math.random()\u00a0*\u00a0rows-1)\u00a0+\u00a01)*boxScale;\r\n\u00a0\u00a0\u00a0\u00a0}\r\n\r\n\u00a0\u00a0\u00a0\u00a0this.drawFruit\u00a0=\u00a0function()\u00a0{\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0ctx.fillStyle\u00a0=\u00a0\"#f00\"\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0ctx.fillRect(this.x,\u00a0this.y,\u00a0boxScale,\u00a0boxScale);\r\n\u00a0\u00a0\u00a0\u00a0}\r\n}\r\n<\/pre>\n<p>There is nothing much to be performed by a fruit object as we can see the file hardly contains 10 lines of code, okay okay 11. Coming back to the point, it has two variables, the 2 coordinates and just two functions.<\/p>\n<p><strong>1. locate function:<\/strong> This function just calculates 2 random positions in the grid using Math.random() function and stores it in the variable.<\/p>\n<p><strong>2. drawfruit function:<\/strong> It draws the fruit (1 x 1 square ) at the position pre-calculated by locate() with the help of fillRect function.<\/p>\n<p>We do not need a separate CSS file because all the designing work is already done by &lt;canvas&gt; which is its biggest advantage. Thus we have successfully implemented such an interesting project in 4 easy steps. Now you can play your own snake game:<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2020\/08\/snake-game.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81107\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2020\/08\/snake-game.png\" alt=\"snake game\" width=\"1366\" height=\"728\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2020\/08\/snake-game.png 1366w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2020\/08\/snake-game-300x160.png 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2020\/08\/snake-game-1024x546.png 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2020\/08\/snake-game-150x80.png 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2020\/08\/snake-game-768x409.png 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2020\/08\/snake-game-520x277.png 520w\" sizes=\"auto, (max-width: 1366px) 100vw, 1366px\" \/><\/a><\/p>\n<h2>Summary<\/h2>\n<p>In this article, we have developed snake game with JavaScript and HTML. Although snake game is a simple javascript project but it&#8217;s good for beginners for practice.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Work on real-time JavaScript Snake game project and become a pro Snake game is an interesting JavaScript project for beginners. Snake game is a single-player game, which we\u2019ve been playing for a very long&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":81104,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[18979],"tags":[20845,23046,23045,23047],"class_list":["post-81097","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","tag-javascript-project","tag-javascript-project-for-beginners","tag-javascript-snake-game","tag-simple-snake-game"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>JavaScript Snake Game Tutorial - Develop a Simple Snake Game - DataFlair<\/title>\n<meta name=\"description\" content=\"JavaScript Snake Game - Develop simple snake game with javascript and html. In this step by step guide we provided all the instructions to develop the game easily.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"JavaScript Snake Game Tutorial - Develop a Simple Snake Game - DataFlair\" \/>\n<meta property=\"og:description\" content=\"JavaScript Snake Game - Develop simple snake game with javascript and html. In this step by step guide we provided all the instructions to develop the game easily.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-08-21T11:14:45+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-08-25T08:33:57+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2020\/08\/javascript-snake-game-project.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"JavaScript Snake Game Tutorial - Develop a Simple Snake Game - DataFlair","description":"JavaScript Snake Game - Develop simple snake game with javascript and html. In this step by step guide we provided all the instructions to develop the game easily.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/","og_locale":"en_US","og_type":"article","og_title":"JavaScript Snake Game Tutorial - Develop a Simple Snake Game - DataFlair","og_description":"JavaScript Snake Game - Develop simple snake game with javascript and html. In this step by step guide we provided all the instructions to develop the game easily.","og_url":"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2020-08-21T11:14:45+00:00","article_modified_time":"2021-08-25T08:33:57+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2020\/08\/javascript-snake-game-project.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"JavaScript Snake Game Tutorial &#8211; Develop a Simple Snake Game","datePublished":"2020-08-21T11:14:45+00:00","dateModified":"2021-08-25T08:33:57+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/"},"wordCount":962,"commentCount":2,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2020\/08\/javascript-snake-game-project.jpg","keywords":["JavaScript Project","javascript project for beginners","javascript snake game","simple snake game"],"articleSection":["JavaScript Tutorial"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/","url":"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/","name":"JavaScript Snake Game Tutorial - Develop a Simple Snake Game - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2020\/08\/javascript-snake-game-project.jpg","datePublished":"2020-08-21T11:14:45+00:00","dateModified":"2021-08-25T08:33:57+00:00","description":"JavaScript Snake Game - Develop simple snake game with javascript and html. In this step by step guide we provided all the instructions to develop the game easily.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2020\/08\/javascript-snake-game-project.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2020\/08\/javascript-snake-game-project.jpg","width":1200,"height":628,"caption":"javascript snake game project"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/javascript-snake-game-project\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"JavaScript Tutorial","item":"https:\/\/data-flair.training\/blogs\/category\/javascript\/"},{"@type":"ListItem","position":3,"name":"JavaScript Snake Game Tutorial &#8211; Develop a Simple Snake Game"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam1\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/81097","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=81097"}],"version-history":[{"count":5,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/81097\/revisions"}],"predecessor-version":[{"id":81108,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/81097\/revisions\/81108"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/81104"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=81097"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=81097"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=81097"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}