Code Tetris: JavaScript Tutorial for Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi and welcome to my JavaScript tutorial in which I will teach you how to code in JavaScript by building your very own basic game of Tetris I always find that learning is easy by doing so if you're the same this tutorial is definitely for you and here you'll have a pretty neat JavaScript game by the end of it this tutorial is for super beginners and we will be going through the fundamentals of JavaScript as well as some import functions that are gonna help us build our Tetris game if you have never touch code before this is a pretty good place to start we will be going through some CSS and HTML as well but just the basics as you know this is a JavaScript tutorial if you do have some prior knowledge of HTML and CSS please do not skip the first few lessons we need them in order to set up our game feel free to watch them on double-speed if you prefer tetris is a simple grid based game in which you as a user had to navigate 5 shapes or tetriminos down to the bottom of your bridge the aim of the game is to get the highest score by filling up rows when your grid in order for them to disappear and for you to gain points you as the user can rotate your shapes and you also have insider knowledge by knowing which shape is coming up next thanks to a grid to the side of your grid in this game we are not gonna have levels we are simply going to do a basic version of the game basic functionality and basic styling this is so you can take it and make it fully your own I would love to see all your finished projects how you have made them your own in terms of styling or leveling up so please do share them with me please do get in touch if you get stuck at any point in this tutorial I am always more than happy to help again please do use my social links below so yeah let's get going in this walkthrough I'm gonna show you my preferred code editor as well as the bonus of how to set it up so that it works for you like a sort of spell checker if you will it will check your code for mistakes and prompt you to change things in order for it to work I am also going to show you what a command tour is and how to use it to access files and folders on your computer as well as speak to them and download things from it okay so let's get going first off start by downloading a code editor I'm going to use Atem if you go to item to i/o and download the program that will be the tool you use to write code in your project now copy it into your Applications folder and add it to your dog once there has been downloaded you will use the command line system to create a folder to store your project if you have a Mac simply search for terminal in your Launchpad if you're on a PC you need to search for your command prompt tool now open up your terminal and using LS you can list all the directories now using CD to enter a directory we navigate to the desktop it is on the desktop that we're going to create our project called basic Tetris so using a command called mukhtar we're going to make a directory called basic Tetris okay great we now have a folder to store all our code files in it to go into this folder again we use CD let's use the command CD to go into this project if you ever want to get out of this project we use CD with two dots like this but we don't so let's go back into it once in this folder we need to create files go in it we do so using a command called touch-touch we'll create files we need to create an HTML file CSS file for our styling and a javascript file to hold our JavaScript I'm going to choose to call them index.html style.css and app.js okay perfect now using assam dot as we are using the assam code editor we will prompt the project to open in our item code editor and there we go we are now set up to start writing some code now i'm going to show you some useful settings on item that will make your life a whole lot simpler Atem allows us to add packages there are literary loads and loads of packages out there that you can pick and choose so I'm simply gonna go through ones that I find useful for my projects open Atem and click on the item menu then install shell commands click on the drop-down and preferences in preferences in the editor panel make the following changes show in that guide check shirt Invisibles check and tab type soft now let's go over to our terminal and type the following code what we are essentially doing here is downloading packages for Assam to use via the command line tool you once these are all downloaded let's quit awesome now let's reopen it to see the packages that we installed and go through the more a little bit more one by one in the navigation find packages and click on the drop down you will see here all the packages we installed use the command line and APM command we have Auto indent Auto a dent will Auto and Daniel code correctly in your files this is good for code readability and considered best practice you awesome tangey ass is a package that adds support for es five-year six-year 7 es 8 nodejs and more this means that it will let us use features of all of them in your code editor for example an arrow function which you will definitely come across is something that is a feature of JavaScript ES 6 and above we are also going to have something that will spell check our code and check our JavaScript code in a way that will notify us if something isn't working correctly for this we will use Linda J as standard you okay great you are now all set up to start writing JavaScript projects let's carry on hi and welcome back in this project we're gonna be using an HTML file and a JavaScript file in order to make our project hTML is a hypertext markup language used as the basis of a web page HTML consists of tags surrounded in angular brackets like this the HTML tag can be used to define headings titles images links buttons there's a whole load of tags available to your disposal in this lesson we're gonna be focusing on the HTML file and how to link it to our other files such as our JavaScript file and CSS stylesheet the first thing we're going to do is make sure to check our files are named accordingly the most important thing is the ending or file extension we need to make sure that we use jeaious to let our code editor know that we are going to be writing JavaScript code in this file and to treat it like a JavaScript file we also need to do this for the stylesheet or CSS file CSS stands for cascading style sheet we will cover that in the next lesson now we need to link the javascript file to the HTML file we will do so by putting a script tag in between the head tag then using a Dom event listener in our JavaScript to make sure this tag is read after all the code in this HTML file has been that an alternative way to do this is by putting the script tag at the end of the document in the footer but this is the way we're doing it for the sake of the tutorial it is important to note that in this script tag the source or SRC as you can see here the text in between the quotation marks needs to be the relative path of where the JavaScript file is as the file is in the root of our folder we simply write up J s if your app JS file happens to be in a folder you will need to change this relative path in the script tag so to recap if the file is in the same location as your HTML file we write this and if it's in a subfolder to your index.html file we write this replacing the green folder with whatever you you have named your folder please do remember to keep your index.html file at the root of your folder if you do not our browser will not be able to read this project well not without loads of configuration anyway I am actually going to flip over to our javascript file and add the Dom event listener now too you must make sure all our JavaScript in the future is written in between these two parentheses we need to make sure this is done so that it's picked up by the script tag you wrote earlier in our HTML file okay so let's go ahead and add that event listener to our javascript file like so again the Dom content loaded event fires when the initial HTML document has been completely loaded and passed this is without waiting for the starchie's images and subframes to finish loading the target of our event is the document referring to the HTML document okay now back to our HTML file so now we're gonna link our stylesheet in a very similar way but using a link tag instead add the following tag in between your head tag again make sure the relative path of the file is correct we do not need to add anything into our CSS file for this to be picked up now that we have licked our to other files in our HTML file let's start by adding some code to our body now we first need to plan exactly what we want our Tetris game to look like in terms of shape as we're gonna be making a grid based game I would suggest drawing this out fast or using something like Google sheets like me to get an idea of what we have to get on with and tackle I'm gonna flip over to Google sheets now I have actually pre drawn this to give you an idea of what to be aiming for you can make your own grid as big or as little as you want it's up to you so you can see here I want to make my grid 20 squares tall and ten squares and height so how would we make these 200 squares we need to make them in our HTML file and then add styling to them with our style sheet or CSS file so let's do it let's code up to 200 divs in our HTML file there are other ways of doing this from the JavaScript filed that involve creating an element 200 times using a for loop but as we're just starting out I think it's important to focus on a more visual way of learning so we can see what's happening now let's put these 200 divs and a div of its own that we are gonna give a class name of grid to we are doing this so we can contain the 200 is in a div of its own that we're gonna start an our CSS later now we are gonna want to display the score let's do that an h3 tag like this with a span inside of it like this h1 h2 h3 tags are all header tags h1 being your main one and going down in size all the way do you hit h8 okay moving on let's give this fan an ID of score so we know exactly which span tag to display the future score in just in case we used another span tag in our project as a person class names IDs are unique and can only be used once I am also going to hard-code a 0 here for now finally I'm going to add a button using the button tag as I want this button to start the game I'm gonna give it a very clear ID or start button ok let's save these files we are going to right click just here so we can open this file in our browser amazing there you won't see the two hundred tubes as they have no styling applied yet you can see them if you inspect the page if you do not know how to inspect the page you can simply do so by pressing down the ctrl button on your keyboard and left clicking the browser like this check out the sniff C animation I did here it's also where you view the console.log we will be using the console log later it's a tool that allows it to see what's going on under the hood when writing JavaScript and is super useful ok great thanks this lesson let's move on after just a few questions in this lesson we're going to be covering CSS or cascading style sheets CSS is a simple mechanism that allows you to add styles so fonts add colors to your web documents becoming a pro at this takes a lot of practice we are simply going to be doing the basics in order for us to carry on learning JavaScript as this is a JavaScript tutorial this will include styling to make our grid look like a grid add colors to ah tetriminos and touching a little bit on flexbox once you have finished this tutorial please do go back and add as much styling as you want feel free to share it with me I would love to see your finished games okay let's start off by giving some styling to our grid the first thing we do is navigate to our style.css file now let's pick up the div with a class name of grid we tell our stylesheet we are looking for a class by using this dot before the class name so as a recap we are picking out the div with a class name of grid that has 200 divs inside of it let's say we want our squares to be 20 by 20 pixels at a 10 by 20 grid that would mean we need to make the width of our grid 200 pixels and the height 400 pixels I'm gonna make it yellow so we can see it in our browser now we are also gonna style the divs in the grid we do serve like this we put the div element after the element with a class name of grid by doing this we are saying that we want to solve only the divs in that element like this so essentially all other divs we use in the future in our project will be unaffected by this styling okay so inside the parenthesis we're gonna assign the height and the width let's also make them red just so we can see them in our browser okay let's save that file and refresh our browser you will see the red squares show up as a stuck over each other this is the case by default divs do this they stack of each other unlike h3 which appear in line this is where flexbox comes in we need to use flexbox to make sure the red squares appear stacks and a line and then stuck over each other as soon as they don't fit in the grid div width parameter let's add display flux and save and refresh the browser and now we have it we now have a grid we can work with and start adding some JavaScript code and game functionality to let's move on just after a few questions you in this video I want to take a break just explain what variables are and how we use them in JavaScript so in JavaScript you can store values in something called variables they are legal identifiers quite simply is this so the variable X here equals one it is important to note that when you declare a variable its name must be unique you can assign numeric value to a variable like the number one or a string value such as 1 and quick marks an array such as 1 & 2 in an array a boolean such as true or false or you can just leave it undefined for later use like this now by definition variables mean anything that can vary so let's see this in action let's get X and assign it to the value 23 note we do not use var again as we have defined X above let's go ahead & console.log that and you will see X has now changed value now let's talk about scope when defining variables it is important to know that they have scope variables have two types of scope global scope will function scope meaning they can only be accessed inside our function let's have a look at this in action here is a function I have written to alert me with their name you let's put the var name here outside the function okay that works this is because it's a globally scoped variable now I'm going to move it here inside the function this also worked as the variable is declared and side the function however what happens if I now want to show you la outside of this function it will not work as the variable is not being picked up as it's inside this functioned scope essentially it's out of our reach now okay got it now let's talk a little bit more about constant depth and how they differ from bar so when es6 came in it introduced two new ways to create variables let and constants let's look a little bit about the difference between left and var fast let allows you to declare variables that are limited to a scope of a block statement unlike a bar what does this mean well let's have a look at an example okay so I'm going to declare variable X here as one now I'm gonna write a function here called find X inside I'm gonna declare variable X again as two now if I want an alert telling me what to is inside this function I will get two however what will I get if I want to move the allow outside of this function I will get to as variable is global and we declared it after the first declaration now let's do the same but using let so all I'm doing is writing the same thing but replacing bar with let you you will now see that we are getting one as the other let inside the find X function is out of our scope now finally Const Const works in the same way let does in that you cannot access it if it is inside a function however it is also constant as conferred allude to once you have defined it you cannot change it later on this is pretty useful when working with big projects and declaring what you do not want to be changed let's have a look at this in our code editor you okay so that we have it let's recap bar a function scoped or globally scoped variable let a block scoped variable and Const a block scoped variable that cannot be reassigned okay now we have a grasp on variables let's go back to our game of Tetris in this lesson we're gonna start adding functionality to our project by adding some JavaScript code we will especially be focusing on JavaScript arrays and how we will be using them in order to make our game an array is a special variable which can hold more than one value at one time if you have a list of items so a list of Tomino names for example storing the tetriminos a single constants we'll do it like this however what if you want to loop through these tetriminos and find a specific one and what if you had not 5 but 200 of them the solution is an array an array can hold many values under a single name and you can access the value by referring to an index number you will be using the index number a lot in this course JavaScript arrays are zero indexed meaning that the first element of the array is at index zero and the last element is at the index equal to the value of the arrays length property minus one this is important for our game but also for JavaScript array knowledge in general the first thing we're going to do is tell our JavaScript the width of a grid in squares using Const so let's flip over to our javascript file now as the value will not change we are going to use a Const so as a reminder the Const keyword denotes a non mutable view of mutable data next we are gonna use something called a query selector to look through our HTML document and find the element with a class name of grid document query selector is an inbuilt JavaScript method you will see here we are using dot again as we are looking for a class name once we find it sign it to the constant we have decided to call grid now our JavaScript knows that every time we type grid and do something to grid we want it to affect the element with a class name of grid in our HTML 5 now we also want our JavaScript to talk to all the squares in our grid using the query selector again but this time using document query selects at all as we want to collect all the divs inside the element the class name of grid we do this now what we are going to do involves an inbuilt JavaScript method called array from you're going to use it to in layman terms collect all the divs on our grid or 200 of them and turn them into an array we can work with now each div will have a specific index number let's pass these collector divs through array from to make them an array and assign it to let squares let's get our console up here so we can see what our console log tells us now hit refresh on your browser okay great you will now see that these squares is an array of 200 divs with index numbers from 0 to 199 the reason it says 0 to 1 9 9 instead of 1 to 200 is that the index count always starts at 0 what does this mean for us in our game well we just need to learn how to count a little differently let's have a look at our grid and these squares inside numbered by their indexes this is something I made in Google sheets earlier to make it easier for us understand you will see that if we want to be in the fifth square so this would be the fifth square here we would need to tell our JavaScript we want to be in the index four of our squares array why is this an array again because we collected all the divs and pass them through array from okay let's move on the last thing I'm going to do for this section is get a few more things from our HTML document we are using a hash here to indicate we are looking for an ID so if you look on HTML page as a reminder we gave this span tag an idea of school and this button an ID of start button let's go ahead and pick them out again with our query selector there is also a get element by ID feel free to use that as well I'm gonna use this query selector okay great that's it for this lesson let's recap with just a few questions you in this video we're gonna take a quick break to go over exactly what a function is and why we use them functions are one of the main building blocks of JavaScript and in fact most languages in JavaScript a function allows you to write a block of code define it with a name and execute it as many times as you like it's all about recycling code with functions in this video I will be showing you how to write a super basic function that we will later be adapting to use in our own game of Tetris okay so let's leap over to our code editor so that I can show you a super basic example of a function first so the simplest example I'm gonna show you is a function that sets off an alert the last thing we're gonna do is write function like this followed by a word I've chosen to call my function this word should really convey what is happening in my function we do this make our code more readable for colleagues simply if we're forgetful I'm gonna choose to call my function show a lot I am using camel case for this camel case is the practice of writing more than one word joined as one but visually separated by making each word after the first start with a capital letter it has no spaces or punctuation I consider this the best practice for writing functions okay so after naming our function we write these two buckets these two brackets are passing down parameters into our function as we don't have any just yet I will leave this lunk now we have to put our block of code that defines a function in a parenthesis I'm going to make my function shown alert like this you will see I'm writing the inbuilt method of alert and passing through is string a string is defined as a word in these clip marks okay great now let's test out what we have written we can invoke a function like this amazing so that's the basics now let's pass parameter or two into our function so the thing about parameters is that if you choose pass one it needs to be one and this needs to be reflected in the COBE right if you try pass any more than one the rest of these parameters will be ignored let's have a look at it now so say I want pass down a first name into my function you and somewhere else in my code I have recycled this function and written this okay let's uncomment that but as soon as I pass on my last name that part will be ignored it is the same for if I ask for the last name and the function but I do not pass it through I will get undefined we can also use argument objects and functions if we declare them outside of the function we do not need to pass them through to use them for example I'm going to write an array called name now using my function I'm gonna access the first item of my array so index is zero like this you okay great we are now ready to carry on with our Tetris walkthrough in this video we're gonna talk a little bit about arrow functions and how we're going to use them in order to draw our tetriminos onto our grid in this lesson we're going to be doing more array work and be introducing something called an arrow function as well as an inbuilt JavaScript method called for each arrow functions were introduced in es6 and allow us to write shorter function syntax here is the original way we would write what was and the evolution to what we now know at the arrow function if you have parameters you can pass them through the brackets like this this is what we're going to be doing and evolving the for each method the for each method calls a provided callback function once for each element in an array in ascending order the callback is invoked for three arguments the value of the element the index of the element and the array object being traversed or in layman terms we're going to get an array with a bunch of values and apply logic to each one here we can see an example of for each working on an array i have called item array using this code I'm also going to pick out each item of that array so I can apply logic to it you can see here I've chosen to call it item I can call it anything I want really JavaScript all know what I mean it will know it's an item in my array now using an error function I do this and add two to each item in my array so that's the syntax I don't see an action the simplest example I can show you of this happening is when we choose to add something to each item in our array let's make an array of names so an array with strings as indicated by these two quick marks here and separated by commas and put them in square brackets now it's super important to remember what is inbuilt and what isn't here names name is our array that we made above for each is the inbuilt method that comes with some magic that will make our javascript do things that was writing any logic for it name here is something that we have chosen to call the items in our array I could call this whatever I want chair dog my JavaScript will know I'm an item in my names array this arrow is the error function we referred to in our last video so what we are saying here is that for each item or name in our names array we want to print out individually that name and add this string is the best to it okay let's check that out okay and that has worked great now this is a super simple example of how to use for each with an array there are literally so many different ways to use this input method I always think as that is learn with a working example so let's get going and use the for each method and our function to draw a five tetromino shapes onto the grid let's do this in the next lesson okay and welcome back this is a continuation from the last lesson where we learn about poor each and how we're going to use it in order to draw the tetriminos on to our grid game the first thing we're going to do is get out our Google sheets again and draw out every single rotation of each shape note the otra Mina will say the same during each rotation and the Zed touch arena and El techo me know we'll only have two versions of itself once we are happy with each of the shapes for rotations it's time to draw them using our Witt constant remember we set that as ten in our JavaScript file let's get going and start with our l tetra me know we will set as const as the shape and it's for rotations will not change you will make the El techo Mina an array with four arrays inside it each of the four arrays is one of its rotations if you see here what I'm doing is using my drawing to draw the shape onto the grid as if I was only allowed to use the grid indexes so drawing in the index with number one on our grid shape and index with the number ten plus one on our grid shape ten being the width and index number twenty-one and the index number two it will give us this shape right here okay now let's draw the other three rotations we can do the ball starting from index zero no need to draw them in their locations on my drawing let's do that now you once we have done that we need to do the other four shapes in the same way now because I have done this before I'm simply gonna copy this into my project from my github account you are welcome to go and grab the tetromino arrays as well but I would stress that I do advise against it and only suggest it if you are stuck and getting some strange shapes or error messages by trying to make all the shapes yourself you will get a better understanding of what we are doing here and what we are trying to achieve it would also defeat the purpose of the tutorial if you're trying to understand JavaScript a little bit better I mean this is the perfect arrays exercise okay once we have our four shapes let's put them in an array of their own let's put this as a Const and call it the tetriminos you okay great we now have our tetriminos but we can't see them that's because we need to add some styling to them to see them first let's decide that we're going to make them all one color for now just to make it easier we can change this later so let's flip over to our style sheet and add the following you okay now let's decide where we want to start to drug our tetriminos on the squares grid let's say the first square of our chosen tetrominos first rotation array is going to start at the square with index 4 so let current position equal 4 now let's pick a tetromino and its first rotation so let's go to our the tetriminos array of arrays by putting a 0 in square brackets like this we are saying we want to access the first item on our array let's look at this slowly okay so first let's console.log the tetriminos our array of arrays you can see that here we have an array of 5 things or as induced 0 to 4 these are our 5 tetromino shapes if you click on the first one so index 0 you will see inside it has its own 4 things in it these are the faster tribunal shape rotations we wrote earlier let's click on the first one so again index 0 this should look familiar it is the first rotation in our alpha 2 meter let's go ahead and now console.log the tetrominos 0 and again in brackets 0 and amazing it's the same we now assign this variable to current just so we are all clear I have picked the L tetrominos first rotation this is now my current shape okay now let's draw this using for each to see if that's true let's write a function called draw and in that function let's get on a current array or what we have assigned is current above now for each item in that array we want to add a classic tetromino which would color that item which is technically a div inside the element with a class name of grid you so this is how footage works it applies logic to each item of an array we use the arrow function here as we saw above to add the code inside the parenthesis to each index of the current array just like we passed the 0 into the array above to access the first item we are passing on a number to the square 0 to correct blue we access the CSS style sheet by using clusters add two other style of tetriminos to the squares in the tetriminos it is in in this occasion and we are passing through a for this is because we set the current position as four plus each index and the currently chosen tetromino array okay so now let's invoke this draw function like this now save your file and quickly go back to a CSS file to get rid of the red background we gave all our divs at the beginning we no longer need this hit save again and let's refresh our browser and great there we go you can now see a blue tetromino shape it is the elta Jimena and its first rotation okay now let's go back to our javascript and select one of the tetrominos randomly today's we're gonna be using three more in book JavaScript methods math.random which will give us a random number from our array length length which is an inbuilt method that will tell us exactly how long our array is and math.floor which will round down to the nearest integer so let's add a variable that we're going to call random to randomly select a tetromino from our tetriminos array we use an inbuilt javascript method called math.random and multiply it by the length of our tetriminos array length being in Beart as well we then pass this through another input method called math.floor this will round down the number to its nearest full integer okay so let's see if that has worked we should get a new number each time you refresh the page refresh again and great now we have that let's go back to our current variable and replace the first zero with random now what is happening here is that instead of passing through 0 and accessing the first item of our H time we are passing through a number from 0 to 4 randomly this will give back the first second third fourth or fifth tetromino in order to Trevino's array once we have one of these five shapes we want to access again but always picking is first rotation let's set this as let current rotation equals zero now if he passes through we will always start at the first rotation of any random tetromino chosen I'm just going to change this here to more accurately reflect what is happening now just to be as transparent as possible let's invoke the draw function here to by getting rid of this code okay now the last thing we want to do is write a function to unroll the randomly chosen tetromino and its current rotation we do the same as we did to draw it so once again we name the function on draw we use a for each so for each item or index in our current shaped array we look at each of their current positions add the index of the shape and pass it through our squares array now the only difference here is apart from adding the class we are removing the class tetromino from its current location in the grid so it will visibly disappear from our grid okay great we now officially have all our tetriminos and can draw each one on our grid please do if you're not quite sure pause here and just have a go at messing around when the numbers replace the current position so on just to see exactly what's happening refresh the browser loads to see if you'll get in a random tetromino if not go over this lesson again I will provide the code below as well so don't worry if you feel stuck in the next lesson we're going to be focusing on moving the tetriminos around our grid hey and welcome back in this lesson we're gonna learn a little bit about timer IDs and an inbuilt method called set interval set interval allows us to invoke a function that we passed through it after X amount of time in this example the time is 1000 milliseconds or in other words one second we are going to be using set interval for this project because we want our tetromino shape to oughta move down the grid every second just like in the real game as mentioned in the example we do this they pass it through a function that we will call move down into the set interval as well as the milliseconds we want to invoke this function at we are going to assign this two-timer ID this is so we can stop the setinterval in the future you now let's write the moves on function using the functions of an draw and draw we wrote in our previous lessons so we want to under the shape from its current position and add a whole width to the current position and draw again in its new position let's check if that has worked okay great we can see that the shape is now also moving down our screen sadly it's not stopping and going through the bottom of our grid this is something that we need to solve we are going to do this simply by clicking back to our HTML and adding ten more divs to the bottom of our two hundred divs this time with a class name of taken as these do not have a style in our style sheet they will not show up visibly we just know that they have that class if I inspect the page you will see them there you you next we need to write a freeze function in this function we want to write an if statement an if statement looks like this we passed through a condition and brackets before an if whatever the condition between these brackets is has to give us a boolean response so a true or a false if the condition is true we carry out the next steps of whatever is in between these two parentheses so here we have an example if the temperature is about 20 degrees so this statement is true you return it is hot now we can also write an if else statement an if-else statement is the same as an if statement however if the condition is our false we can also return a response so in this example here if the temperature is not over 20 degrees we return it is cold now we can also keep adding and adding with this else if and go on forever just like in this example here so here if the temperature is not above 20 degrees so false we bypass this if statement and check the else F if the temperature is deeply equal to indicated by these three equal signs that is deeply equal deeply equal to 18 then we return at it is warm and of course if it is not then this statement is also false and we return a it is called so let's go back to what we want to happen in our if statement if some some another inbuilt JavaScript method similar to how for each works however instead of applying logic to each item in our array like for each with some we are checking that the logic we write in the brackets is true for some of the items in our array so basically if we ever get one true back we are good to go so if some of the squares that make up the current tetromino if their index plus a whole width so essentially we are checking the next space down from each square contains a square with a class name of taken so if this statement is true for at least one item in our current item you know array we turn each of the tetromino squares into a square that contains the class of taken you you got it we then also in we do select a new tetriminos if your car tetromino this will be familiar let's get a random tetromino number you you we then passes through a tremendous array and it's fast rotation we then set this as our current tetromino then we put it at the current position so for and finally we draw this new randomly selected such amino okay that is it that is our freeze function let's add this freeze function into our move down function so that it gets invoked to check every second oops I missed the capital M of math here that is really important please don't forget to add this here okay great now let's flip over to our browser and see if that has worked you amazing let's move on to the next lesson you you okay so we now have an array of squares great and we have wrap these squares over each other to appear like a grid amazing however in reality how does our computer know when we are at the very left hand side of our grid what stops a touch from you know from going from this position to this position when we were being right technically we are in an array so this would be the next logical step we need to write a set of rules to let our JavaScript know when any of our squares that make up our tetromino are in a certain indexed square we are going to do this using good old-fashioned maths as we can see here our grid has a width of 10 made up of an array of squares with indexes 0 to 199 I want to make sure that if the tetromino is in the square with index 10 I don't want it to move left anymore I want to stop it as otherwise it will appear in the square with index number 11 so I need to write a rule that will stop our squares if they are in the square with index 10 20 30 and so on let's get started by defining what is a move left function what we're going to be doing is visually moving the tetrameter left by drawing it and undrawn it in the squares we start off by removing any trace of the shape in its current location before we start so that we have a clean slate next we define what is the left edge and if the shape is in it this is where our math comes in for this we use the inbuilt method called sum again as a recap sum is a method that looks at each item in the array and checks if a statement is true for at least one of the items if it is the whole statement is therefore true so once again let's use current as a reminder current is our current randomly selected tetromino and its current rotation we are checking that some of the current tetriminos item indexes if divided by the width leave exactly no remainder so again if one of the tetromino squares is in a square let's say that has an index of 10 we also know that 10 divided by the width so 10 gives us exactly 0 as a remainder this means our statement is true and the shape is at the left hand side of our grid this is also true for index 20 30 40 and so on let's use this information and only allow our shape to move left or minus one from its current position in the array if the shape is not at the left edge indicated by this exclamation or bang here we also want our tetromino to stop if there is another touch romina already there that has been frozen for this we are gonna have to have a taken class we are not gonna star this class we just want to assign it to the spaces that have been taken and you can't go into we will use an if statement for this what we want to write is if some of the squares in on touch communicate suddenly go into a space that contains a class I've taken while traveling left you want to push it back one space so it appears not to have moved we want to do this for every index in our tetromino shape so use an arrow function to do that like this and pass through the current position and add every index as it gets passed through then we add one to the current position so that moves back to its original space in the Euro and finally we draw the tetromino okay so that was a lot to take in so before we start writing the move right to move down and move up function let's why that's all up to see if it works fast before we move on Keiko's are pretty cool every single key on your keyboard has an assigned code to it that we can access through our JavaScript we are going to use this to make our tetromino move left if you press key code 37 right if you press key code 39 and make some JavaScript magic happen if you press the button down and so on you can technically make your such a minami of left if you press just about any key on your keyboard that you choose there is actually a pretty cool site called key code info that will give you the key code as soon as you press it when you're on the site we will also be looking at passing through events into functions so that we can use them so let's get started by assigning key codes to functions let's write a function called control and add a document event listener to listen for any time we press a key on our keyboard anytime you press a key on our keyboard we're going to listen out for which one was clicked and invert with the control function we are also going to pass through an e here for event now with if-statements we're going to decide what happens when you press a key if we press the key that deeply equals key code 37 we want our tetromino to invoke this function new left let's see if this works as we wrote the function in the previous lesson now I'll give you the coolest part about JavaScript is making stuff happen in your browser well you'll be glad to know this is exactly what the event listener does the event target method at event listener sets up a function that we called whenever the specified event is delivered to the target common targets are elements document and window in laymen terms if you attach an event listener to something like a div and click it in your browser cool stuff will happen you just have to attach it to the element you have chosen like this you can see here that we are passing through two things the type of event so in this case key up and a function in this case is the function control we are just written you can also do remove event listener to deactivate any listening happening there are literally so many events you can use here are just a few of the my head so once again the eventlistener here listens out any time you press a key on our keyboard using the key up event if a key is pressed we invoke the control function we have just written we attach this event listener to our whole HTML document okay let's refresh our browser and great it works the tetromino is even stopping when we hit the left-hand side which is great now let's figure out what we're going to do for the rest of the key codes I have commented out the other functions for now as we have not written them yet but just so you know what we need to do so if I press up I want the shape to rotate if I press key code 39 and want the shape to go right and if I press down I want the shape to go down put pasta this is something you already have so we can pass it through here again you let's do the move right function based on the same logic as the move left and leave the rotate function for the next lesson you so once again we under the squares that make up adduction we know from their current indexes we define what it means when some of the squares that make up our current amino are in certain indexes and call this a constant of is a right edge what you can see is happening here is that if an index is divisible by the web and its remainder deeply equals the width minus one so in this case 9 or 18 or 27 and so on this statement is true and we are at the right edge so if we are not at the right edge indicated by the bank here we can freely move each square and the tetromino plus 1 down the array then if some of the squares that make up our tetromino are suddenly in a square that contains the clothes taken we have to push them back a space in our array visually making them appear like they have new double you and finally we redraw the tetromino in its new position let's try this out okay great we can now move left to right without going off the grid and to the bottom without our tetriminos going past the squares with the class of taken let's move on to our next lesson in this lesson we're going to be doing more of a work and also looking a little bit into the increment operator the increment operator it's going to help us access the next item in our tetrominos array we are going to be doing this as we need to access all four of each of our tetromino rotations on the click of a key code we're going to be doing this using the double plus so plus plus which works in a way that simply means we are adding plus one to the defined value before it it is called an increment operator in this example you can see how it works if Y is five and we use the increment operator on it the Y will now have a value of six and you guessed it there's also a decrement operator using the double - will make the value of our Y change from five to four now let's use this in our code we're going to write a function to rotate the tetromino this is actually us just skipping to the next rotation in the current rotation array as always let's start by on drawing the shape next we use the increment operator to move down to the next item in our array so the layout of our next rotation we drew up for the concert Romina you using an if statement we say that if the current rotation index is equal to the amount of rotations in our current tetromino shape so for we want to go back to the first item in our array so in other words the first rotation they are again you if the statement is false we simply want to pass through that new current rotation number into our contact Romina like this you and then we draw it okay now let's not forget to uncomment this out here we need to do this so that when we press the up key the shape will rotate now let's refresh our page and see how that works you okay great we are now ready to move on in this lesson we're going to be covering everything we have learnt before to essentially build a mini-grid to the right of our grid right now we will be doing this so that we can display the upcoming shapes for our user this is a great lesson as it can also be considered a mini recap of all the work we have done so far we will be going over how to create a grid pick out elements to style in our style sheet pick out elements add functionality to and how to work with arrays in order to pick our next shape okay so let's get started the first thing I'm going to do is go over to our HTML and do the following we are going to add a four by four grid word game so how do we do this the same way as we did it before we add 16 divs here and put them in a div you will choose to call our mini grids you now let's flip over to our stylesheet and similarly to the other grid make our mini grid 80 by 80 pixels I'm gonna use flexbox again and then wrap them over themselves like this you you okay great and there we have our mini grid now I want it to display to the right of my main grid however to do this I'm simply going to put two grids and the two goons only into a div of its own that I'm going to choose the core container you now back in our stylesheet I'm going to use flexbox again to make these two items display:inline you I am also going to do one thing to make it look a little better and that is at a margin left of 50 pixels okay great now we can see that there are two separate grades next to one another now let's move on to our JavaScript code so the first thing I want to do is pick up each div and our mini grid and call it display squares instead of squares once again we do this using query selector all as we want all the divs inside the div with a class named mini grid you note we are not using away from this time just to show you a slightly different approach the next thing we need to do is tell our JavaScript how big the width of our mini grid is let's use display width instead of width for naming this constant we are also going to need to set our index at zero let's call this our display index so our JavaScript knows we want to talk to the mini grid only now we need another array we need an array of our fighter Tommy knows as they're fast rotations for our mini grid to show we do not need all the rotations as we just need to display our tetromino here as you can see I am simply rewriting the Altima nose fast rotation here same for the Zed T touch me know and so on okay now let's get to writing a function that will display a shape using the display squares I have collected so all the DES in our mini grid I am using for each to get each item or as I'm gonna call it square and remove any trace of a tetromino class from it so that's for the whole mini grid I'm removing across - shereena from the whole mini grid you next I'm going into the next latet Ramirez array and using next random so let's define next random as a value I'm going to start with the value of 0 so next round and be 0 let's actually move this up to the very top of our file we are doing this as we also need to use it and the freeze function you so right before we choose a random tetromino for our main grid we are adding one more step what is happening here the value next random is being passed on to the random value so we choose a next randomly selected tetromino assign this value to those random this means we now have a value okay let's get back to writing or display shape function you for each square that makes up are now randomly selected up next satrom you know we want to add a class of tetromino to it we then when a pass it through our display squares hopefully this approach is now familiar to you you let's see if that has now worked save your file flip over to the browser hit refresh you and great that has now worked now what would be really great is if we can get this shape to display as soon as our game starts for this we're gonna start to hook up the start and pause button this was quite a tough section so I would recommend going slowly on this section and trying a console log each step as you code just to make sure you understand what is happening under the hood feel free to go over the section once more if you need to this lesson is going to be all about setting intervals and clearing intervals this is an extension of what we touched on previously when we taught our JavaScript that we want the move done function to invoke every thousand milliseconds we are now essentially going to move that function into an event listener that has attached to our button that we have an idea of start button for this means that every time we press the start button we are going to invoke the function move down with its set interval we are also going to go a step further to see how timer ids work by adding a pause functionality the first thing we're going to do is grab our button we get an ID or start button - that we called start button above and attach it to an event listener ah it's saying not to find let's see why not okay use the capital here I'm gonna change this I'm also going to change this for the school display okay let's carry on as you can see everything's really case sensitive and spelling is really important when coding I'm also gonna let our timer ID be null by leaving it blank like this okay so if the button is clicked and we have at our MIDI value so the value is not null we want to pause the game we do this by passing timer ID through clear interval like this and setting the value of our timer ID to null else when the start button is pressed we draw the tetromino in what is the default current position so for put the timer ID on a set interval of invoking they moved down function every 1000 milliseconds select the next random shape you want to display in our mini grid and evoke the display shape function we wrote that will display the randomly selects term you know we just determined you you you okay great we now need to uninvite them you don't function that is on a timer that we wrote previously from our code so get rid of it unless it's in the start button eventlistener you so what is happening here is that because we have this line of code the set interval that starts us at from you know moving down and vocht on the load of the browser we want it to be invoked only if we press the start button so let's comment this out here and let's refresh our browser and per fax let's carry on you in this video we're gonna take a break to look into what exactly splice is and us using a splice on an array controller changes content we can remove items from the array or remove them and replace them with totally new ones it is important to note that it will change the original array once this particular JavaScript method is used in other words we are mutating the array so to recap splice can remove an item or items from any position in an array splice can also remove an item or items from any position in an array and replace them with new ones let's have a look at how this works by flipping over to our code ok let's get an array we can work with I'm going to call it planets so we now have an array of four planets now what if I want to remove Pluto from my array as I'm not sure of its planet in our winni days I would use a splice to do this typing my planets array I would attach splice to it like this next I will pass through the index of the item in my array I want to remove as I only want to remove that one item I'm gonna pass in a 1 so 2 1 ok great let's console.log planet slice 2 1 in brackets you will see that we should get Pluto if you console.log planets you will see that our original planets array now only contains 3 planets without Pluto ok now what if I have changed my mind I want to Riyadh Pluto but also add Uranus we can use splice to do this let's say I want to put in the first index of myarray but not remove anything just put Pluto back as well as add Uranus I would do so like this we pass through a 1 for the first index and a 0 as we don't want to remove anything and then the two strains we want to add at index 1 let's have a look at what this gives us and perfect as you can probably tell by now the first two parameters are the start index and the delete count respectively leaving the delete count zero will not remove anything from the array you might also notice that we get a return of removed items or item every time we use splice I have just one more example to show you before we move on to implementing this in our Tetris project so say I want to remove every single item from my array but Amar's that's right and I believe that Mars is the only planet we can do this by simply passing through the index number into slice passing this through returns all of our the planets and if we console.log planets we will now see it only consists of Mars ok great now that we have covered splice let's move on into implementing it into Tetris in this section we're gonna be focusing on what happens when the user managed to fill a whole row with tetromino squares we need to do a few things here we need to remove the roof from our grid or array add an increased score to our score tally display the score on our browser and add a new fresh row to a grid or array so the grid doesn't appear to shrink in size for this we're gonna be focusing on splice concat and appendchild as we now know the splice method adds and removes items to and from arrays and returns removed items let's move on to concat concat allows us to merge two arrays together let's use the same tetriminos array now let's say we want to add another array to it we do so using concat here is my second array and I'm gonna call it shapes by using the syntax and passing through these shapes Rea like this we get the two arrays joined together and finally append child append child is an inbuilt JavaScript method that allows us to append elements to an existing element for example a grid let's have a look at how this works in an example first let's recreate a grid so make a div with a class of grids now we're going to be appending divs into this div with a class of grid so let's add some styling so we can actually see them now let's get the div with a class of grid using our query selector and call it grid for JavaScript now using Create element so that's another inbuilt method let's create a div and our JavaScript now let's put this create a div into a grid using a pen child like this and tada we have now put a little red square into a div for the class of grid now let's use these three input methods in our project let's get the lesson started by creating our add school function where we want all the steps outline to happen the first thing we're gonna do is write a for loop this loop will loop over entire grid and all its squares every 10 squares so with my whip the for loop syntax in George grip looks a little bit like this in this example what we are doing here is three things setting a variable before the loop starts so far equals zero defining the condition for the loop to run so I must be less than 5 and incrementing the value by one using the increment operator we move on to the next item in our array to loop over so what would this look like let's have a look with an example an array that I have called shapes now if we use the for loop to loop over the length of the array and loop over each item one by one what will we get every console.log shapes you will get a list of the shapes printed out in our console.log okay now let's use this in a project we nexif i and what we want our road to be this will be the i+ every square that makes up a row now we use an inbuilt method called every to check if every square and are defined row contains a div with a class of taken if it does and the statement is true we do a few things we add 10 to the score we display the to our user using the score display and an inbuilt method called inner HTML and for each item the row we remove the class of taken and we take out this row using splice like this I have a sinus taken out row to a Const called squares removed let's console.log this to see what is happening okay great you can see here what our row is and what is made up of now let's riad these squares to our squares array so that the grid doesn't appear smaller so what we're going to do is we're going to append these new squares to our grid let's go back to our browser hit refresh and great you will see here that our row has cut itself out and appended itself to the beginning of our array okay let's remove the cross tetromino so the blue so that it looks like it should amazing we are now down to the final stage of our game which is defining what a game over is we are now nearly at the end of our tetris course by now you would have covered all the following inbuilt JavaScript methods and use them in our project this is pretty impressive we only have one more thing let's do and that is define what is our game over now as you know tetris finishes when you stack up or you'll touch aminos so that they don't fit in the grid anymore this makes our writing of the gaming of a definition super simple all we have to do is tell our JavaScript that if there is a taken shape present in the original default position or index for we call it a game over okay let's write our game over function we're going to write a game of a function in it we are gonna have an if statement that says if some of our current tetromino shape that is in play if some of its items or index is at the current tetriminos composition contain the class of taken we call our game over we then display this in our school display we then also clear the games timer IDs so that the autumn you down function stops you and there we have it a fully functioning game of tetris now I would love you to take this game make your own share with me on YouTube my channel is Anna Kubo or on Twitter and your underscore Kubo I would love to see what you're made and how you've taken this and made your own and taking it to the next level the options for you to do this are adding levels adding a line count may be having some music to the game or just styling your game to the max I do have one final lesson for you that I think might be quite interesting that is to do with styling of the tetromino colors if you want to learn how to do this and also wanna learn how to tidy up your code for best practice please do watch my final video for this series hi and welcome to the last video in my JavaScript games tutorial if you want to learn how to assign colors each from you know and also wanna learn how to tidy up your code for best practice definitely watch this last video in the series once again I hope you have enjoyed this series and if you do have any questions please do not hesitate to contact me on my socials below ok so the last thing we want to do is assign colors to each of our tetriminos you will do this in our JavaScript file first we want to make a Const called colors in it I'm gonna put the colors I want my tetriminos to be in in the same order as they appear in my tetriminos array this means my alt search I mean I wanna be orange my Zed touch me know will not be red and so on you now that we have that we need to find each time we add and remove the class list of tetromino in our code so we can add this color on top of it so after that line of code has been written the first instance I can see this in is in the draw function let's use style and background color to add styling in our JavaScript file we also pass through whatever value is currently random into our colors array this means that if the random tetromino is currently the l tetromino the color we will get back will be orange each time as we are passing through zero to remove the color as we need to do for undraw we just leave an empty string like this you we also need to do this for the mini-grid where it displays the next shape let's do the same passing through next random instead of random you finally the only place remove the color is here in the ad score function you let's see if that has worked and wait you now just a quick cleanup you can see here getting rid of any additional lines commented out codes and changing this as it should be a conce not alert and there we have it thank you so much for watching my video
Info
Channel: freeCodeCamp.org
Views: 217,524
Rating: undefined out of 5
Keywords: tetris, javascript, javascript tutorial
Id: rAUn1Lom6dw
Channel Id: undefined
Length: 96min 8sec (5768 seconds)
Published: Thu May 14 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.