Beginner JavaScript Project – Snake Game Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
improve your web dev skills by coding a retro snake game using HTML CSS and JavaScript you'll learn how to use JavaScript to draw the game board create the snake and randomly generate food make the snake move increase the snake size when it eats and a bunch of other features adamir is great at breaking down concepts for beginners and he teaches this course we are making this retro snake game inspired by the iconic Nokia snake game we will style this awesome retro design using HTML and CSS then we'll set up our game logic we'll draw the game board create the snake and food elements we'll learn how to make the snake move and increase its size when the snake eats as well as increase its speed to make the game more fun and challenging we're also going to learn how to keep score of our snake size as the game progresses and also to track when the snake collides with the walls or itself we are we are also keeping track of the largest our snake has ever been in our high score so when we do lose a game we can keep track of what we need to beat the next time around by the end of this tutorial you will have made the best snake game on YouTube from scratch and you will understand all the JavaScript that makes it run and this video is intended for beginners to JavaScript as I will be explaining all the code we use to make this game take Life by the end you will have learned to create and manipulate HTML elements using JavaScript and you will have learned simple game logic and design and we will be using VSS code as our code editor Google fonts for our retro font as well as an AI generated image for our snake game logo as always you can find deployed game and GitHub repo in the description below if you're ready to make your own addictive version of the very best snake game you will find on YouTube let's get started the first thing we're going to do is open up our vs code open an empty project I am just going to create a new folder on my desktop and I am going to rename that to snake game and I'm going to drag that into vs code so now we have that open in our Explorer the first thing we are making is our index file so new file we're going to create an index.html file and then we are going to write exclamation mark and then we get these shortcuts here with emit abbreviation we're going to hit the first uh the single exclamation mark to give us some boilerplate HTML let's give it a title of let's say snake game save that and then let's actually if you don't have that install already there's an extension tab here you can look for live server by which we day so install that uh if you don't have that installed that's going to enable us to run this game uh live without having to kind of refresh the page to get the latest changes and also to make some of the JavaScript work we're going to need to run it live so let's hit that little go live button and you'll have that if you installed the extension and that is opening up our browser here here as we can see snake game is written in the top here so we see that is correctly rendering the little HTML that we have so far then I'm going to go in here in View and I'm going to turn on word wrap to get all the text neatly visible on the screen let's now also create our CSS our style. CSS file and let's also just create our script .js file uh while we are at it those are the three files we need nothing else now let's link these files up with each other so in the head of our HTML under the title we are going to first link to the stylesheet and writing link we can now choose the third option which is going to give us the standard way of writing a stylesheet and we've already cheated a bit because we've called it exactly what the standard is so now let's just check that by writing body in our stylesheet and some curly brackets and giving it a background color of red hitting save and we see that that is updating correctly so let's just remove that for now same thing with uh the script we're going to link that up now writing script script and Source third one and here we're going to give it script.js and hit save so here let's try console logging a shortcut is just writing log and hitting enter or tab depending on your um system preferences and that gives us the full console log so we're going to console log test and then in our browser we're going to inspect and we're going to go up to the console here and we see that we have test indeed getting uh logged so it is working as well let's now remove that back in our index file let's also be sure to write uh the defer attribute inside of the script opening script tag which is going to say that it's going to run the script after it has run everything in the HTML which is going to help us avoid a lot of error and that also makes us be able to put the script neatly in the head which is the best practice so inside the body we're going to write a div and that is just not going to have any class or anything but inside of that div we're going to write another div and it is going to have the class of scores that is going to keep our score then inside of here we are going to have an H1 it is going to have an ID of score and here we can just put that to 0 0 for now and also another H1 with an ID of let's see high score with capital S and we're also going to put that initialize that as 0 0 0 then under this div we're going to create another div and it is going to have a class of game border one and hit enter or tab so what just happened well I used emit abbreviation um and you can actually create a div and if you write div and then dot that dot signals that that's going to be a whatever you write after here is going to be the class name so like so so that can save you a bit of typing inside the game border one we are going to create the game border two cuz it's getting a bit meta here we have some nice borders around our main um game board and we're simply using these divs to style and give them different colors and borders so this one is going to be game border 2 and then third one with a class of game border let's see three and inside of the third game border we're creating the div that is actually going to have the ID of game board like so so obviously we don't see anything yet CU we haven't given them any style whatsoever or any properties they don't have any height no width nothing then just above the closing body tag we're going to create another H1 it's going to have an ID of instruction text and that is going to be the one that says press space bar to start the game like so and then also under there we're going to have an image and that is going to have let's see the alt is going to be the Snake logo so we don't have the image just now but if you look in the description there will be a link to the Snake logo image this is free of use it's an AI generated image so feel free to use it for your project so go in the description uh look for the snake image uh link download it and then drag that into the um repository here I'm doing the same it's called snake game AI gen PNG so now in our source attribute here in the image we can uh link to that so snake game AI gen and we hit save there we go cool so now we can move on to our style. CSS let's actually first before we move on let's target both the H1 and the image and just comment those out if you hit uh control KC that's going to comment that out or command KC for on Mac and then we hit save because um we are hiding and unhiding those elements on our in our JavaScript later but in the meantime uh just to make it a bit easier for us to see what's going on we're just going to hide them for now so now we can pop up into our style. CSS file let's also inspect in our browser and we can stay in the elements I'm going to open the body here the div just so you can see that we have all the elements here we have our game border with literally no properties all these no properties they're just empty divs so now we're going to give these div more life and make this actually look like a game so body going to Target that first we are going to say display Flex so that we can have things neatly under each other and centered we're going to align it align items to the center we are going to justify the content to the center as well this is going to align items uh both uh vertically and horizontally to the center then we're going to give the body the height of 100 view height so it takes the entire height of the screen then we are going to give it a margin because by default you see we have this scroll bar here that's because the body as you can see here when I hover over it has this orange by default margin of what is it uh 8 pixels so we're going to remove that and say zero and that removes the scroll bar then we are going to give a fult family which is going to be something we're going to get from Google fonts to make these numbers and the text we write more game like more retro and more like pixelated we are going to get that from fonts. goole.com it's completely free to use and quite easy in Google fonts you're going to search font you're going to write VT and then you're going to see this vt323 that is the font we're going to be using if you scroll down you're going to see a select Reg 400 you're going to hit that and then you're going to go in the top right corner you going see we have that selected you're going to copy this link here we're going to head over to the index.html file Under The Meta tags here and over the title you're going to paste that in and then this preconnect stuff basically loads the the font a bit sooner and then this link redirects to the correct font hosted on Google fonts so here we're telling our stylesheet that basically now you have access to this font and how we use it is we use this CSS rule here so we can copy that head back to our CSS and let's also go back to our snake game we have our zeros here if we save the CSS we see that it reloads because of the live server now when I paste in here the font family we see that we get our nice retro design cool now we are ready to move on so next we're going to Target our body as well as our DOT snake class that we haven't used yet but we're going to be using in our JavaScript so we're just going to Target it at the same time we are giving them a background color that is quite dark uh so it's hash 414141 which gives us this uh dark grayish color then we are also going to Target the ID game board game dashboard and we're going to give it a border radius of 100 pixels we are going to give it a display of grid so this is where we're actually making the game board with this grid and then we're going to give it a grid template columns so how many columns is this grid going to have well it's going to be repeat 20 columns and each of them are going to be 20 pixels wide and then same with rows grid template rows that is going to be repeat 20 by 20 pixels like so so let's check out our body now game board game board two border game board here we go can we see that okay so we see now that we have if we hover over game board here we see that we actually see the game board it is 400 * 400 pixels wide and um size basically and it has 20 * 20 a little squares in inside of it so that's the grid we just made this is our playing field that we're going to be using throughout the game lastly here we're going to also give it a margin of five pixels because later on we are going to have a border here and this margin basically makes it so that our snake when it hits the Border it's not going to overlap the border and it's going to create a neat um uh visual aesthetic so it's simply for visuals this margin then we're going to Target the game border one and we are going to say we're going to give it a border of hashtag and that's going to be 5 95 f43 and that's going to be a solid border and it's going to be 10 pixels wide there we go and and then we're going to give it a border radius of 30 pixels to round that out a bit as well as a box shadow of inset and I'm going to explain in a bit why we're using box Shadow here in addition to uh the Border but it's easier to see once we actually have some more elements this is also going to be 10 pixels and it's going to be the color of it's going to be the same color actually 59 5 f43 save that so you slightly see the the Border here so if I comment that out control KC you see that the Border actually goes on the outside of the game board whilst the if I comment this in again you see that the uh box shadow goes on the inside it's a bit hard to see because it covers it but you see that the border is basically here so the Border goes out the box shadow box shadow goes in and because we have different radiuses on these different game borders without the Box Shadow it would basically give a a little gap between one and the other so that's why we're adding a box shadow in addition to a border but I can show you that and then you'll see why so let's just call copy this whole game border one down so shift alt down or shift option down if you're on Mac and you can hit that twice and I'm just going to copy that code so let's say game border two and game border three hit save and now let's alter it so it's the correct colors so here it's going to be um let's see a BB 78 a and we're going to give that the same color here A B B 78 a and the third one is going to be 8 B 9 66 C and the same color for the Box Shadow there we go hit save now we can see the difference between them so now let me me remove the Box Shadows like so by commenting them out hitting save and that's here you can see why we are adding those box Shadows because we're avoiding that little Gap there because these have different border radiuses if they had matching border radiuses but they don't and we don't want to have it either because that's the visual aesthetic that gives it that more uh cartoony and Vibe so let's comment that back again but we're going to change the um the different properties here in game border 2 The Box radius is going to be 26 pixels in game border three the Box radius is going to be 20 pixels like so and in game border two it's going to be for the Border it's going to be not 10 pixels but 8 and for the third one it's not going to be 10 but 30 like so let's see if we can see the allall there we go starting to look more like it and the same here in the third uh game border 3 the Box Shadow is not going to be 10 pixels but five so that is all for the borders now let's move on to the instructions text instruction text then we are going to Let's comment back these in the index.html so control KU that's going to make them show up again so just to see them then we are going to position it we're going to position it absolute like so we're going to position it from the top 60% we are going to give it the color of # 333 we are going to give it a width of 300 pixels which makes it also um fold under each other we're going to text align it to the center we are also going to text transform this to capitalize to capitalize each word we're going to give it a padding of 30 pixels and we're going to give it a margin of zero these are all just simple stylistic choices just to to make it look good uh it's not still not looking good because we have this snake image here that is still positioned relative to the other elements whilst the positioning of absolute kind of frees it to be just positioned within the frame so now we're going to Target the scores as well that's our two scores up here we are going to say display of flex and then we are going to justify the content to space between like so then we are going to Target the score and we're going to give it a color of hasht ABB 788 gives us that nice green then we are going to Target both score and high score capital S and we're going to give it a font size of 40 pixels we're going to give it a font weight of [Music] Boulder and we're going to give it a margin of 10 pixels and zero hm why is the they should not be so score should be on this side and high score should be here but it's not happening so this scores here is not targeting properly let's see class ah I see I think yeah okay so this is a class as we can see here class scores and we have defined it as an ID here so let's just remove the hashtag and another the dot and that solves it there we go looking way way better and as intended now let's target only the high score again remember capital S we're going to give it a color of Hash d8 D D CA like so bit more whiter but still on the green scale and we are going to give it a display for now of none cuz until we start the game the first time and actually um hit into something so we can save the score we had we're going to kind of remove the high score to give more of a visual um um element to it so there's something new happening once you actually have played the game then we are going to Target the game border 3 together with the logo and we're going to give both of them a background color of hasht C4 cf3 starting to look good then we are going to Target the snake and we're going to give it a background color we're not going to be able to see this yet now but uh we're going to see it soon once we start with our JavaScript 41 41 41 actually we have that already here so we don't need that let's remove that we're going to give it simply a border of # five A5 A5 a one pixel and that's going to be dotted there then we're are targeting the snakes food and that is going to have a background color of hhde DDE as well as a border of # 9995 pixels and solid and then lastly in the CSS we're going to Target the logo and we are going to position it absolute straight in the middle H we did we add we didn't add the class in the HTML so go to the HTML and then the image we're going to give it a class of logo sorry an ID of logo save that and then we see we have something looking better here now we are ready to move on to our JavaScript so let's save the style and the index and then we can open our script file and the first thing we're going to do here is we're going to Define HTML elements that we need from uh the HTML that we're going to manipulate here in the JavaScript so the first we're going to uh get a hold of is the game board because we need it to do anything in the game so we're going to Define that using the cost and we're going to say we're going to give that board as a name and then we're going to use the document property and then the get element by ID method so then here we're saying uh the constant board that is going to be equivalent to if you go into the document that means the entire page here the entire HTML document and then you get the element by the ID and then let's go to the HTML and see what the ID is game board so let's copy that and head over back to our script and then be sure to add some brackets here and gameboard and hit save and then let's log that just to test log board and then let's inspect go into our console and we see that it has successfully logged the game board with a div uh with the ID of game board so it works cool let's remove that and it disappears so then we are ready to start actually the functions of our game so we're ready to start the game well we can't start the game just yet because we first we actually need to draw the map so we're going to create a function called Draw and this essentially is going to draw let's see draw game map it's going to draw the snake and also the food so we are going to first we're going to take the event that if we have started this game before we're going to need to reset the board so we're targeting the board we just made here and we're going to say inner HTML and we're going to say set that to just empty strings so that it's empty so then every time we draw this board is going to be reset then we are going to call another function because we're going to draw our snake so we don't have this function made but that's what we're going to make just now so so next thing we're going to draw Snake by defining this function we just used or called function draw Snake and inside of here we are going to need basically to Define how our snake looks and the way we are doing that is by actually using um an array an object inside of it so if we go back to the top here under the const board we are going to also Define game variables and here we're going to say let snake and we're using the let and not the const because the board stays the same but the snake is going to change in size so let snake equals an array with one object object inside and that object or in fact all the objects that the snake is going to have throughout the game is going to be um positions within the game map so it's going to have an X position that is going to be 10 and it's going to have a y position that is also going to be 10 this essentially if we go back and we inspect our game map here we see that we have a game board and it has 20 rows and 20 columns so the 10th row and the 10th column more oress in the middle is going to be where the snake starts so that is what we have defined here let snake is this position now currently it's only a position it's nothing else there's there's nothing tying it to the game board but we'll get to that so now we are uh continuing with our draw Snake function inside of here we are going to take the snake that we just made and we're going to say four each which is an array method so we're going to say for each of the children it has in here so for everything that is inside this array so now it's just one object so that's going to be for each object which is just one for now we're going to say for all for all those segments for each segment do something we're going to call an arrow function and inside of here we're basically running some code on every single element that is inside of the snake so at the start of the snake is just one dot so what are we going to do well we're going to define a new const here we're going to say snake l element is equal to create create game element this is something we haven't as a function that we haven't made yet but we're going to make shortly so we're going to say create game element you're going to create a div and then that div is going to have the snake class let's also go to view and word wrap like so so basically this function that we're going to create is going to be responsible for creating every snake element and for giving it the snake class it's going to be a div with a snake class that we have already styled here in our CSS that has a border and the background color and that essentially gives the illusion in a way that there is a snake on the board here so before we move on here and do something with the snake element let's actually make that function so it's going to be the function that is responsible for creating a snake and or or food Cube or div so that's going to be the function create game element and it is going to take uh an argument tag and it's going to take class name so as we can see here create G element we're giving it a div and we're giving it the class name snake so that's the tag is a div and the class name is the snake and then we're going to say const element is equal to document dot create [Music] create element like so tag so inside of the create G element we are creating a new constant element that is using the same way to Target the the HTML but here instead of targeting an existing element by ID like we did here we're actually just creating a new uh HTML element inside of our JavaScript that's what this inbuilt method does and we are saying that you should create a tag and the tag is whatever is sent in here in this position and we can see here that the div is sent in so here B essentially what is saying here is document create element div when it's used like this this but if we used it somewhere else or if we change that to P that would be a paragraph that would be created then we are going to go into the element that we just created we're going to go to the class name of the element and we're going to give it the same as class name so this might be a bit confusing because this is what we call the um argument here in the the function but it's also the same name as what the actual um property on this element is so class name is also the inbuilt definition of a just simple class which is what we use in um HTML but essentially what we're doing here is we're taking this snake here inside of the great game element and we're adding that to the div that we are creating as the class so what this does is creates a div with the class name of snake and then we need to also return this element that we just made like so so now con snake element is equivalent to a div with a class of snake then we can move on inside of the draw Snake function so the next thing we're going to do then is we're going to call another uh function that we haven't made yet so it's going to be set position and here oops set position is also going to basically take similar arguments snake element and also segment let's scroll down and create that set position function what this set position is going to do is going to set the position of the snake or the food so once we've made it it's going to actually set it on the game board or actually Define the position it's going to have on the game board so we're going to create that set position and that's going to take the arguments of element as well as position and inside of there we're going to take the element we're going to go into the style of it and we are going to say grid column is going to be equal to position X so essentially what we're doing here we see that we are using the set position here we have created the snake element we created create a div with a class of snake then we're sending that into set position and that's the element here so here we're we have a div class snake I'm going into its style we're going into this grid column which is a CSS uh property and we're setting that equal to position dox so what is position well here we're sending in segment and segment if you remember is for each segment here that's basically every single object here that is a coordinate inside of the snake so as the snake grows basically it's going to have many of these uh object inside but at the start it's just X10 y10 so that's what we are sending in here so position X means this position here 10 because position is this and that is this segment and segment is simply this so segment X segment y position X segment X okay I hope that makes sense um we are going to see that soon in action and then it's going to be more clear to see what is going on we also need to set the element. style grid row and then we set that to position y so that we both have the X which is the horizontal coordinate and also the y coordinate which is the vertical now let's actually see how this works uh in practice so now let's actually go to the draw Snake function under set position we are going to Target the board we are going to append child we're going to actually take the board element the HTML board here and we're going to add the snake that we just created snake element like so now if we actually call this function draw we should be able to see our snake element so testing draw function draw we're not going to call it like this but just to test if it works and then let's also remove our two texts here so we can see like so there we go there's our snake let's go back to the script let's comment out our draw function there is no snake and once we call the draw we see in the game board we have a div class snake and look at the style here if you can read that it's small I know but if you can look it there has style grid area 10 * 10 if I now edit this in the element dot style here and I change that to let's say two you see that it goes here one here 2 3 4 and it goes gradually down if I give it a one two if I give it a 20 it's at the end 18 so that is what we have been positioning here you can also do that directly in the JavaScript if we change that to 20 and 20 that should be the bottom right like so and 120 should be the bottom uh left like so so I hope it makes a bit more sense and pat yourself on the back we just made our first snake element we made the snake head so now we can actually remove this I'm just going to comment it out for now and we are going to create our actual food as well so draw food like so inside of the draw food we're going to create a const called food element which is going to be equal to using that create game element function again we are going to create a div but this time instead of snake it's going to have a a class of food which we are of course targeting in our CSS then we are going to set position so this is as you can see it is similar to the draw Snake uh function so set position we are also using the already made uh function we're going to give it the food element as the element and then for the position we're going to give it food which we haven't made yet so let's make that if we scroll back up under let snake we're going to say let food equals and because food is going to be automatically generated it's not going to have the same position every time cuz that would be boring wouldn't make a very fun game we are going to call a function here to give it a randomize position so generate food is going to be called here we have not created this so let's copy that name and create a function generate food and let's just leave that blank for now continuing inside of the draw food function we also need to actually append this food to the actual board so board append child and then food element like so so it's pretty much the same setup as in the draw Snake now in actually to actually get this food position uh cuz now it's not going to work it's not getting the function is not returning anything so let's move on to our gener generate food function let's also just comment here this is draw food function inside of our generate food function we are going to create a new constant called X which is going to be its X position we are going to use the inbuilt math object here which has some cool inbuilt methods like random which gives us a random number uh in JavaScript so this is currently just going to give us math random is going to give you a random number between zero and up to one not including one though so it's going to be 0.1 0 uh 39 0. 99.9999 so everything apart from one so 0 to up to one then we are going to times that times 20 we could do that like uh put 20 here because we know the grid size is 20 but let's rather go up to our game variables and let's just Define a new constant here call it grid size equals 20 and then we can use that here instead so if we want to change the grid size later we can easily do that here and then because we are getting this math random you know up from zero we don't want a zero position cuz the grid starts at one right so we're just going to take all of that and we are going to plus one but then we also have a new problem is that this is basically giving us um not whole numbers it's giving us commas so we need to also use something called math floor on it which basically takes whatever this expression is and it floors it so if it's 1.99 it's going to turn into one if it's 3.20 it's going to turn into three so that's what the math floor does and the one at the end is simply to raise this from zero to start from one all the way up to 20 so that gives us the X it's going to be the exact same thing for the Y so let's just copy that call it Y and then we are going to return this as an object X and Y and save that so now generate food returns a random coordinate in X and Y position let's draw the function again let's uncomment the draw function and let's see let's see generate food are we actually using it anywhere I see we have not added the draw food uh function here so we haven't actually called this function ever we're calling the draw but we're not calling the draw food inside of it so draw food like so there we go now we have our snake if I hit save again here it should as it is doing giving us a random position for our food uh di here how cool is that so now when we start a game it has a random position well snake is always at 10 10 okay now let's move on to actually getting this snake to move let me just comment here generate food it's a bit self-explanatory but we've started commenting every function so we might as well continue next one is going to moving the snake so function move it's going to be called and then inside of that function we're going to create a new constant we're going to call it head and this is basically going to be the head of the snake but it's not the direct head uh it's not actually this object here the first object we don't want to manipulate that uh we want to make something that is called a shallow copy because if we don't then we're basically going to run into some problems very usual in JavaScript where you don't actually want to alter the original object or the original array we want to use the position of the head but we don't want to actually alter it so we are going to call the spread operator on the snake zero which is going to be the head here cuz in an object it's zero index base so the first object or in an array sorry the first position in the index is zero so we're getting a hold of the snake zeroth position which is 10 10 and we're simply spreading it into this new object this is basically a copy of this but it is not changing this otherwise we could just call it like this but if you try doing that you're going to see that it's not working and you're going to run into some uh weird uh Behavior basically then we're going to create a switch statement here where we are taking the direction of the snake now we haven't made this yet we're going to create it now and the direction in the start if we go up to the game variables here let direction is going to be by default to the right let's scroll back down so we're taking the direction we're running a switch case on it and inside of the switch case we're going to have different uh cases so if the case is like it is now let's see right then we're going to take the head and we're going to say take the head take its X position and you are going to iterate that or you're going to increment that what that mean means is you're going to increase it by one so if you press right you're going to go into the x coordinate that's here that's X and you're going to go one up so that's from this place to that place which kind of fits if you're going right you want to go right so that is what this is doing so the direction by default is going to start moving the snake in the right direction we need a couple of more cases though well we need three more so let's just copy those in so if the case is up we're going to actually go to the y coordinate and we are going to go Y and decrement because the position up here is one and if we go if we press actually from the start it's 10 if we go up we're going closer to one so we actually want to go down in uh numbers so that's why this might seem a bit counterintuitive but it makes sense then we're going to take that down then it's going to go Y ++ and then left is going to be x - minus now we have the start of our move function but we're missing something here so basically here we are um moving the head but here we are actually taking the head we are un shifting it and we're giving it the head so what unshift does is it basically adds a head object to the beginning of the snake array so this head here which is a copy of the original head it is basically putting that at the start of the snake array here so now it only has one um object here but when we for example go uh uh up we are going to be pushing or un shifting a new uh object inside of here so up would be X same y it would be nine so that's what happens if you would to press up from the start of the game and that is what we are doing here uh after the snake unshift we want to also take the snake pop like so because what we are doing here when we're moving as you might have noticed if we're un Shifting the head we're adding a new part to the snake we are actually just elongating the snake so if we were to move 1 2 3 4 you would see that the snake doesn't move it just grows in that direction so that's why we're also taking the snake and we're calling pop on it because as you can see here it removes the last element from an array so when we go right let's say we are adding a piece here but we're removing the last piece so it gives this illusion we're actually just building a snake a new elements in One Direction and we're removing the elements behind it so it gives the illusion of movement but actually it's just being rebuilt and destroyed uh one after the other now let's simply test this function test moving so we're going to call a set interval uh in build function because we want to move more than once and we want to call the move function that we just made so that's going to move first and then we want to draw again cuz uh if we don't draw then we're not going to see the new changes so then draw again new position and let's also comment that out like so and then finally we also need to have a time on this so let's give it a 200 milliseconds and as you can see now when I start the game and I reload for every 200 M seconds or 1/5 of a second the snake is moving in the direction of Direction which we have put to right let's change that to up as we can see it goes up and then down let's say working left working so you can choose whichever you want to have by default I'm just leaving it as a right so cool our moving function works so now we are actually ready to also make the snake uh become bigger if it hits the uh food and it's actually quite simple and elegant solution so as I told you if I uncomment this now look what happens the snake by default just grows because that's actually the move is actually more of a grow function it is that we remove the last part so the only thing we need to uh do to make the snake grow when it hits the uh food is to just remove this function when it hits the same coordinates as the food element so let's just take this away let's uh comment that out so we can uh see what's going on let's go back inside of the move function under this snake pop we're actually going to comment that out we are going to create an if statement and if head remember that's what we defined here as the shallow copy if the head x coordinate is equal to the food x coordinate and as you can remember the food we have here randomly generated that's this coordinate here so if those two are equal and head Y is equal to food y so basically if they're on the same spot then we're going to run some code so then we're going to say food equals generate food because that means that we have run into the food so we need a new food placed on the map so then that would happen so if we hit it it's going to create a new random location for the food then we also want to uh clear the interval it's another inbuilt method or function because otherwise we're also going to run into some um issues and it's basically we just want to reset the movement and the whole uh move function here otherwise uh a lot of bugs are going to happen so we're clearing clear past interval then we want to go into the game interval which we have not defined yet we going to go back up to our variables we are going to Define let game interval and we're just going to Define it that it exists and we're going to go down here it's keeping track of when we are running the our game basically so we're going to take the game interval we're going to set it to a new interval cuz we already had paused the other one and here we are going to run some code we're going to run a new move we're going to reset that we are going to also run a new draw and reset that and then we are going to add that we're going to add the game speed delay because instead of uh setting it to 200 here we might want to change it which we actually do when we eat a food we are decreasing this delay and thereby increasing the game speed so we also need to Define this let game speed delay and we're going to start with 200 milliseconds so then scrolling back down then if our head is on the same position as the food we generate a new food and we then skip the snake pop so snake pop is not happening here and thereby this one uh div snake is going to turn into a two div snake it's going to basically turn into the position uh of the food else we are going to run the snake pop so I hope that makes sense basically if we don't run into food we're going to be continuously building building the snake One Direction and then we're moving the snake back or the tail and then if we hit the food we're just going to not remove the tail and therefore the snake is going to grow now we're going to move on to actually creating our start game function which is going to be called originally start game inside of the start game function we we are going to use the game started variable that we are going to create and we're going to set it to true so let's scroll up and let's create let game started and initially it's going to be set to false like so and then when we start the game it's going to be set to true so here we're going to basically keep track of a running game that's going to be very useful um to enable us to basically if we want to start the game we want to hit enter and we don't want to be able to start the game over again while the game is running things like that so it's very useful to keep track of if it's running or not then we want to take the instruction we haven't defined those either let's scroll up and let's get a hold of const instruction text equals document get element by ID and we are going to Target the instruction text let's just see if we gave that correctly let's also uncomment them in the JavaScript code so now we see that they are taking the space and we want to actually hide them when we start the game so yeah instruction text let's just copy that for safety and paste that in there we also want to define a const logo document equals document get mement by ID and that's going to be logo like so now we scroll down and we can use them here in the start game so instruction text we are going to go into that style and display and we are going to set that to none when we start let's also shift all down and we're going to do the same with the logo so when we start the game we're going to hide these two and basically we're going to get then view the snake and the food again unobstructed then we are also going to go to the game interval and we're going to set the new interval and when we start we're going to call the move we are going to call the check Collision function that we haven't made yet collision and we're going to also call the draw and that is also going to be run on the game speed delay like so let's comment out the check Collision for now that is the function we're going to create to basically see if the snake is running into the corners or into itself but let's not get ahead of ourselves we're going to create that later so for now it's just comment that out and let's also we are calling draw here in our start game let's go up to line 45 let's um comment that out like so then we are ready to actually make to start our game so here it says press space bar well if we do that nothing happens because we're not listening for the space bar that's what we're going to create now we're going to create a key press listener event listener like so and that is going to be function handle key press is taking an event and inside of here we are going to call the start game but not um at any point so if we press up Arrow we don't want to start the game we just want to move the the snake so if the game started so if the game is not started with the exclamation mark and the event. code equals space then we want to let's see like so then we want to start the game called that function and this doesn't work for every browser so we also need to call let's see or like so and let's wrap these in uh in parentheses like so and then we can create another one here let's just copy this so if game started an event code equals space or if game hasn't started an event key is just an empty space like so so that's going to basically handle um every browser's um handling of space key if the game hasn't started and we press the space then we're going to start the game else we are going to handle the arrow keys so another switch case here and we're going to handle the event key because that's the event we're getting in here that's the key we press first case is going to be Arrow up so these are the basically the shorthand uh phrases for the different Keys they're inbuilt and let's see we want to handle it like this call on then we're going to take the direction and we're going to set that to up so remember the direction is what we have defined here it's by default right but if we press now we're listening to key presses if we press up it's going to change to up and that is going to affect how the move function moves and it's going to change the direction of the snake so here we are basically listening for the handle key press and that sets the chain of motion for the snake Direction and then we are going to break after that then we're going to copy this down one 2 three times arrow down that is going to change it to down arrow left and that is going to be left and arrow right that is going to be right like so and we're breaking out of that switch case after each uh case then we have our handle uh key press function ready now we need to call it so now we're just going to go to the document we're going to add an event listener and we're just going to listen to that all the time I'm going to listen to key press actually key down and for every key down we're going to call the handle key press so when we that's the event we take in here and we're going to call handle key press so if we have clicked something or press something that is the space it's going to call the start game if we click something else then we are going to move the um the snake so let's try enter it works how cool reload enter it works and now I am also hitting the arrow keys how cool is that now we have a snake that is moving let's see if we can eat and there we go oh we are speeding up by a lot that is a bug but we are moving around around and we are increasing our size as well sped up a lot it's hard to eat the second one in any case we have successfully started the game we have successfully changed the direction of the uh snake and we are making it grow by eating food we have a bug somewhere where it's actually increasing the um speed drastically so let's go to our uh start game let's see no that's uh correct maybe we have something in our um when we eat it changes when we eat so here we're also going to call the uh check Collision function like so we're just going to comment it out for now so be sure to add that uh in the if statement in the move so game interval we're setting an interval we are let's see we're calling the move we're calling the check Collision we're calling draw on the game speed delay else no no it looks good I wonder if we are simply um unknowingly to us we're altering this game speed delay so let's just um go into here into the if statement here we're going to create a new function under or over clear interval we're going to call increase speed function and we're going to create that right away so under our event listener going to call the function increase increase speed and then we're going to log the game speed delay let's see now what happens if we start it's 200 okay 200 okay so it's not to do with the game speed H let's Try by adding the if statement if game speed delay is bigger than 150 then we are going to decrease it like so by five let's start again still speed speing up very fast H let's comment out that start again it's 200 195 so it has nothing to do with the game speed delay at least uh I see what we did wrong okay here in the clear interval we are actually not clearing anything we need to clear the actual interval game interval there we go now let's see if we start the game ah there we go now we're also logging the speed as we can see we are successfully eating food growing the snake and it is not um increasing in speed uh drastically it is increasing in speed normally as you can see going from 200 to now 155 which is a way more uh normal and easier way to play the game and now we've hit our uh only condition in our speed uh like increase speed function which is 150 so it's not increasing more also you can see we don't have the Collision function working so we can just walk through our own snake our own body we can hit the corners nothing really happens then down again into the increased speed function let's add an else if statement here else if game Speed game speed delay is bigger than 100 then we're going to run uh different uh let's see game speed delay is going to be minus equal to 3 so basically we're going to decrease the speed increase the faster it gets so that it's not going to get to a point too quickly where it's unplayable basically but it's still going to increase incrementally then let's copy this paste that there two more times for the 50 Mark and also the 25 Mark which is starting to become very very fast so one and two now if we save and we restart the game we can see that when we hit 150 it is going to be um decreasing by three instead of five here we go when we hit under 150 we are going to 147 144 141 so uh decreasing by three instead of five which is exactly what we have coded right now if you're wondering how I'm resetting the game I'm simply just saving the script file now we can go on to actually make our Collision like check Collision function that we've been using uh in at Le at least two places so check collision and this is going to be the thing that resets the game if we hit the wall or we hit our own body so const head is equal to snake and zero so here compared to the spread operator we have up here we are not uh us using it here we are simply uh say setting it exactly equal to the zeroth index of snake namely the head then if head X position is less than one meaning that it's here is the one meaning is zero it's going to hit the wall or or head X is a larger than grid size which is 20 it means it's going to go on the right side over so it's going to hit either here or here so this one or head y is also smaller than one or head Y is bigger than grid size in that case we are going to reset game and that's a function we haven't made yet but that function is going to basically reset our game when we hit uh the borders of the wall now we need to take the we need to check also for the times when it hits itself so here we're going to need a for Loop so four we're going to Define I let I equals one starting at one and I is going to go towards snake. length and then when that happens it's going to increment by one so what that means is we have an I that we just randomly defined as one we just made and I as long as I is smaller than the snake length which is at the start it's just uh one then we are are going to increment it so we're going to go basically through the entire snake length that's the point of this so for every part of the snake we're going to run a piece of code that's the point of the for Loop and then inside of here we're going to have an if statement and we're going to check if head X is equal to snake in the position of I because the position of I is going to be starting with the body and going upwards so if snake i x so here we're checking if the head is the same position of the snake uh body in the E position and the same snake one I equals snake I position and y coordinate because otherwise it might be on the same position in the X Direction here but it might not be in the Y so we need to check for both unless it's uh hitting on both the X and the Y it's not in the same exact position but if it is we're also going to reset the game then we are we going to create our reset game function reset game also let's go and uncomment the check Collis we have let's see by searching for it contrl f we're going to remove those comments here and here there we go now we're using it now we just need to create the reset game function inside of here we are going to call the snake and we are going to reset that to its original uh position x equals 10 we need to create a object in here x = 10 and Y = 10 we're also going to take the food and we're going to reset that by generating the food again randomly we're going to reset the direction to right which was its original position and we're also going to reset the game speed delay to its original 200 when that happens when we reset the game we also want to update the score so update score let's make that function right now function update score we're going to create a constant here current score is equal to snake dot length the length of the snake Min - one because the snake length starts at one so we don't want to start the square at one all the time we just want to start it at zero makes more sense but you're free to choose then we want to go go into the score that we have made up here oh we haven't actually we haven't made that yet so let's create a constant score is equal to document dot get element by ID and it's going to Target the score element and here we're going to go into that element we are going to go into the text content and we are going to set that equals to the current score two string and then we are going to pad that to the start with three uh numbers and that's going to be zero so what does this mean well we're basically setting the score text content here equals to the uh snake length and we're turning that into a string so that we can also make that a triple digit number without this PAAD start it would turn it into one it would remove the uh two zeros and turn it into one so this is just simply some flare to make it a triple digit number and start uh counting from the end here which is the P start here it's going to add zeros if the number is not big enough so if the number is 20 it's just going to add one zero if the number is two it's going to add two zeros then we need to actually call this function we're going to go up to our let's see our draw and we're going to call the update score here now if we start the game let's try and there we go we see that we have our score starting to tick how cool now it's starting to become an addictive game okay and let me also just demonstrate if we H remove that and we said two to the pad start let's start the game we see that now we have two numbers in instead of three change that back to three like so but there are more things we want in our reset game we also want to actually once we have hit something we want to also have our high score so we need to also update high score and also stop game so those are two functions we're going to create right now so first let's take the stop game function so stop game and inside of here whenever we want to stop the game we want to actually clear the interval and what interval the game interval then we want to go into the game started and we want to say well now it's not started anymore now it's stopped and then we want to go to the instruction text style display and we want to say that it's a block because before it was hidden and the same with the logo we're going to go into the style display and we're going to say block that's for the Stop game then creating our update high score we want to then call a constant current score similar to earlier we're going to say that it's length actually snake do length minus one then if the current score is bigger than the high score then we want to set the high score to current score now we don't have the score May yet or the high score Let's see we are missing the const high score text equals document get element by ID and that's going to be high score like so now we have that we also need to actually Define the high score in the this is just the element for the text but we also need to define the high score here so under our generate food let high score equals to zero at the start now let's scroll back down so if high score if if current score is bigger than high score that's this one if it's bigger than what we have here it is going to be set as the new high score that's what we're doing here and then we're also going to unhide the high score text text content equals high score to string and it's the same as last pad start and it's going to be three digits and it's going to be with zeros then here we are unhiding it high score text style display and equals to block so now if we start the game and we get a score let's just crash into something we also see that our Collision is working and we crashed and we we had only one in score let's start again and we see so now we have one let's try to get a bit higher number two high score stays the same but score is incrementing three and four and crash and then four is saved here so now we're starting to get the real game elements that want want makes you want to keep playing more and more so now we have most of our game done but I don't know if you see uh when I restart the game you see that sometimes the food is generated here and it doesn't really look good uh like here we want to have the logo we want to have like press space bar this food looks a bit off so the way we're going to do that we're going to scroll up and we're going to fix or tweak speak the draw food function a little bit so where is it draw food here it goes so you know how we have this game started function here well we're basically going to wrap this draw food in that in an if statement so if game started then we are going to allow this uh stuff to happen but but if not well it's not going to happen now draw food is only drawing food if the game is already started and on this screen it hasn't started until we press space bar so now if we start the game over again we can see that the food actually starts dra uh drawing rendering on the page once we have started the game and now it's not going to show up and is never going to show up on this page when we have our logo and our text showing and there we go let's do a final trial I am eating the snake eating the food sorry I am the snake let's see and we are successfully growing let's see if I hit myself then it's game over high score is updated score is reset if I hit the edges same thing great now we can remove this console log as well let's see console log you can just comment out that that is everything for our snake game I hope you enjoyed it I hope you now can also have fun playing this game you can also tweak it further if you want there are many things you could add here you could customize the way the score is counted you could add for example if you are eating food close to the snake body or the edges that could maybe potentially give you more score you could add score a bit depending on the time that you have been playing so the more you play the more score you also uh increase or you could also make it more um Advanced the way the speed is increased maybe also based on the score so there's many things here you could do to increase and further tweak the game to your liking you can also change the style you can change the design of the snake and the food there's many things here you could do and I encourage you to to play around with the uh code that we now have and make it your own as well um I really hope you enjoyed this game uh if you liked uh if you would like to put it uh online and you don't know how to do that then here is a video that explains how to host your game live for free using netlify and I'm looking forward to see you in the next video Until then see you
Info
Channel: freeCodeCamp.org
Views: 90,199
Rating: undefined out of 5
Keywords:
Id: uyhzCBEGaBY
Channel Id: undefined
Length: 98min 19sec (5899 seconds)
Published: Thu Dec 07 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.