Learn JavaScript by Building 7 Games - Full Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Hey, and welcome to the JavaScript games course in which you will learn how to build seven awesome grid based games. Coding to build tangible projects is definitely by far the easiest way to learn any language. This is why I've chosen seven easy grid based games going from easiest to hardest to help us overcome prayers at JavaScript, not to mention, you're going to have a pretty cool portfolio full of stuff by the end of this tutorial, these games from easiest to hardest, our memory game. Whack a mole. Connect for Nokia 3310 Snoke. Space Invaders Frogger and Tetris. I think my favorite game is definitely Tetris. What I would suggest is that you do each game from the easiest to the hardest, don't just jump in the middle and start with I don't know Frogger. This is because I'm going to be covering functions at the beginning, for example, query selector that we're going to use in literally every single game, but I'm not going to go into detail about it in any tutorial after the one that we cover in. So if you start us at the end, you're literally going to not know well the majority of the inbuilt functions we're going to be talking about, I'm going to be incorporating as many inbuilt JavaScript functions as I possibly can. So by the end of this course, you should be pretty confident using all of them. If you want a full list of the functions we're going to cover, please do look below, I'm going to include that in the description along with the games that we're going to cover. As always, I'm going to go with bare minimum styling, this is so that you can take the project and make it your own. So let's get going. Okay, so the first game we're gonna make is memory game. memory game is a simple grid based game in which you as a player how to flip over two cards. If the two cards match, that's one point for you. And also the cards get taken off the board, leaving with you with the remainder of the cause that you then also have to flip over. The game has finished when you flipped over all the guards. No one really knows the origin of the memory game. And trust me I've done my fair share of internet stalking to try and find out. What I can tell you is that it's been renamed flipped over made variations of Justin English alone. It's called concentration game match match, match up memory pallmann ism, or simply pass, we are going to be coding a game of memory game in order to get our heads around working with empty arrays, as well as pushing and storing things in them. Other things we're going to cover are the inbuilt JavaScript functions set attribute, get attribute, create element appendChild math random sought and working with loops, as always simple styling for you to take and make your own. So let's set up our folder to have our app js file, index HTML files style CSS file, and the route along with an images folder for all the images we are going to use. Please make sure to have the images as 100 pixel by 100 pixels squares to avoid stretching and tampering with them later. After saving your images, simply drag and drop them into your folder. I have chosen to go for six fast foods. A blank for when my card is on its front and a white PNG file to simulate the board space being empty. Now in our HTML boilerplate, we need to put a h3 tag in the body along with a span of ID result. livescore will show up in here. Next we create a div with a class name of grid. This is where our game grid will be created. Don't forget to link up your styles CSS file an app js file with these tags. Now flip over to your CSS file and add some styling to your grid. Because our cards are 100 pixels by 100 pixels, we will be able to make a three by four square grid. Now flip over to our app js file. All our JavaScript code will be done in this Dom event listener from now on. Let's start by making an array of cards and giving them names that we will use later. I'm going to make two of each as we need to have each card in our array to play the game. You will see here that I am simply in a In the chord, and for the image, I'm writing the relative relative path to each image. Okay, now we're going to create our gameboard. First using query selector, I'm going to pick up the element with the class name of grid from HTML, and define it as grid for our JavaScript. Now using a for loop, I'm going to loop over my card array. And for each card, I'm going to create an image element, I'm going to call this element card. For each card, I'm going to set it set as an attribute. linking it to the image and relative path image, blank. png. I'm also going to give each one a data ID and loop over each one to give them an ID that goes from zero to 11. As we have 12 cars in total in our card array, we will then add an event listener to listen out to if the cards have been clicked on and invoke a flipcard function. Have a comment this out for now, as we have not written this function quite yet. Finally, all these cards are technically image elements with different ideas we've created, we're going to put into the div with a class name of grid using append child. Now let's invoke the function and flip over to our browser. And done let's carry on. So to make our game work, we need to do two more things, check for matched and flip your card. Let's start by writing flip card as we saw in our function above, let's set a variable of card ID. And this we are simply getting the data ID attribute we created in the Create board function above. We will now make an empty array of cards chosen. Using push we will push the cards from the card array based on that card ID. So the card ideas for this will match the fifth card in our card array. Once we have located this card, we will get its name, we are going to do the same to push the card ID in a separate for now empty array. For this one, we just want the ID. Now because Flipkart is already in a function, we technically already have a card picked. This set attribute will let us add an image to that square. Based on the card ID it holds. We only want to put two cards in our card chosen array. So with this if statement, we are saying that if the cards chosen array is equal to two, we want to invoke the function for check for much. This set timeout will give us some buffer time so the whole thing doesn't happen too quickly. I want to check for a match up to exactly 500 milliseconds. Okay, now let's write the check for MATCH function. Let's pick up all the images that we created in our first function using query selector all and call them cards. Now we have two values in our cards chosen a row, as well as our card chosen ID array at this point. Let's use both values here like this and set them as const. By writing cards, chosen ID, and then zero in square brackets, I am saying I want the first value in my array, and I want to assign it to the constant option one Id do the same for the second value using the same logic but for cards chosen, so the names rather than the IDs. I'm going to check that the first item in my array deeply equals the second item in my cards chosen array. If the answer is true, I want an alert I want an alert to pop up and I want to assign both of them a white PNG for styling. I also want to make another empty array called cards one and push the two chosen cards into the array to be stored. If the cars don't match, I want to flip the card back over to play it again. So visually giving them a blank PNG and sent unlocked. Either way, if either of these two things happen, I still want to via the cards chosen array, and the cards chosen ID array arrays and start flipping again. So now, we are collecting cards one, it will be cool to convert this into a score and display this to the user via the browser. by picking out the span element with the ID result from our HTML, we can do this using text content, we can pass through exactly how many times we have stored something in our cards one array. So one point for every month. If the cards weren't deeply equal the length of our cards array divided by two, we know we have collected all the possible cards in our cards array. let other alert the user of this via the browser, like this. Now the final thing that will allow us to refresh the game with new compositions is to randomize our card array. Let's do this using sort and math random. And there you have it, your very own memory game. Again, I'm not going to turn on styling simply because otherwise we will be here for way too long. But please have a go yourself. Comment below if you have any questions. And yeah, let me know if you have any other ideas for games, I can make an audience. Thanks. So hopefully by now you have your own working game, our memory game, as well as a strong grasp of query selectors and event listeners. We are going to be using them again today to build your very own game of whack a mole. We will also be using class list add remove for each and arrow functions as this game is going to be timed with you getting 60 seconds to bash them all as many times as possible. We're also going to be introducing set interval and clear interval for this game. Whack a mole is a simple grid based game in which you as the user have to whack the mole as many times as possible in 60 seconds. Whack a mole is a game invented in 1975, where you kazoo or your mother, you clearly saw a gap in the market for bashing walls with massive mallets. And judging by the popularity of this game today, he was right. As always, we're going to do simple styling for you to take and make your own. Okay to start a project, let's first make sure that we have the right files in our folder. You can see here I already have made an index HTML file, app js file and style sheet called style CSS. As you can see, I've gone ahead and set out our HTML for the project. The first thing that we need to do is see that our HTML boilerplate, I have added a link to our CSS file right here on line six. I have also made sure to add a script tag to talk to our JavaScript file. You can see this on line 31. We also have some h two headers with IDs, one for score and one for time left. I have also gone ahead and added a div with a class name of of grid with nine divs inside each div has unique ID that we will use later as well as a general class name of square. We will be using these class names and IDs for our JavaScript file and CSS file to communicate with our HTML page. So now let's flip over to our CSS file in order to render our dams into a visual grid in the browser. Using dot square I am looking for class names called square and our HTML file. This is what dot essentially means class name and giving them each 200 pixel width and height as well as some additional styling. Feel free to go wild with your own colors, border styles and fills. If you say the following open up your browser by right clicking the index dot HTML file. This is what you should see nine divs we just styled stacked on top of each other. Using classroom grid We will now make sure the squares are put into a grid shape. We will do this by using display flex and flex flow to make our divs stuck left and right and stuck over each other was being entered and constrained into a height and width of the overall grid. Let's go back to our browser and refresh. And this is now what we see. For the mole classname and going to show you how to add an image to a div. Type the following like so. Then drop the JPEG file into your project. You will see on the left as mole dot jpg, then simply typed the path name into your background image style. Now let's see if that has worked by hard coding it into our HTML. And it has perfect right now on to writing our JavaScript and making our game work. We will start by selecting all the devs with class name of square from our HTML file and calling them square for our JavaScript file and our future using it. We will do the same for divs with the class name of model. And also for time left using query selector to find the ID of time left, shown here as an ID by using the hash as opposed to a dot for class names. Again, we do the same for school and use a let as this will change as we progress in the game. To start the game, let's set result zero and get to writing our first function of randomly selecting a square on our grid. We will start as with all grid based games by removing any class from DOS, this is done so there are no seemingly left behind divs with styling on our board using an arrow function, and for each, we remove the class name and more from all of our squares in the grid. Now we define a random position on our grid by using math random. And then we multiply by the number of squares we have in the grid. We use math floor to round down to the nearest integer so that the random position is always under or equivalent to nine. Once the random position is defined, we add the class of mall to it so that the mall appears in the grid. Next, we pass on the random positions ID to our hit position. We need this to use later in our code. So for example, if the ID of the position from our HTML is four, this will now be our hip position. We will now use an arrow function for each and an event listener to write if statements. The eventlistener mouse up refers to when we hit our mouse on an element. On this occasion, it means if we hit with our mouse, and the ID of that div equals our hip position, we win. And we add one point to our result, we then use text content to visually display that result in the browser. Now, we need to write a function that will move the mole every so often, we can set this time interval ourselves. We start by setting the timer ID as null, then using set interval to make the function random square run every 1000 milliseconds, you can obviously change this to whatever time you want. Let's invoke this function like so and see in an action. Great now let's remove that function to an invoke it and get to realizing how much time we have left in the game for that extra suspense. That scroll to the top and that current time be the inner context of the header two with ID time left. Now let's write our countdown function. This function will make our current time go down by one incrementally show this new time in the browser. And if the current time which is zero, we have a game over. we clear the time interval and setting an alert to let the user know that the game is over and that final result. Finally, using set interval we pass through the countdown function, make it evoke every one second and there you have it. Blackmore. Hi and welcome back to the JavaScript games course. In this tutorial, we're going to be coding Connect Four As well as focusing on onClick events for this game, if you haven't watched the two previous tutorials before this, I strongly recommend you do, we're going to be using things like query selectors and event listeners that we did cover in the previous ones. So if you're not comfortable with them, please watch those videos before attempting this one. As always, we're gonna do simple styling. This is so that you can get the project make your own. So I'm literally gonna be focusing maybe like max five minutes on the stylesheet Connect for is a simple grid based game in which you as the user have to drop a chip down into one of the columns to take your place. After you take in your place, the second player will take their turn, please bear in mind for this game, obviously, we can't really have gravity. So we're just going to use the bottom grid as the you know, bottom grid. Meaning that if you want to put a chip in a chip in a space that doesn't have a chip below it, you're not going to be able to write so the point of the game is to get four in a row. This is either in a column or row but also diagonally. The first place to do this wins. Okay, so let's get going. Okay, so first, let's set up our project with the correct files in our folder. We will have the app j s for our JavaScript index HTML for our HTML code, and style CSS for our CSS styling. In your HTML file, add a div with a class name of grid with enough divs inside to make a seven by six grid. So 42 divs. We also need to add seven more depth to the bottom with the class name token. This will be the bottom of our grid. Add a span with the ID current players so we can display the current player to the user like this. And also one final result so we can see who wins in the event of a win. Always make sure to link your cell sheet and JavaScript file in the HTML file. Okay, now flip over to your CSS file and add the following styling to make our list of divs and the div with a class name grid lockback and actual grid, we use Flexbox to wrap the divs into a grid square. We will also be parsing our player one and player two colors here like this. Okay, now flip over to your JavaScript file and add a DOM event listener like this. All your JavaScript code will be done in the event listener from now on. Okay, so the first thing we are going to do is write a function that will listen out for every time we click a square and our grid. We will start off by writing a loop to loop over each square, then a function to add an onClick to it. Now let's write some if statements. So what we are writing here is that if you click on a div and the div below it or seven squares down, has a class name of taken you are allowed to click on this stuff and claim it as you will take and go. Right so if you can go and if you are playing one at a class name have taken to that square. Also add a class name of player one to that square, so we can visually see where you have chosen to place your go in the browser. I'll do the same for player two. If you aren't in a square that is one out from one with the class. taken an alert saying you can't go here will pop up. Now let's open our browser to see if this works. Okay, great. Now let's check the board for win or lose with a chalkboard function. First, we need to declare what a winning combination actually is on our board. I actually found these somewhere online. So I have cheated, and I'm passing this on to you. So you don't have to figure this out ourselves. Otherwise, we'll be here all day. Okay, now again, using a loop, we are essentially plugging in values to the squares on our grid. This is so we can check if these squares are in a winning array and also contain the class name at playout. One. If the answer is true, we want to display player one wins in the inner HTML the span with ID result on our HTML page. Okay, do the same for player two like this. Finally, on each click of the squares in our grid, we want to add an event listener and pass through the check board function. This means the function will run every time you press on a square in the grid. Okay, there you have it. Thanks for listening. If you have any questions, please do let me know. Welcome back to the JavaScript games course. Today we're going to be teaching you how to make your own Nakia 3310 snake, for those of you have never owned a Nokia 3310 snake is a simple grid base game in which the snake or array is going to be tasting a little apple on the screen. So you're going to be controlling the snake it's been going like this, it's going to be on a timer, obviously, it's going to keep going. So we were just going to control it. And once it gets the apple, it's going to give you points but it's also going to speed up in time. So that's going to be quite cool to build, we're going to be using a lot of set intervals and clear intervals as well for this game. We are now on game four out of seven of this course. In this game, you're going to be learning how to use key codes, which are really cool. I'll talk about them later, as well as pop and shift, push and going over functions that we've previously learned in the four previous games. So key codes are pretty awesome. A key code is literally the code associated with the ones on your keyboard. So for example, if I want to say start the game by pressing, I don't know the G on your keyboard, we can do that. That's pretty cool. I'm going to be going into that and a lot more detail in the game along with switch cases. So if you're interested in that, please stop my video and let's get going to start a project. Let's first make sure we have the right files in our folder. You can see here I've already made an index, HTML file, app js file and style sheet called style CSS. The first thing we need to do is set our HTML template making sure to add the following script tag to talk to our JavaScript file. Next, we need to add a link to our CSS file like so. I'm going to go ahead and add a button tag with a class name of start to our HTML file. This class name will allow us to pick out this specific element later in our JavaScript file. I am now going to add a div with a class name score to it for the same purpose. Once we have written our JavaScript code, the score of our game will appear between the two span tags here and overwrite the zero I am writing now. Now let's make all good. Now to make the grid we need to decide how many squares a snake game should have. This is totally up to you, you can make the game as big small or awkward as you want. For the sake of ease, I'm going to make my grid 10 by 10 squares, meaning I need a total of 100 squats. Now let's make our grid actually look like a grid by flipping over to our stylesheet and adding some stuff. Using dot grid, I am looking for a class name called grid. This is what the dot essentially means class name, engaging make my grid 200 pixels by 200 pixels and make sure that does fit into this grid by using display flex and flex wrap. Now we're going to give each of the divs and our grid a height and width of 20 pixels. This is simply so that they fit into our 200 by 200 pixel grid, making sure there's only 10 of them each way. Now let's add a snake class and make it blue. flip back to the HTML file and hard coded in here just so we can see how that will look. And voila, any div with a class there was a snake now we'll be blue. Let's do the same for Apple. Now let's get to writing some JavaScript and making our game work. Add an event listener like so from now on all our code will be in this event listener. Now we need to pick up the elements from our html5 by class name as I mentioned before, for this we will use document query selectors. What we are telling the file to do is select all the devs in a div with class name of grid and call them squares for the file. We will also select the span element and call it the score display and select the button with a class name of start. Note that dot here it's for class name and call it start button. Now we just need to set the width. So our JavaScript file knows as we have not told it yet our current index so the first div in our grid, it is important to know that by writing zero, I mean it's the first I guess item what element is just that the computer starts counting when there's a race involved. So now let's set up our apple index at zero for the time being. Now let's draw our snake as you can imagine, we will need to differentiate between what is the head and what is the tail. From now on all devs have a value of two will be the head and all devs with a value of zero will be the tail. For body parts we will use ones on this array will now be our snake direction we're going to stay as one meaning that the snake should always go wander down the array. And then we used to stick the score speed interval time and it's okay now let's make a snake move across the board using key codes. Each key on your keyboard has a key code assigned to it. We will write a function called control and pass to e4 event in order to make a snake move up and down, left and right. Depending on what key you press on your keyboard. We will first make sure how to remove all class lists of snake between each move. This will take a split second but will prevent our snake from appearing to be left behind. Now we will write an if statement stating if we press the right arrow button on our keyboard, the snake will go right or in other words downward space in our grid array. Now let's do the same for the up arrow making sure our snake goes into the 10th position back from its current position in the array. As this is what we set our width to the result of this snake would appear to be up one whole row Now let's finish off by writing the same for the left arrow button and the down arrow one. Finally, let's add an event listener every time a key is pressed to execute the function control now we have assigned key codes to our snake movements. Let's write a function to start the game and make our snake move at a certain speed around our grid. Using an arrow function, we are going to make sure that each index of the current snake row is taken into consideration. We do this using for each then we remove all class names of snake from the devs. The current snake array is currently in at the start of this function, there is no class name of snake in any other days in our current snake. We also have the apple class like sir from the dev that is the apple index. What I am doing here is essentially resetting everything the interval the score everything. Once this reset we are going to randomly generate an apple you will write this function now we write what we want to happen when we start the game. So direction is equal one for the snake to go right, we set an interval the time we define our snake, give it a start position and our class name to the devs the snake correct is currently in. Now we need to pass through the interval of time and a function we will write called move outcomes. This function will deal with any and all outcomes for our decisions to move the snake, it will deal with collisions when's school setting. Let's plant what the snake needs to do by writing out like so. To deal with a snake hitting a water or itself we are going to write an if statement in our move outcomes function. First of all, it's important to see that we are dealing with the snake's head at the moment. And we are using width to figure out where on the grid the snake head is. We need to do this to figure out when the snake head is in any of the squares at the bottom of our grid or indicated by the two parallel lines or on the right side of our grid and so on. last statement is an if statement for if the snake goes into itself. Oops we need another or here. Right so if any of the above happened, the following was returned. we clear the interval. Now we need to define what exactly is the tail. We do so right by writing this constant and using now let's remove the classroom of snake from the tail and give a direction to just the head of the snake. Let's deal with what happens when the head of the current snake gets into a square that contains a class named Apple with an if statement. Once again, we start with removing the apple class name for a clean slate, then adding a class to the newly added tail of the snake making it appear to grow longer. Again, we will add our random Apple function here when we write it to generate a new Apple once this one is gone, and add one to the score. Now let's display that new score in the HTML of our score display and clear the interval time. Finally, let's multiply the new interval time by the speed as our sphere to 0.9. This will decrease the interval of time each time this is updated. Lastly, let's reset the interval and close the if statement. Let's not forget to re add the class name of snake at the end of our move outcomes function. Right then we've been coding for a while. Let's see if this works. So far, we have written a start game function. So now let's link it to the start button on our HTML page with an event listener. So on click on the start button, we want to invoke the start game function. And it works. some reason the left arrow button is not working. And here is why we are missing an equals sign. Oops. Okay, now finally, let's address that generate random Apple function we have been talking about. So with that, we use math random to generate a random number based on the squares length. This means the apple can pop up anywhere on our grid, we use math floor to round down the number to the nearest integer to make sure the random square is below or including the 100th Square. We will use while to make sure that the Apple does not appear in any day that already has a class name snake. And that's it. Let's read the let's reorder the content out random Apple function in our code. Let's get rid of the hard coded classes in our HTML. And there we go, we now have a fully functioning game up snake. Hey, welcome back. We are currently at game five out of seven of the JavaScript games course. In this tutorial, we're going to be learning how to build Space Invaders and other JavaScript, HTML and CSS Grid based game. By building Space Invaders, we're going to be concentrating on the switch ghosts. This is going to be massive throughout the whole game. So if you're interested in learning more about the switch goes, please watch this video. Space Invaders is really simple, you're going to be a user or shooter that moves along from one side of the grid to the other in a 15 by 15 grid square. Your goal is to shoot all the little invaders. So all the little ones coming down. They're going down like this before they get to you. So technically, it is a time game. There's not too much of a countdown, but obviously the invaders moving down is a countdown in itself. This means we're going to be using a lot of set interval and clear interval to as always minimal styling for you to take and make your own. So yeah, let's get going. So as always, let's make sure to link up your style CSS file with a link tag and app js file with a script tag in your HTML file. Let's start off by adding an h3 tag where we can display our score. Let's add a span with an ID of result here so we can display the score as well as play our game. Next, let's add a div with a class name of grid. In it, we will put 11 by 11. Actually, let's make it bigger. Let's make a 15 by 15 squares for our game. So a total of 225 days that we will start as squares in our style CSS. Let's flip over to that. Now. Let's apply some styling to our grid to make it look like an actual grid, as well as the grid divs inside of it. We are using a width and a height of 300 pixels here, meaning that the height and the width of our squares need to be 20 pixels in order to make sure 15 squares fit on a line before being wrapped over themselves. To make a second row. We might as well assign a color to future classes, we will use our shooter invader boom for when they shoot hits an invader and the laser. Let's open the HTML file path in our browser to check that looks fine. Okay, great. Now let's go to our app js file. We start off by adding a DOM event listener. All our JavaScript code will go inside this event listener from now on. Now let's pick out the classes and IDs we have defined using query selectors. As there's more than one element that is considered a div in inside the element with the class own grid, we need to make sure to use query selector all for the squares. Also note how we use the hash when we pick out our ID names, rather than the dot for class name. Now let's let our JavaScript know that we want the width of the grid to be 15 that we want the shooter to start at index 202 in our squares array, and our invaded start at index zero or collectively invaders. I'll explain that later. We are going to leave an empty array for the invaders we have shot down. Let's resolve zero for now. And let the direction we want to go in be a one. Again, I will explain that later. And finally, let's leave the invader ID as null for now. Now let's define our alien invaders as how we would want them to appear in our squares array. So by saying these are the indexes we want our alien invader to be in, we can easily see this on our grid by adding a color class name to them. So let's do this using for each like this. So in the array alien invaders, for each item in the array, we will choose to call invader I will pass this through our squares and any current index value there might be so in this case zero. And then I want to add a class list I'm invada to that square. We set this up purple as purple in our style sheet. So let's see if that works. Let's flip over to a browser puppet it works. Now the best part of this is that we can control all the positions of all the invaders in our alien array. Thanks to the current invader index, try this yourself by changing the value from zero to five in your file. Okay, let's do the same for shooter flip over to our browser to check and let's carry on. Now we need to make our shooter move across the grid but not go up or down. For this we're gonna look at key codes which are the codes given to the keys on your keyboard. Let's write a function called move shooter and pass through E for event. Let's start off by clearing the board of the shooter by removing the class name on the shooters current location index 202 as we sit above now using switch cases we will make a case for key code that is seven or the left arrow on your keyboard and that you nine to the right. So the case that is seven if the shooters current index is divisible by the width so 15 and leaves a remain leader remainder is allowed to move left. So for example if you're going to square with index 30, you will know you're on the very left side of the grid as that is divisible by 15 and it's not good give you any remainders. As you have no remainder you cannot move left anymore. That's what we've written. Now for case 39 if the shooters current index is in a Square index where the number is divisible by the width. So 15 and the number is less than 14, then you are allowed to move right. Then once it is done at a class of shooter to the new location of the shooter on the grid Finally, let's add an event listener for the key down action that triggers the move shooter function each time you put one of the keys we discussed down on your keyboard. Let's check out the browser to see if this is what. Okay, great. Now let's move on. Let's move the alien invaders from one side of the grid to the other moving down a row each time, we will now write a function called move invaders that we'll put, we'll put on a time loop. First, as above, let's define our left edge and our right edge using similar logic, but the elite for the alien invaders array. This is trickier as many as apply the logic to the first item in the array for checking if we on the left edge and apply the logic the last items the last alien and alien invader array to check if we were at the right edge. If we don't do this, aliens will just carry on going through and what we see as the right edge and look really weird. So make sure to do that. Okay, so if we are on the left edge and our direction is minus one, so I use minus one here because of the alien was to go back one index in a row, it will essentially appear to be going left. So if both these things are true, or we are at the right edge and the direction is currently plus one, we want to get the direction and value of 15. So it will move down to whole row on average. If the directions already 15 we carry on with the same logic as above. So if you're the left or change direction be positive. Else carry on going left we're keeping the direction as minus one. Now let's move over the alien invader array to move and the invaders. loop over again to add a new direction to all the items in the alien array. And loop over again to other class of invader to the new location of all the aliens in the array or items. Now let's write some logic that decides that the game is over. If the square and our current shooter is in has a class name that contains invader and shooter, the game is over. This is because the alien invader has got to the you know tutor and it's gone to the same square. we display the game over in our browser using text content and add a boom class just for fun. We also clear the time interval for the game like this. We also want to make sure that if any of the aliens Mr. shooter, but reached the end of the grid, the game is over to we do so by declaring that if any aliens are in the last 15 squares of the grid, the game is over. Now we need to invoke this function every 500 milliseconds like this. Let's see how that looks now. Okay, great. Finally we need to write a function that allows us to shoot at the alien to try when and gain points. We will do so by passing through an event or E through our function shoot. let's declare laser ideas no and add a new current index for the laser. The current index of the laser will always be the current location of the shooter to start with. If we write this is what's going to go to the shooter pool. These two declarations needs to be an only the scope of this function for this to work by the way, make sure that now we will write a function in here called the move laser. very similarly we will move the laser from its current starting position and square. This time removing the whole width for it to appear to be moving up awkward. So minus 50. MRI other laser close later. If the current square the laser is incandescent and VEDA we do three things. Remove the laser, move the invader and add a boom for fun We only want the moon to appear for a very short time, so we can use a timeout for this and make sure to remove the boom after 250 milliseconds. We then clear the time interval for this light set. Let's make an array of aliens we are taken down like this. By writing this we are pushing a new item to our alien invaders take down empty array we declared at the beginning of this video using push. We then add one to the result and display this in our browser using text content. Lastly, if the laser is in the very first 15 squares, we want to clear this interval and remove the laser class from the grid. We want all of this to happen when we press the spacebar. using logic we learn above we add an event listener on pass through an event or E for the keyCode 32 which is a spacebar on your keyboard. We then pass through the middle is a function on 100 millisecond interval like this. Now that we are counting how many aliens we have taken down, we need to add some code above. Using bang we are writing here that if the alien takes alien take down array does not include the space you can add an invader class this means that we will not be reacting invaders once they are shot. And finally, we need to write some logic to declare a win. This is simple if the length of our alien invaders taken down array is equal to the length of our alien invaders we went this is because we have shot all the images Okay, now let's flip over to play. Okay, I can see it doesn't like my event. Now. Let's change this to switch case because I know that works. Even though there's only one option in this which case I mean it's gonna work so I'm just going to use it as something else isn't working as the aliens aren't disappearing reappearing. Okay, we forgot to add a classless oops. And there we have it your very own space invader game. If you have any other questions about the game, please let me know below. And I'll try to get back to you. Thank you. Hi, everyone, we are now at game six out of seven of our JavaScript games course. We only have one more grid based game to make after this until you have at seven fully functioning JavaScript games for your portfolio. In this tutorial, we're going to make Frogger in which we're going to be looking at every single function that you have learnt before in the previous five games. So yeah, if you haven't watched the previous videos definitely do that now before watching this one. But we are going to be taking them that extra level so making them do more complicated things. As always minimal styling, I've gone max five minutes doing the styling on this. So Frogger is a simple Bass game in which you as the user and frog style at the bottom of the grid and have two obstacles to pass to get your home, which is at the top of the grid based game. The first obstacle is a road in which little cars are going from one side of the other new race car to avoid them like this. Once you avoid that, that is the second hurdle of the river. This is basically flipped on its head. So instead of avoiding things in it, you have to jump on things in it. So you're gonna have to jump on the logs in the river. In order to get to the home. What's cool about this is actually one of the frog is on the log is gonna have to move with the log until it can jump off. So that's gonna be really fun to build. I'm really excited to walk you through this. So yeah, let's get going. So first, let's set up a project with the correct files in our folder. We have the app j s for our JavaScript, index, HTML for our HTML code, and style CSS for our CSS styling. Let's start with the HTML by adding some HTML boilerplate, we will add a title of Fraga for our project that will not visually render in the browser, but show up on the tab. We next need to link our stylesheet using a link tag like this to the correct file using an href and link our JavaScript file again using source and the correct file name of app j s where we saw our JavaScript code. Now we have that let's do some basic visualization of the grid and add a start and pause button for the game. And an h3 tag let us know how much time we have left or whether we have won or lost. Let's add the Start button and h3 tags to give them unique IDs instead of class names. I am also going to hard code the time left to display was 20. Okay, now let's flip over to our CSS file. Add the following styling to make our list of divs and the HTML look like an actual grid. What we are doing here is making the divs wrapper rechab using Flexbox. Each div inside a div with a class name grid, we are assigning a height and width of 20 pixels because under an 80 divided by nine is 20. And we want a nine by nine grid. So now right click your index HTML file to open it in the browser. And this is what we will see. Now let's assign colors to our ending block, starting block and our frog flip back to your HTML file and hard code these in to the fifth div down on the fifth from the bottom. This is what it should now look like in your browser. Okay, now let's add some functionality to the frog that we have hard coded, not hard coded, but we'll add to our HTML using JavaScript. Flip over to your app js file and add an event listener like this. Okay, all our code will be done in this event listener. Now let's pick our elements from my HTML file using constants and query selectors like this. Know how we use query selector all for the divs inside a div with the class name grid. This is because we want all the divs in there and also see how we use dot for class names and hashes for picking out ideas. So now if I want to show the frog my grid, I can simply add the class name of frog to a square and the grid of index 76 using JavaScript like this. Now flip over to my browser, hit refresh, and okay now add a timer ID and leave it as that for now. This is here for our countdown that we will build later. The first we are going to do is make a frog move when you press on your keyboard. For this, you need to know the key codes to your keyboard up down left and right buttons, you can easily Google or the key codes to your entire keyboard. For now, I'm just going to tell you the key codes for the ones we want. We are going to write the function and pass it through an E or an event we're going to remove the frog from whatever current squared is in and then using event and keycodes decide which way the frog is going to go using switch cases. So in this case, if key 37 is pressed, so are left on your keyboard. And if the current index is divisible by the width with a remainder, we're the frog left one space. Do you see the key 38 so the up arrow moving the frog a whole width back visually displaying as if it was going up one square, then for keys 39 or our right and key 40 are down. Then we draw the frog on each key press we also want to check if the frog has done anything that would result in winning or losing let's put in these functions that we will write in a bit. So if you try and move your probe now these functions will not work as they did not observe some will break your code so just bear that in mind. Okay, now let's get to rendering the first obstacle the frog needs to cross so that will be the road with cause that needs to be avoided. Then the second obstacle which is a river with some logs, frogs needs to jump on to cross you will see here and my finished game that the cars moving left are actually just on a loop being rendered and three squares 123 and then repeat. Same for the card game right. And even the logs are on this loop just a loop of five squares random instead goes through HTML and other following class names your days making sure to start from the 19th down or for JavaScript sake index 18. And the same for the road. So diff 46, but index 45 And now flip over is your CSS file and add some colors so we know what is road call river, or loc. Now Save and refresh the browser. And there we go, we can see a road here river, some logs and some cars. Now back in our JavaScript file, let's write a function that will make all the divs with a class name of car left, go left, and the divs of class name car right, go right. First, let's pick out these debts from HTML and add that to the top of our project. We might as well add the others to now let's write a function called auto move cars in this function where we use arrow functions that will allow us to give a name to individual devs from all our devs called cause left and passing through a function, we will do this using for each so for each Doom that has a class name, cause left pass through a function called move car left, that will make the day go left and the same for cars right. Okay, now let's write that move car left function that technically is just going to rerender three days every second, we use a switch for this and pass through the car left we got from the function automotive costs. Now for the common good, right on the same logic as above. Now let's do the exact same for the logs. One loop three, rendering five devs every second Okay, now let's write all this function. So if the time runs out, or is equal to zero, or two using these two parallel lines means or, or the square the frog is currently and contains a C one class name to call, or l five class name. So blue and engaging river, or l four class name, which again is a river it loses. Again, we display the reducing message, remove the frog, clear the timer from the countdown and stop the frog movie. Now the final functionality we need to give our game is make sure that the frog is on the log. So when it's on the log and moves with the log, so in the river, or the frog is in the squares index of bigger than or equal to 27, and smaller to 35. Move the frog left, it doesn't matter that we actually including the river does in here as well as the frog automatically loses if it goes in there. So don't worry about that. That's fine. Okay. Do the same. The Right. Okay, now we need to invoke all of our functions to happen every second, every second year, we need to move a car or log, make sure to move the frog if it's on a log, and evoke lose if it's standing in a square that a car is going into it let's call this function move piece. Note we need to pass loose in there. And in our moving frog function. If we don't have it here, cause we'll be able to pass through our frog willy nilly. You also use our logic to make our current time go down by one every second and update the time left div in our HTML to show this to our user. Finally, we need to pass through the movies function into a countdown that goes down every second. We do this by adding an event listener to a start button. We will also be making the button double up was a pause button which is quite cool. So on click, we do an if else statement. By using set interval like this, we are making sure the move pieces function is invoked every second until the timer ID equals zero. We also want to make sure that the frog can only move when the game has started. So we add in our event listener to start the move frog move frog function we were above here. As you can see, something's not working. Let's have a look. That's because I need to use document query selector all because we're selecting all the divs let's change that here and here. Okay, we need to change this. And there you have it your very own Frogger game. How'd you like my tutorial? Feel free to comment if you'd like some more information, or if I haven't explained something very well. Please do subscribe for more videos are really into making grid based games at the moment and pure JavaScript. So if you can think of any cool ones, let me know and I'll try have a go at it. Thank you. Hi, everyone, and welcome to the last game of the JavaScript games course. This is actually my favorite game. So we're going to be building Tetris. It's my favorite. It's also the hardest, which is why I obviously left it to last and we're going to be using every single thing that we learnt before, as well as learning a few new things. So a few new things that we're going to be learning are get elements by class name, math floor, some splice concat, as well as adding background images, via JavaScript using that style background. For anyone joining us now, I would strongly recommend going all the way back to the beginning. And starting from the first game as we're going to be using functions that I'm not going to go into detail. And again, I feel like I've already explained them and it wouldn't be fair on everyone else who's watched from the beginning. So things like query selectors, event listeners are functions. We're not going to be going over that again. So yeah, definitely go back. Tetris is a 1984 video game invented by Soviet engineer Alexey pay it off. It is a grid based game that has seven shapes, or technically tetromino is that you need to navigate all the way down the grid in order to fill up at the bottom. When you fill up exactly a row, this will disappear, but also give you points. The cool part about this is that the shapes are going to rotate. So we're going to learn how to rotate these shapes in JavaScript, as well as move them down from left and right and so on. The other cool thing that we're going to do is a display the shape that's about to come down. So I don't know if you've seen Tetris. But usually there's a grid. But there's also like a little side thing that will display the shape that's literally about to come down. After you finish having your go. There is a reason why I saved this game to last is pretty hard. So if you're feeling brave, let's get going on this project, we are going to use a HTML file, CSS file and a JavaScript file. Make sure to set up your files accordingly. Next, we need to add the following script tag into the head of your HTML file. I'll point you to your JavaScript file and your app folder file through the source attribute. Next, add an event listener to your JavaScript file like so. First of all, to make the game we need to decide on our grid size. For this video, I have chosen 10 squares width by 20 squares height. So from now on, consider each square to be one div on your HTML file. This gives a total of 200 dibs on our HTML file. If you flip over to your HTML file, please add a total of 200 dose, please put these divs in the div itself and give it a class name of grid. For the purpose of teaching. I'm going to give each of these divs a color of yellow and my CSS file and a height and width. So you can see them as squares like so. As you can see, because divs are programmed to be in block. This is what happens in our browser. By setting a width to our grid, we can stack the digit from left to right and rows of 10. Obviously, the way that we did it 20 pixels and the width of the grid is 200 pixels. We will get tenders in a row. So feel free to mess around about as you want. I've numbered them for the sake of the tutorial like this. Let's have a look at our grid now. Next, we need to use the query selector to add the following into the top of our js file. js file now that is what we mean by grid. We're picking up the div with a class name of grid from what HTML page. Now that we have our grid set up, let's focus on the total Nino's themselves. In Tetris, there are five to caminos Tetris in general as a pretty cool story. So check it out, if you can write their official names are the L tetromino, Zed tetrominoes to tetromino, o tetromino, and ita terino. As you can see here, I've put them in four by four grid, so conduct for their rotational axes. There's so my drawer and we are now able to draw the tetromino as as constants with their four rotations. Using the concept of width a set above we have set the width is 10. So let's do the starting position is zero, and start drawing attention Muniz, out on the grid into the forward stations. So let's set this out of the top of your j s file. Now that we have our five touch windows with the four rotations, let's put them in an array and call them the tetromino O's. As you know, Tetris determiners are selected at random. We will now need to write something that will randomly select a tetromino from our tetrominoes Right, my floor was simply round down the integer that is returned in this case making sure that it was one below the tetrominoes array length. Once we have defined random, we need to define the current rotation of the randomly selected tetromino. Let's define this as current. So now we tackling have defined what one of the randomly selected determiners current rotation is. Let's move on to the next part, moving current down one div space with every second. This let's pick the top center of the board as a starting point for the current are to drop down from, let's call this current position. We are now going to visually move the tetromino down by drawing it and unrolling it in depth. This we are going to assign a class name to the details, we want to visually display a tetromino shape. And so let's put this at the top of our file. Again, using query selector all this time, now go to your CSS file. Now the following from now on all divs with a class name block will be blue. Now let's write the drawer function to give all the squares in your current dictionary know the class name block. I've also written some code to give you surgery now randomly select a color from an array. You can choose as you want, but we're not going to do it. Now because it's not really necessary, we have to work again head over to my GitHub if you want to check that out. Right, so now that we wrote the draw function, let's write the unroll function. So this will essentially get rid of the class name block from the dues and what we define this current. As you can see, we are using for each which meaning that each of the squares or dues and our current tetromino will have the class name of block removed from them. Like so. But now that we've done that, we need to write two more functions. Actually, let's get the move down function out the way fast. So just to speed up moving down. We will do this like so it simply adds the width to visually display the shape moving down. I added the freeze function here. I'm having it so that you know it's necessary to put this in at the move down function to stop the current tetromino when it reaches the end of the grid, we will write this function towards the end of the tutorial. If you want to invoke the move down function earlier than this, please take out the freeze function. Okay, now I'm going to write the move write function. A lot is going on here, I'm going to write a reminder that we need the current tetromino to move left if it's the right edge of the grid, we do not want the tetromino crossing over into the other side of our grid. We also don't want it to go through other frozen pieces. Okay, so function move right goes like this. First we unroll the space, then we define what is the right edge and what happens to the current tetromino when is it Next we write what happens when the shape is not in the right edge I freeze to move right but adding one to the current position. Now finally, if any of the squares and our current tetromino go into a div containing block two, we also want it to move left so appearing as if the shape hasn't moved at all. This block two is what I have defined as a frozen shape. Finally we redraw the tetromino now go to your CSS file and add a block to all offers and shapes will now appear as purple. Let's do the same moving on which means left using the same logic as above. You will notice I use modular here. This is saying that if our shape as a square and dib 10 to 2030 and so on, it will it is divisible by our set width and is a range of zero. Remember that we count the first item on a range zero to 10 is actually to 11 in our physically drawn divs in our age. Hello. Alright, so once we've written those, our final function is to rotate the tetromino. This is actually us just skipping to the next rotation in the current rotation array of each tetromino. So again, it's a visual trick making it look like it's rotated. We like this simply like so. Okay, so now we've written the functions for our group down, move left and move right. and rotate when you assign keys to them and add an event listener. Do this at the top of your js file. The E here means event and user pass it through the functions like so. Okay, so now we can move the tetromino around on the board or rotate it great. We now need to decide what happens if the tetromino class name block hits the bottom of the board or frozen tetromino of class name block too fast. Let's decide that the bottom of the board is defined as anything with div class name block through right so we're going to add another block class name. Go back to your CSS file unlike before, add the following. Now we're going to HTML file and hardcore block three as a class named into the last tenant dupes. You should see this show up in your balls It looks so great. Okay. Now as everyone knows, in Tetris, you can actually see the upcoming section winners in your game. Let's quickly create this feature we're writing a function called display shape, and adding some code to our HTML so you can see what's happening. I'm going to use a lot of logic we've used before to make the small grid a four by four grid to display our display squares, even creating a new small tetromino array. Okay, now we can see our display grid above our main grid in the browser. Again, we need our JavaScript to know what we mean when I said using the constant display squares, so we need to add this query selector here. Now using the same logic, let's write how we are going to see the previous shapes or terminos in our display squares. When you set a new width for the small grid, also a new index, let's call this display index. Now, just like before, we are going to write out our five to caminos. However, this time, we do not need all four rotations, we are simply displaying the tetromino. So for this we only need one iteration of each tetromino in an array. Let's call this constant small caminos Now let's write the function display shape. Again, you might be familiar with how I write this by now. We will also be selecting the small tech community at random. Let's put next random at zero up here. So what is happening is each time the display shaped function is invoked, we are removing any classes from devs fast. Selecting the next one knows what action you know, then drawing it out onto our grid. Let's see if it works by invoking function here. Oops, I made a mistake. This should be crew so it's all Yes, with a page refresh there is a small tetromino on our display display grid. Okay, now let's get rid of that and carry on. Now let's go back to the freeze function that I mentioned previously, in the move down function, a lot will be happening in the freeze function, we need to freeze the tetromino if any or some of its squares and with a square containing block three, so the bottom of our grid essentially, or if it is the if the squares enter a div with the class name block two, so frozen squares. If any of the two above happen, we need to turn all the squares in the community block two squares. After this happens, we need to make sure the next random tetromino from the disclosures becomes our next current. Finally, we need to draw the current tetromino by invoking the draw function, and then display the next tetromino. In the display grid. We're invoking the display shape function. Next, when it's for all these things together, and create a way for our user to start the game. Therefore invoking the draw function and making sure the game continues to move the tetromino is every one second as we do This by creating a start button in HTML and adding an event listener like so. For now, set timer ID at now, we will need this to restart the game. Again, here, we need to display a random tetromino from our small little mini tetromino. All right, like so, and invoke the display shape function we were earlier. So now go into your HTML and add a button. And now the following to do is, you will now see in your browser that upon pressing start the drawer function and the display function will be invoked, as well as the time. Oops, you can see the shapes are falling through the bottom floor. This is because there's no freeze function, and I'll move down function. I moved it as I mentioned earlier in the tutorial, it would have not let me move left right up down on the key codes if that was still in there because we didn't like the function. So if you got rid of the freeze function from our move down function, as I mentioned, please do put it back in now. If this is not here, then the shift will simply fall through the bottom of the grid. Okay, now that should work. Now get your HTML page so we can visually show a score and how many lines we have cleared in our browser. I'm going to do this with h1 tags. So as you can see, here, we're using class names for a js file so we can then use the query selector. To make our js file an HTML file. Let's add the following to the top of JavaScript file school. We are now set to write the game over function in our JavaScript file. I'm going to write it like so. Hopefully by now you're comfortable with how I am using block two and block three in my functions. It's just the same here. Make sure to clear the time where I do so that note attorneys carry on falling. Again, please add this function into office function. And finally we can write our add school function. This function will add 10 to our current score each time is executed Let's start by defining a constant row like this. Next we need to use every to make sure that if every square and I'll define row contains block at your frozen tetromino, we add a score of 10, unlined to one of our and now we want to disclose in our browser. We can do this using an HTML like sir. Finally, we need to get rid of the row just like in Tetris. Once we have added the score on the line, we will do so using remove. Now to move the river down one, we will use splice splice will cut out the current index up plus our defined width of 10. So in other words, the whole world now that's done we will need to use append child to add a new row to the top of our grid visually appearing as if nothing got removed or added in the first place. And there you have it. My game of Tetris, as mentioned, it's my first video.
Info
Channel: freeCodeCamp.org
Views: 560,691
Rating: undefined out of 5
Keywords:
Id: lhNdUVh3qCc
Channel Id: undefined
Length: 109min 10sec (6550 seconds)
Published: Wed Apr 08 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.