How to code snake game in JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey there hope you're having a wonderful day in this video we're going to be creating the snake game and this is a classic game i'm pretty sure you've played it before and the way it works is you're given a single square and you use the arrow keys to move around so if i press left you can see the snake continuously moves left and if i press right it changes the direction so by using the arrow keys i change the direction in which the snake moves and when the snake eats a red square which is the food it grows bigger so every time you collide with a red square it adds a segment to the snake's body so of course this is why the game is called snake because it's all about growing the segments and yeah so this game is pretty simple to make and we're going to use html css and javascript and most of it is going to be in javascript and yeah so why don't we begin so before we get started i just want to quickly mention that i am working on a weekly project tutorial series so here you can see i have a tutorial on how to code blackjack i have one on candy crush minesweeper wordo 2048 connect 4 and so on so i will be making videos like this every week and if this is something that you're interested in please consider subscribing it helps a lot and feel free to check out my other videos alright so let's begin so start by creating three files index.html snake.css snake.js and as i mentioned before it's going to be mainly a javascript tutorial on canvas so we're going to do minimal stuff in html and css so let's just get started so doctype html html so let's create a head tag and in here we're just going to do the standard stuff so meta car set utf-8 meta name equals viewport content is equal to width equals device width initial scale equals 1.0 let's give a title to our page so let's call it snake and then now let's link our style sheet and our javascript so link rel equals stylesheet href is going to be snake dot css and our script is going to be source equal snake.js okay so that's it for the head now let's move on to the body and we're just going to create a header tag with the word snake and we're going to create a canvas tag and give it an id of board so by giving it an id we can use javascript to access this canvas tag okay [Music] so if you open up your directory and just double click on index.html you can see this is what we have so far so let's quickly style this so styling is going to be pretty minimal if you want to style the rest of the page feel free to do so for now i'm just going to do body and i'm going to change the font to courier and i'm going to do text align center so this is going to align all the text and images as well as our canvas towards the center of the page so if i refresh now you can see the text is aligned at the center now you can't see the canvas because we haven't filled a color in for it yet and we haven't given it any dimensions so we're going to do that using javascript alright so before we move on to the javascript part i want to explain how we're going to design this game so here you can see we have a canvas and it is 18 by 18 squares so each row there are 18 tiles and each column they're 18 tiles and you can see we have these numbered here so this would be the indices so usually when we refer to matrices if we wanted let's say this location of the red square this would be board of row column right so we would have to go to the 15th row and the third column so this would be board of 15 3. now the thing is we are not going to use rowing column to represent the locations instead we are going to refer to x and y and if you remember from basic math you have your cartesian coordinate this is x and this is y so if i go to the right that is going like this across the columns so when i move in the x direction negative x or positive so let's say i move here or here it is going to move uh through the columns to the right or to the left and likewise if i want to move down the rows i am basically moving in the y axis right so if i move up this is minus one minus two and then i move down this is plus one plus two so i'm going down the rows when i'm moving down the y axis so this can be confusing for beginners because if i ask you for the location of this red square if you want the row and columns this would be 15 3 like i said over here but in terms of x and y this would be 3 15. okay and going down is positive and going to the right is positive and going left is negative and going up is negative okay so as you can see over here that i've written to go up we do y minus one and to go down we do y plus one likewise to go to the left you do x minus one to go right you do x plus one okay so you're moving through the columns to move between left and right and if you want to move up and down that's moving through the rows now with that said let's also talk about the size of the board so we're going to create a variable called box size and this refers to the size of each box over here so like this currently there are no sizes given but if i wanted the box size to be 25 so let's say i wanted the food this red square i wanted uh the food to be over here when we look at the board we say okay that would be at one one right or in terms of x and y it would just be one one but the thing is on the screen if you just do 1 1 you won't be able to see it you need to consider the box size so instead of 1 1 it would be 1 times 25 and 1 times 25 so it would fill over here 25 by 25 okay so for that reason we are going to multiply the coordinates by the box size all right so within the javascript let's add our board so the block size is going to be 25 and we're going to have a certain number of rows you can change this if you want but i'm just going to set it as 20 and columns i'm going to make this 20 as well [Music] and i'm going to create a variable for the board and a variable for the context so the context is going to be what we use to draw with it's going to be our drawing object all right so now when the page loads we're going to do window.onload equal function and we're going to get the board so earlier we gave our canvas the id of board so we can access this tag by doing document dot get element by d board so now this variable board has a canvas tag and we're going to set the height to rows times block size and the width is going to be columns times block size and then we're going to get the context which is board dot get context 2d okay so this is used for drawing on the board so now let's create an update function and this is going to update the board on the html is going to redraw it so for now let's just draw it once and i'm going to create a function called update and i'm going to do context dot fill style black so this is going to change the color of the pen to black and i'm going to do context context.fill rect starting from 0 0 to board that width and board dot height okay so we're starting from the corner of the page or the canvas actually and we're filling a width and height of 500 right because 20 times 25 that's 500 so if you go back here you can see this is 0 0 it's going to fill all this up and make it black alright so if i refresh the page you can see now we have our canvas and it has created a rectangle that is black and 500 pixels by 500 pixels and again if i change the number of columns let's say 10 and i refresh you can see it shortens the width okay so you can play around with those variables if you want i'm just going to keep it as 20 by 20 or 20 squares by 20 squares all right so now that we have our board let's draw the snake so i'm just going to draw the head first so here i'm going to write snake head and we're going to have a snake x which is the x coordinate and that is going to be block size and i'm going to make it 5 and var snake y block size 5. basically i am saying the snake is going to start over here at 5 5 and of course we multiply the x and y coordinates by the box size or the block size because we want to accurately fill it to make sure that it reaches this pixel uh pixel region on the page all right so within our update function i'm going to do contacts dot fill style and i'm going to make it lime so this is going to be the color of the snake and i'm going to do context dot fill rect of snake x snake y block size block size okay so again this is the x and y coordinates and this is the width and this is the height so the width and height is just one square all right so if i refresh the page you can see that the snake is on five five the coordinates five five and you can see we have the snake over here let's also draw the food so over here we're going to do the same thing var food x is equal to block size times 10 and food y is equal to block size times 10 so i'm just going to put it in another random location and over here i'm going to do context dot fill style is equal to red [Music] and we're going to do the same thing context dot fill rect food x food y block size block size so if i refresh the page now you can see that the food is over here at 10 10 and in a regular snake game the food is actually randomly placed so let's create a function that would place the food in a random x and y coordinate so down here i'm going to create a function called place food and we're going to set food x to math.floor math.random times columns times block size and we'll do the same for food y [Music] okay so now let's get rid of this we don't need to initialize it and right before update i'm going to call place food [Music] okay all right so now if i refresh you can see the food is randomly placed every time okay and for those of you who don't know how this works math.random returns a number between 0 and 1 and we're multiplying it by the number of columns or rows so this becomes a number between 0 and 20 but it doesn't include 20. so it's more like 0 to 19.9999 and we need to do math.4 so that we can get rid of the decimal places so then this becomes a number between 0 and 19 and we multiply it by the block size 25. all right so that's how this uh place food function works alright so now that we have our food in our snake head let's make the snake move so over here i'm going to do document dot add event listener and it's going to listen for a key up and it's going to call a function called change direction [Music] so we're going to create a function called change direction over here so basically the key up is going to wait for you to press on an arrow key up down left or right and as soon as you let go of that key it's going to call change direction so over here we're going to pass in an event and this is going to be a key event and we're going to do if e dot code is equal to arrow up [Music] then we're going to change a velocity so we need to give the snake some speed otherwise it can't move right so we're going to have velocity x equals 0 and velocity y equals zero so down here i'm going to do arrow up this means you go up and that is velocity x doesn't change because x is left and right but to go up we need velocity y to be negative one and we're going to copy and paste this [Music] so here i'm going to do else if arrow down then it's going to be positive one and over here [Music] we're going to do arrow left so to go left you do negative one on the x and zero for y and finally for our right we're going to do positive one and zero okay so this is changing direction all right so now that we have our key handler what we need to do is update the canvas because even though we can change the direction we need to reflect it by painting that onto the canvas so before i fill in the rectangle i'm going to update the snake x and y position each time and add the velocity x [Music] and the velocity y okay and there's also one more thing that we need to add and see here we have an update function so the update function again paints onto the canvas but the thing is we only call it once instead we want to call it multiple times because the way the game works is the game is always redrawing the canvas so one moment is here so this is the first frame and then the next moment it is over here and then over here so you can see the canvas needs to keep your drawing so that it shows the snake moving each time so over here i'm going to call set interval and i'm going to have it called the update function and we're going to have it run 10 times a second so this 1000 milliseconds and we divided by 10 so every 100 milliseconds it is going to run the update function all right so now if i refresh the page and i hit the right arrow key you can see the snake is moving but it's moving actually quite slow and the reason is because the velocity is plus one so it's actually inching one pixel to the right each time every 100 milliseconds so this is not what we want instead we need to multiply the velocity here by block size so that it is actually moving one unit it's moving one square over every 100 milliseconds and the same thing for velocity y so now if i refresh this you can see the snake is actually moving much faster because it is going one square unit at a time instead of one pixel at a time okay so now what we need to do is have the snake collide with the food and let's try that [Music] as you can see every time we collide with the food the snake appears underneath it and the reason is because we drew the snake first and then the food so basically we're painting the food over the snake's head so let's flip that so over here we're going to copy and paste this and move it up here so that we can draw the food first okay now what we need to do is actually do something when the snake collides with the food so we need to have the snake eat the food so to check if the snake touches the food we simply need to check their x and y positions so if snake x is equal to food x and snake y oops is equal to food y that means they're in the exact same square we're going to consume the food so for now instead of increasing the segment of the snake i'm just going to temporarily place the food so we know that it is working all right so if i refresh the page and i move right you can see we consume the food and the food moves into a random location come on [Music] okay and also i want to fix one more thing and that is you can see if i move up i can move down and in the snake game you're not allowed to move in the direction opposite of what where you're going and the reason is because if the snake turns around it kind of just eats his body right so we need to fix that so over here i'm going to add an additional check so if the arrow key up is pressed then i'm going to check to see if velocity y is not equal to 1. so if it is equal to 1 this means it is going down so it shouldn't be able to go up and let's also do the same thing here oops velocity y not equal to negative one and this one velocity x not equal to one and velocity x is not equal to negative one okay so you're not allowed to go in the opposite direction that you're currently heading towards all right so if i refresh the page and i go right i can't go left but if i go down then i can change directions okay [Music] all right so now let's actually do something with the food give the snake some nutrition so for the snake let's give it a body so over here i'm going to do var snake body is going to be an array and this array is going to store a bunch of segments and each segment is essentially an x y coordinate so it is similar to the head except because we have multiple of them this time we want to use an array so over here after we eat the food i'm going to do snake body dot push an array of x and y coordinates snake x and snake y well actually let's do food x and food y this would be more accurate okay so it's going to grow the segment where the food was so now that we have our array our body segments we need to draw them we're going to do for let i equal zero i less than snakebody.length i plus plus we're going to do context not fill rectangle and it's basically snake body of i zero snake body of i one so these are the x and y coordinates as you see over here and we're going to put in block size and block size okay all right so now if i refresh and i eat this oh let's do it again you can see the snake just leaves its body chilling where the food was and the reason is because yes we are drawing where the x and y coordinates of the body parts are the problem is we are not moving the body along with the head so the head is basically detached so we need to fix that so over here let's move the body and i'm going to do for let i go snake body.length minus 1 i greater than 0 i minus minus i'm going to do snake body of i equal to snake body of i minus 1. so basically we are starting from the very end of the snake body the tail and before we update the x and y coordinates we want the tail to get the previous x and y coordinates so that they can move forward so what i mean is if i go back to paint let's say we have a snake of three segments or three squares and i press arrow down so now we expect the snake to look like this right because the head is now over here and if i move the snake head down we need to inform the other body parts where to go so if i move the head first then the second piece it's not going to know where to go so what we need to do is start from tail and before we have the head move we're going to say okay wait over here it's going to tell the previous part don't move yet because i need to catch up to you so after it catches up it's going to look something like this where there are two squares over here they're overlapping and then the one that was previously here is going to tell the head hey don't move down yet let me catch up so once it catches up we're going to have both the second segment and the head over here and after that segment uh second segment arrives over here the head can freely move down like this okay so we start from the tail and go towards the head and we're going to move each segment forward by one so that's what we're doing over here okay so we're starting from the end and we're having each segment move uh forward to where the previous segment was and then finally we're going to update the second segment to take the head's place so over here i'm going to do if snake body dot length this means if there are body parts in the array then we're going to set snake body of zero which is the one before the head and we're going to set it to the head like this okay so after all that is done we can freely move the head [Music] so now if i refresh the page and i play the game uh come on you can see the body is moving along with the head okay so now we are almost done except we have one problem and that is when is game over so game over happens in two instances where you go out of bounds like that or you intersect with yourself so basically you cross into your own body come on let me get this you cross into your own body and you eat yourself that's basically the idea so let's implement that logic so over here i am going to add another variable called gameover and i'm going to set it to false and over here i'm going to do if game over then i'm going to return because we want to stop updating the canvas we want to stop drawing once the game is over and down here i'm going to update our update function by adding the game over conditions [Music] so the first condition as i mentioned was you go out of bounds so basically if snake x is less than zero or snake x is greater than columns times block size or snake y is less than zero or snake y is greater than rows times block size then we're going to set game over to true and i'm going to alert game over okay and the second condition is when you bump into any of your body parts so we're going to use a for loop and we're going to loop over each segment so i less than snake body the length i plus plus so basically just like how we detect the collision with the food over here right snake x is equal to food x and snake y is equal to food y we're going to do if snake x is equal to snake body of i index 0 and snake y is equal to snake body of i index one we are going to set game over to true and we are going to alert game over all right so now if i refresh the page and i head to the left you can see i'm going out of bounds game over okay and if i go up out of bounds game over and then let's try to get enough sick uh segments so that i can eat myself uh that sounds kind of weird but oh well game over my bad let's do it again so let's try to [Music] gain enough segments where i can have the snakehead intersect with its body [Music] okay there you go so you can see the snake's head is intersecting with its body and we have game over all right so that's it for this tutorial and this is how you create snake using html css and javascript with the html canvas if you found this tutorial helpful make sure you give it a like let me know down below in the comments and don't forget to subscribe for more tutorials like this and i'll see you in the next video bye bye
Info
Channel: Kenny Yip Coding
Views: 109,193
Rating: undefined out of 5
Keywords: snake javascript, how to code snake javascript, how to code snake in javascript, code snake with javascript, snake javascript tutorial, code snake using javascript, snake in javascript, snake with javascript, program snake with javascript, code snake in javascript, how to code snake using javascript, how to code snake with javascript, code snake game with javascript, code snake game in javascript, snake game javascript, code snake game using javascript, code snake game
Id: baBq5GAL0_U
Channel Id: undefined
Length: 29min 44sec (1784 seconds)
Published: Mon Mar 28 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.