Www.shodor.org



The BasicsJS and HTMLWhat is JavaScript?Editing HTML with JSLinking JS to HTMLEventsOutputAlertPromptConsoleSyntaxStatementsCommentsVariablesOperatorsData TypesConditional StatementsIf/Elif/ElseSwitchArraysArray BasicsArray MethodsLoopsFor LoopsForFor EachFor InWhileWhileDo WhileFunctionsObjectsMake Your Own Project – SnakeJS AND HTMLWhat is JavaScript?JavaScript is the programming language of HTML and the Internet. JavaScript is used in conjunction with HTML and CSS (which define the content and design of the webpage) to define the behavior of the webpage. JavaScript is very powerful and is a must-learn if you wish to create a dynamic and interactive website. Before beginning this tutorial it is recommended to have completed the HTML and CSS tutorials at tutorials.Editing HTML with JSJavaScript is used in most dynamic websites across the internet. JS can be used to edit HTML elements and attributes, as well as CSS styles. One of the ways to edit HTML with JS is using the method getElementById()This method finds an HTML element (with id="test"), and changes the element (innerHTML) to "I edited HTML using JS!":document.getElementById(“test”).innerHTML = “I edited HTML using JS!”;JavaScript can also change the attributes of HTML elements. Here I changed the source of an image (I changed the current image to a different image).:image.src = “differentimage.jpg”;Lastly, JavaScript can change the styles of HTML attributes (CSS). Here I changed the font color of the attribute with id= “test” to blue:document.getElementById(“test”).style.color = “blue”;Linking JS to HTMLJavaScript code can be placed in the <body> and the <head> sections of an HTML page. In HTML, JavaScript code must be inserted between <script> and </script> tags. Script tags can be placed in the <body>, or in the <head> section of an HTML page, or in both. (the <head> section is recommended however)<html><head><script>document.getElementById(“test”).innerHTML = “Hello”;</script></head><body><script>document.getElementById(“test”).innerHTML = “Goodbye”;</script></body></html>JavaScript code can also be placed in external files. External scripts are highly useful, because the same JavaScript file can be used for multiple web pages, while also keeping HTML, CSS, and JavaScript in separate files for easy readability. JavaScript files must have the file extension of .js (Ex. script.js, code.js, index.js).To use an external script, put the name of the script file in the src (source) attribute of the <script> tag:<html><head><script src= “index.js” type= “text/javascript”></script></head><body></body></html>EventsHTML events are things that occur, due to something the user or browser does. JavaScript is used on HTML pages execute code during HTML events. Here are some examples of HTML events:An HTML button was pressedThe page loadedThe user moved their mouse over an HTML elementJavaScript lets you execute code when events are detected. HTML uses event handlers and JS code to execute this code.Here are some common events:onloadonclickonmouseoverThese are examples of event handlers at work:<button onclick=“getElementById("test").innerHTML= “I used an event handler!!!!”>Click!</button>The above example changed the HTML element with id= “test” to “I used an event handler!!!!” when the button was clicked. OUTPUTConsoleTo see JavaScript in action open up the web console in your browser. This is where you can enter snippets of JS code to see output. Use the command console.log(“Type your stuff here!”); to see expressions printed in the console. Here is how to open the console:Chrome-Windows: Ctrl + Shift + JChrome-Mac: Cmd + Option + JFirefox-Windows: Ctrl + Shift + KFirefox-Mac: Cmd + Option + KInternet Explorer: F12Safari: Cmd + Option + CTry out the console right now! You can use the console for all your JavaScript snippets.AlertUse the alert(“ALERT”); command to send an alert to the user, which will appear in a a popup window in the browser. A variation of the alert function is the confirm function. The confirm command will send an alert to the user, but will ask the user to confirm an action or cancel the action. Use confirm(“CONFIRM”); in the console to try it out. PromptUse the prompt(“Ask a question”); command to ask the user a question, and receive a response. JavaScript also allows you to save the response as a variable, for later use, which can come in handy. To save the response as a variable follow this syntax:Note: You will learn more about variables in the following lessons. var response = prompt(“How old are you?”); SYNTAXStatementsJavaScript statements are lines of code that the computer follows and executes. Typical JS programs contain multiple statements. The computer executes statements in the order they are typed, one at a time. Each JS statement must end with a semicolon (;), to signal to the computer the end of the statement. CommentsI. CommentsComments are used in programming to make notes in your code for organization purposes and to help other programmers to understand your code. To write a comment in JS, simply type //Write your comment here!Everything followed by the // will be ignored by JS, and will not be read as code. The // operator is used for one-line comments only. To write a multiline comment, simply type /* Write your long multiline comment right here! */Everything in between the /* */ will be ignored by JS, and will not be read as code. VariablesI. VariablesIn JavaScript, variables are used to store data. (very similar to algebraic variables). Each variable must be named. These unique names are called identifiers. Identifiers can be short names (like x and y), or more descriptive names (age, sum, name). The general rules for constructing names for variables (unique identifiers) are:Names can contain letters, digits, underscores, and dollar signs.Names are case sensitive (hello and Hello are different variables)Reserved words (like JavaScript keywords) cannot be used as namesHere are some reserved words:breakdowhileforfunctionif/elsereturnswitchvarEx:var x = 5;var ytetawtwaie = “fadfaljdfl”;var HOLA = “hello”;var hola = true;To declare a variable, use the keyword var, followed by a variable identifier. Then use the assignment operator (=) to assign a certain value to the variable. OperatorsOperatorsMathJavaScript can be used to evaluate arithmetic operations.AdditionThe + operator is used to perform addition in JavaScript.Ex: 5+6; 118+3;11SubtractionThe – operator is used to perform subtraction in JS.Ex:6-5;134-3;31MultiplicationThe * operator is used to perform multiplication in JS.Ex:6*5;3012*4;48DivisionThe / operator is used to perform division in JS.Ex:10/5;236/6;6ModuloThe % operator is used to determine the remainder from a division problem in JS.Ex:6%5;139%6;3IncrementThe ++ is used to indicate an increment of 1 to an existing value.Ex: var i = 0;i++;console.log(i);1DecrementThe -- is used to indicate an increment of 1 to an existing value.Ex: var i = 1;i--;console.log(i);0AssignmentVariable AssignmentThe = operator is used to assign a value to a variable. Ex:var x = 5;x;5AdditionThe += operator is used to add a value to a variable and then assign that new value to the variable.Ex:var x = 2;var x += 5; (Same as var x = x + 5;)x;7SubtractionThe -= operator is used to subtract a value from a variable and then assign that new value to the variable.Ex:var x = 5;var x -= 2; (Same as var x = x - 2;)x;3MultiplicationThe *= operator is used to multiply a value by a variable and then assign that new value to the variable.Ex:var x = 2;var x *= 5; (Same as var x = x * 5;)x;10DivisionThe /= operator is used to divide a variable by a value and then assign that new value to the variable.Ex:var x = 10;var x /= 5; (Same as var x = x / 5;)x;2ModuloThe %= operator is used to divide a variable by a value and then assign the remainder of the division expression to the variable.Ex:var x = 12;var x %= 5; (Same as var x = x % 5;)x;2StringConcatenationThe + operator is used to add strings together, which is called concatenation of strings. Concatenation will always return a string. Ex:var x = “Hello”;x + “World”;“HelloWorld”LogicalEquality/InequalityThe == operator is used to test equality of two values. Ex: var x = 56;x == 7*8;truex == 57;falseThe === operator is used to test equality of values and types.Ex: var x = 5;x === “5”;falsex === 5;trueThe != operator is used to test inequality of two values.Ex: var x = 5;x != 5;falsex != 6;trueThe !== operator is used to test inequality of values and types.Ex:var x = 5;x !== “5”;truex !== 5;falseGreater/Less ThanThe > operator is used to test if a value is greater than another value.Ex: 5>4;trueThe < operator is used to test if a value is less than another value.Ex: 5<4;falseThe >= operator is used to test if a value is greater than or equal to another value.Ex: 5>=4;true5>=5;trueThe <= operator is used to test if a value is less than or equal to another value.Ex: 5<=4;false4<=4;trueAnd/Or The && operator is used to test if two conditions are true simultaneously. The condition will evaluate to true only if both conditions are true. Ex:if (4*5 == 20 && 3*4 ==15) {console.log(“Both statements are true”);}else if (4*5 == 20 && 3*4 ==12) {console.log(“Now, both statements are true”);}The second console.log statement will be executed, because both conditions are true, as opposed to the first condition, where only a single condition is true. The following lines will show the value of a condition depending on the value of both sides of the && operator. true && true -> truetrue && false -> falsefalse && true -> falsefalse && false -> falseThe || operator is used to test if at least one out of multiple conditions is true. The condition will evaluate to true when one condition is true. Ex:if (4*5 == 20 || 3*4 ==15) {console.log(“One statement is true”);}else if (4*5 == 21 || 3*4 ==13) {console.log(“Now, one statement is true”);}The first console.log statement will be executed, because at least one condition is true, as opposed to the second condition, where both conditions are false. The following lines will show the value of a condition depending on the value of both sides of the || operator. true || true -> truetrue || false -> truefalse || true -> truefalse || false -> falseData TypesData Types Data types are different types of expressions used in JavaScript. You will learn more about the array and object data types later in this lesson. NumbersEx: 1, 2, 456, 5432, 3232, 1214134134134134141, etc.StringsEx: “Hello World”, “John Doe”, ‘Computers’Strings must be enclosed in single/double quotations.BooleansEx: true, falseArraysEx: var x = [“hello”, “hi”, “hola”, “bonjour”]; ObjectsEx: var car = {type:"Fiat", model:500, color:"white"}; CONDITIONAL STATEMENTSIf/Elif/ElseIf/Elif/ElseJS uses if/elif/else statements to control the flow of code and execute specified blocks of code depending on if the condition is true or false.Ex:if (5>4) {console.log(“The statement is true”);}elif (5*6 == 40) {console.log(“The second statement is true”);}else {console.log(“The statements are false”);}The first line of the above example is testing if 5 is greater than 4. Since the expression is true, the following block of code encased in curly braces is executed. If the first if statement is false, the next condition is tested (elif means else if). If all the conditions are false, the else block will be executed. SwitchSwitchSwitch statements are used in the case of many conditions. Instead of writing multiple elif statements, a switch statement with multiple cases is used. Ex:var x = prompt(“What day is today?”);switch(x) {case “Sunday”:case “Saturday”:console.log(“It’s the weekend!”);break;case “Monday”:case “Tuesday”:case “Wednesday”:case “Thursday”:case “Friday”:default:console.log(“It’s not the weekend!”);break;}The switch statement above checks the value of the variable x. The variable x is any day of the week. Certain values of x will return certain strings. The expression within the parentheses after switch is the condition being tested. The strings after case are the values being checked. If one case is true, the following block of code is executed. At the end of each block of code, a break statement is required to exit the switch statement and to resume the code. ARRAYSArray BasicsI. ArraysAn array is used to store multiple values in a single variable. To create an array, make a variable using the var keyword, and then assign it to brackets, filled with the values of your choice. Commas must separate the values. Values in an array can be any data type (numbers, strings, booleans, objects, or even other arrays!). Ex: var array = [“val1”, “val2”, “val3”]; [0] [1] [2]The values in an array are numbered starting from 0; these numbers are called indices. The values can be accessed through their index, like so:array[0];“val1” array[2];“val3”To add elements to an array, simply assign a value to an index, using the notation above:Ex: array[3] = “val4”;console.log(array);[“val1”, “val2”, “val3”, “val4”];Arrays have many properties and methods to change and use them. Some array properties include the length and sort() properties. The length property will return the length (number of values) of the array.Ex: array.length;4The sort() property will sort the strings in an array in alphabetical order. Ex: var array = [“hello”, “goodbye”, “hola”, “bonjour”]array.sort();[“bonjour”, “goodbye”, “hello”, “hola”]Array MethodsAs aforementioned, arrays have many methods to change and use arrays. Here are some array methods that I will show you how to use. toString()/valueOf()join()pop()push()shift()unshift()splice()reverse()concat()slice()The toString() and valueOf() methods convert all the values in an array to a single string. Commas separate each value. Both of these methods do the same thing. Ex:array.toString();hello,goodbye,hola,bonjourarray.valueOf();hello,goodbye,hola,bonjourThe join() method is very similar to the two above methods; however, the separator may be specified. Ex:array.join(“ + ”);hello + goodbye + hola + bonjour The pop() method removes the last element of the array.Ex: array.pop();[“hello”, “goodbye”, “hola”]The push() method adds an element to the end of the array.Ex:array.push(“namaste”);[“hello” , “goodbye” , “hola” , “bonjour” , “namaste”]The shift() method removes the first element and shifts the remaining elements down a place.Ex:array.shift();[“goodbye” , “hola” , “bonjour”]The unshift() method adds an element to the first position and shifts the other elements up a place. Ex:array.unshift(“guten tag”);[“guten tag”, “hello” , “goodbye” , “hola” , “bonjour”]The splice() method adds elements to arrays. It takes a couple of parameters. The first parameter indicates the position to insert the new elements. The second parameter indicates how many elements should be removed. The following parameters are the new elements to be added. Ex:array.splice(2, 0, “namaste”);[“hello” , “goodbye” , “namaste”, “hola” , “bonjour”]array.splice(2, 1, “namaste”);[“hello” , “goodbye” , “namaste”, “bonjour”]The reverse() method simply reverses the order of the elements in an array.Ex:array.reverse();[“bonjour”, “hola”, “goodbye”, “hello”]The concat() method concatenates arrays, similarly to string concatenation. Ex:var array2 = [“namaste”, “guten tag”];array.concat(array2);[“hello” , “goodbye” , “hola” , “bonjour”, “namaste”, “guten tag”]The slice() method removes a section of the array and makes it into a new array.It takes two parameters. The first parameter indicates the starting point of the new array. The second parameter indicates the ending point of the new array.Ex:array.slice(2, 3);[“hello” , “goodbye”][“hola”, “bonjour”]LOOPSLoops are used in programming if you want to execute blocks of code multiple times with different valuesFor LoopsForFor loops are used when you know the number of iterations you wish to run the loop.Ex:for (i=0; i<3; i++) {console.log(i);}This block of code will print out:012The for loop above takes three parameters inside the parentheses. The first parameter sets the initial value of the variable being used in the for loop. The second parameter sets the duration of the loop (the loop will run as long as i is less than 3). The last parameter sets the change in the variable after each iteration (after the block of code is executed, i will increment by 1). A semicolon separates each parameter. For EachFor each loops are a version of for loops used to extract the values of each element in an object. You will learn what an object is later in the lesson.Ex:var sumAge;var object = {myAge: 16, herAge: 13, hisAge: 8};for each (var item in object) { //for every value in the variable object sumAge += item; //add that value to the variable sumAge}console.log(sum); // logs "37", which is 16 + 13 + 8The above example took each value of the object’s properties and added them to a variable called sum. Then it printed the sum of all the ages to the console. For InFor in loops are another version of for loops used to extract the property names of each element in an object. You will learn more about objects later in the lesson. Ex:var object = {Ishaan: “That’s me!”, Joe: “That’s a random guy!”, Bob: “Another random guy!”}; for (var name in object) {console.log("My name is ” + name);}/* Will return:“My name is Ishaan”“My name is Joe”“My name is Bob”*/While LoopsWhileWhile loops are used when the number of iterations is unknown. The loop will run until the specified condition becomes false. Ex:var i = 0;while (i < 10) {console.log(i);i++;}The above while loop will print:0123456789The while loop above takes one parameter inside the parentheses. The parameter identifies a condition. While the condition is true the following code block inside the curly braces will run. The loop prints the variable i in each iteration. After printing i, the variable i is then incremented by 1. The loop will continue to print out i, until i is no longer less than 10(the condition is false). Make sure that your while loop is not an infinite loop by incrementing i by 1 on each iteration. An infinite loop is a loop that will never end, and will eventually crash your computer. AVOID INFINITE LOOPS.Do-WhileIn some cases the condition in a while loop will have a condition that will always be false. However, you may want to the loop to execute a block of code before the while loop begins. This case is where a do-while loop is useful. Ex: var i = 10;do {console.log(“The while loop is always false”);}while(i > 15) {console.log(“The while loop ran”);}In the example above, the block of code between the set of curly braces after do will always run, regardless of the condition of the while loop. After the block of code is executed, the while loop condition is then executed; if true, the while loop will also run; however, if false, the while loop will be ignored by the computer. FUNCTIONSI. FunctionsFunctions in JavaScript are used execute a particular task.A JavaScript function is executed when it is called.Functions are very useful, because you can reuse code with different arguments, to produce different results. Ex:var helloWorld = function() {console.log(“Hello World”);}helloWorld();“Hello World”To declare a function use the var keyword and then an identifier to name your function. Assign that to function() {}. The code that the function must execute will be written between the curly braces. Some functions also take parameters, which go between the parentheses after the function keyword. To call a function, simply write the function’s name followed by parentheses(sometimes with a parameter) and ending with a semicolon.Ex: var myName = function(name) {console.log(“Hello, my name is “ + name);}myName(“Ishaan”);“Hello, my name is Ishaan”Functions will only run when they are called. Functions may be called within other functions, in JavaScript events, or simply in JavaScript statements. OBJECTSI. ObjectsObjects are simply variables with many properties and values. Arrays are a special type of object, that have numbered indices instead of property names. Objects have name:value pairs called properties. Some objects’ properties can be functions, which are known as methods. To declare an object, follow this syntax:var car = {make: “Bugatti”,model: “Veyron”,year: 2015,color: “black”,drive: function() {console.log(“Vroom Vroom”);}}To access properties in an object, follow this syntax:car.make;“Bugatti”car[“make”];“Bugatti”To call methods in an object, follow this syntax:car.drive();SNAKE Introduction:After learning the basics of JavaScript, we will now be creating a simple arcade game using our learned knowledge. This game is a re-creation of the classic game Snake, where a snake will move around the screen, controlled by the user, growing as it eats more food. This program tutorial will reinforce concepts previously learned in the lessons, while also teaching additional JavaScript skills, such as:ScopeHTML CanvasAdvanced Arrays/ObjectsIntervals and Time Steps Keypress/Onclick/Onload EventsTo start off the project, I will show you how to create a JavaScript file, and how to link it to an HTML file. Open a text-editor where you are going to be editing your code (Notepad++, Brackets, TextWrangler, etc.). Next, open two blank documents and save them as snake.html and snake.js respectively. In the HTML file we will set up the basic HTML outline, with a head, body, title, header, etc. Follow this code to create a basic HTML file. <html> <head> <title>Snake!</title> </head> <body> <h1>Snake!</h1> </body></html>Next we will need to link our JavaScript file to our HTML file, using a <script> tag. Place this tag inside the head tag of the HTML, where (if you recall from the HTML tutorial) information about the webpage, such as title, meta data, and links to JS/CSS go.<head> <title>Snake!</title> <script type=“text/javascript” src=“snake.js”></script></head>Now we will be creating the HTML canvas, where our game will take place. The HTML canvas is a very powerful element, and can be used for many programs. Our snake object and food will be drawn on the canvas. To create the canvas, we will use the <canvas> tag in our HTML body. We also need to give our canvas properties, such as height, width, and a border (so we are able to see the shape of the canvas). We also want to give our canvas an i.d., so we can access it through JavaScript later. <body> <h1>Snake!</h1> <canvas height= “500” width = “500” style=“border: 1px solid black" id= “myCanvas”></canvas></body>If you load your HTML file in the browser, you should now be able to see a giant square on your page. One thing to keep in mind about canvases is that the coordinate system on them is different from that of your math class. The x-value increases left to right, like the Cartesian plane; however, the y-value increases top to bottom, as opposed to bottom to top, like the Cartesian plane. Use this diagram as reference: x(0, 0)Canvas yScope, Initial FunctionsAfter setting up our HTML file, we will now begin to edit the JavaScript file for our snake program. Open up the snake.js file. To draw on the canvas, we will need to use two variables to store the canvas and the drawing tool. We want these variables to be able to be accessed by the entire JavaScript file. This means that we need to create something called a global variable. A variable declared outside a function, becomes global. A global variable has global scope: all scripts and functions on a web page can access it.?Variables declared within a JavaScript function, become local to the function. Local variables have local scope: they can only be accessed within the function. Local variables are created when a function starts, and deleted when the function is completed.Our canvas needs to be accessed by all the functions in our code to be able to draw the snake and the food, so it must be a global variable. We will now declare our global variables at the top of the page. Remember how to declare variables? Use the var keyword followed by the name, assignment operator, and value. We will declare the following two variables. Canvas stores the HTML canvas, while context allows us to draw on the canvas. var canvas;var context;Notice, I haven’t defined the variables canvas and context at the moment, because they will be defined in the next function, which is called when the page loads. We will now create an initial function that will load our canvas, draw things on the canvas, and call all necessary functions. Next, we want to create the aforementioned function. I will name it initial, because it is the first function called (when page loads). You may call it whatever you wish; however, it is strongly recommended that the name describe the purpose of the function. Do you recall how to create and define a function? We use the var keyword again, followed by the function name, assignment operator, and function() {}.var initial = function() {};Inside this function we want to define the canvas and context variables. The canvas variable will store the HTML canvas element, so we need to use one of the first JavaScript techniques taught in this lesson: document.getElementById. We used the myCanvas id for our canvas, so the canvas variable should be defined as follows:var initial = function() {canvas = document.getElementById(“myCanvas”);};Notice the lack of the var keyword. Since we defined canvas as a global variable outside the initial function using the var keyword, we do not need to use it again. If we use the var keyword, we create a local variable inside the function, which can only be used by other statements inside that function. Next, we need to define the context variable, which allows to draw on a canvas that is 2-dimensional in nature. var initial = function() {canvas = document.getElementById(“myCanvas”);context = canvas.getContext(“2d”);};After creating this initial function, we need to call it when the page loads. This is an example of an HTML event being modified by JavaScript. To call initial() on the page load we need to go back to the HTML file. In this file, we need to find the body element, because the <body> tag has all the content of the webpage. We want to use the onload event to call our initial function. To do this, follow this syntax: <body onload=“initial();”> <h1>Snake!</h1> <canvas height= “500” width = “500” style=“border: 1px solid black" id= “myCanvas”></canvas></body>Everytime the page loads our initial function is called. Currently, you shouldn’t be able to see any visible changes on your page, since our initial() function doesn’t do anything at the moment. Next, we will begin to draw shapes on our canvas, which will eventually become our snake object and food. Creating the Food:To draw a rectangle on a canvas, follow this syntax:context.fillStyle = “blue”; context.fillRect(0, 0, 30, 30);The first line defines the color of our rectangle, while the second statement defines the positioning and size of our rectangle. fillRect takes four parameters: the first two are the (x, y) coordinates of the top left corner of the rectangle on the canvas, and the last two parameters are the width and height of the rectangle respectively. If the above lines are placed inside the initial function and the page is refreshed, you should now be able to see a blue square in the top left corner of the canvas. Since we now know how to draw rectangles on the canvas, we will proceed to drawing the food on the canvas. The food will need five global variables associated with it: foodPosX, foodPosY, foodWidth, foodHeight, and foodColor. We will also need a new function to create new food on the canvas, when needed. Also, our food will need to be placed in random spots across the canvas, instead of set coordinates. First we will create the global variables for our food at the top of the file, under the canvas and context variables. We want the foodPosX and foodPosY variables to be defined inside the new food function, ensuring that the food will have a new set of coordinates each time the function is called. We will create the global variables like so: var foodPosX;var foodPosY;var foodWidth = 10;var foodHeight = 10;var foodColor = “red”;You may choose any values for foodWidth and foodHeight, as long as the size is reasonable. The color of your food may also be any acceptable CSS color. We currently have no values defined for the foodPosX and foodPosY, so we need to define them inside the new food function. To create the function follow the same syntax, as the initial function: var newFood() {foodPosX = Math.floor(Math.random() * (canvas.width – foodWidth));foodPosY = Math.floor(Math.random() * (canvas.height – foodHeight));}Math.floor() and Math.random() are two new functions that are very useful in JavaScript. Math.floor() will round a number down to the nearest integer. Math.random() will return a random number between 0 and 1. We have multiplied Math.random by the canvas.width-foodWidth and canvas.height-foodHeight to give us random numbers from 0 to the edges of the canvas, while also preventing the food to be cut off the edge. Ex. Math.floor(4.5) -> 4Math.floor(4.8) -> 4Math.random() -> 0.4563229Now we need to draw the food on the canvas. To do so, we can go back to our initial function. We need to call our newFood() function inside the initial function to ensure that the (x,y) coordinates of the food are set to random numbers, before drawing the food. Follow this syntax to draw the food on the canvas. We can remove the code for drawing the blue square, as that was just an example.var initial = function() {canvas = document.getElementById('myCanvas');context = canvas.getContext('2d');newFood();context.fillStyle = foodColor; context.fillRect(foodPosX, foodPosY, foodWidth, foodHeight);}Now every time you refresh your page, the food should appear in random positions across the canvas. After creating our food, we must begin to draw the snake object. As we discussed in the tutorial, and object is a special type variable that holds multiple pieces of data, as opposed to one. Additionally, the data is stored in name:value pairs known as properties. Our snake is an element with multiple pieces that will continue to grow. Therefore we will use an array to store the entire snake, while each part of its body will be an object in that array. Our snake will only need two properties, x and y coordinates. This will allow us to keep track of our snake’s position, for later use. To create the snake object, we will use the same syntax as we learned in the tutorial; however, now we must make sure the object is an element in the array. We will define the snake objects inside the initial function. Creating the Snake Object:First we must create a blank global snake array to store our snake objects. In addition to creating this variable, we will make the same global variables that we made for the food. var snake = [];var snakePosX = 100;var snakePosY = 100;var snakeWidth = 10;var snakeHeight = 10;var snakeColor = “green”;These variables are defined at the top of the file, under the global variables for the food. Now we need to define each element in the array as an object, and then draw the snake. Since we will now be drawing the snake and the food, it is a good idea to make a draw() function, which will hold the statements for drawing the food and the snake. This is how to create snake objects in an array (there will only be one object in our array at the moment) and make a draw() function. We want to call this draw() function inside our initial() function, so the snake and food are drawn when the page loads. We use a for loop to loop through each element in the snake array, and define it as an object. var initial = function() {canvas = document.getElementById('myCanvas');context = canvas.getContext('2d');newFood();for (var i = 0; i < 1; i++) {snake[i] = {};snake[i].x = snakePosX;snake[i].y = snakePosY;}draw();}var draw = function() {for (var i = 0; i < 1; i++) {context.fillStyle = snakeColor; context.fillRect(snake[i].x, snake[i].y, snakeWidth, snakeHeight);}context.fillStyle = foodColor; context.fillRect(foodPosX, foodPosY, foodWidth, foodHeight);}Notice the use of the var keyword when defining the loop variable i. This is because we want to keep the value of i local to each loop, instead of making a global variable i, which will be accessed by all the loops. Refreshing the page now should result in a green square (snake) appearing at (100, 100) and a red square (food) appearing at a random position on the canvas. Moving the Snake:Before adding more elements to the snake array, we want to move the snake around using the keys W, A, S, and D. To do so we must utilize another HTML event: keypress. First we must create a function that will check if a key is pressed on the keyboard (event), and will react depending on which key is pressed. This function will move the snake left when A is pressed, right when D is pressed, up when W is pressed, and down when S is pressed. The function will look like this:var keyPress = function(evt) {if (evt.keyCode == 119) {snake[0].y -= snakeHeight; draw(); } else if (evt.keyCode == 115) { snake[0].y += snakeHeight; draw(); } else if (evt.keyCode == 97) { snake[0].x -= snakeWidth; draw(); } else if (evt.keyCode == 100) { snake[0].x += snakeWidth; draw();}}The function has a parameter that is the keypress event. Each key on the keyboard has a specific keyCode, which are the numbers you notice in the if statements. W has a keyCode value of 119, S of 115, A of 97, and D of 100. You can find the full list of keyCode values at . If we press the W key, the snake’s y coordinate will decrease by the height of the snake, if we press the S key, the snake’s y coordinate will increase by the height of the snake, if we press the A key the snake’s x coordinate will decrease by the width of the snake, and lastly if we press the D key the snake’s x coordinate will increase by the width of the snake. Notice that we are calling the draw function after each key is pressed. This is because JavaScript must be instructed to redraw the snake object each time the keys are pressed, so the snake[0].x and snake[0].y are updated. To call this function we need to add a JavaScript statement called addEventListener. This function allows JavaScript to identify an event occurring in the HTML document. In our case, we want JavaScript to call our keypress function when the W, A, S, or D keys are pressed, so we would add the following statement at the bottom of our initial function: document.addEventListener(“keypress”, keyPress);This function takes two parameters, the event and the function to be called. We want JavaScript to “listen” for the “keypress” event and to call the keyPress function. A refresh of the webpage will now result in you being able to move the green snake around using the W, A, S, and D keys. However, you will notice that the snake is being redrawn over and over, but its previous position is not being erased, resulting in a long path of green squares. To solve the issue, we need to clear the canvas each time the keys are pressed, and then draw the snake object and food. To do this we need to add two lines to the top of the draw() function that will draw a white rectangle over the entire canvas each time the draw() function is called. context.fillStyle = "white";context.fillRect(0, 0, canvas.width, canvas.height);Now save the file and refresh your webpage once again, and you will notice that the snake square now moves without the green path behind it. We are now halfway through with our snake tutorial! All we have left is making the snake grow, eat, and die. Adding an Interval:Next, we want to add a JavaScript called interval. In the classic snake game, the snake will move continuously in one direction until a different key is pressed to move the snake in a new direction. To do this we must add an interval statement to our code which will call the draw() function every few milliseconds or seconds, this way we do not need to call the draw() function each time we press a key. First create two new global variables: step and interval. Step will contain the function that calls the draw() function on an interval, and interval will contain a number that will be the duration of the interval in milliseconds. We will set the interval to 50 milliseconds. The step variable will be defined when we set the interval function in the initial() function. var step;var interval = 50;Next we need to set the interval to call the draw() function on an interval. The setInterval function will take two parameters, the first being the function be called, and the second being the duration of the interval in milliseconds (we already made a variable for this!). We will place this statement inside the initial function where we originally called the draw() function. step = setInterval(“draw();”, interval);Animating the Snake:Next we need to create a new function that will animate the snake, and we need to modify the keyPress function to adapt to the new interval we have set. First we will create a global variable that stores the direction of the moving snake, called snakeDirection. It will be defined as “still” at this moment, because initially the snake is not moving. var snakeDirection = “still”;Now we need to create an animateSnake() function that will control the movement of our snake (basically what our keyPress function currently does). After creating this function we will change our keyPress function to adapt to this change. Our animateSnake() function will change our snake’s (x, y) coordinates depending on what the value of snakeDirection is: var animateSnake = function() {if(snakeDirection === "up") { snake[0].y -= snakeHeight; } else if(snakeDirection === "down") { snake[0].y += snakeHeight; } else if(snakeDirection === "right") { snake[0].x += snakeWidth; } else if(snakeDirection === "left") { snake[0].x -= snakeWidth; }}This is very similar to our original keyPress function, which now needs to be modified. If you have noticed, the variable snakeDirection has never been defined to string values of “up”, “down”, “left”, and “right”. We now need to use the keyPress function to define snakeDirection. When W is pressed, we want snakeDirection to be set to “up”, so the animate function will execute. Our new keyPress function will look something like this: var keyPress = function(evt) {if (evt.keyCode == 119) {snakeDirection = “up”; } else if (evt.keyCode == 115) { snakeDirection = “down”; } else if (evt.keyCode == 97) { snakeDirection = “left”; } else if (evt.keyCode == 100) { snakeDirection = “right”;}}Notice how we no longer call the draw() function. This is because the draw() function is being called on the interval every 50 milliseconds, so any movement will be automatically reflected on the canvas. The last step of this part is to call the animateSnake() function. Remember how our draw() function is called on an interval? This means that everything inside the function definition of draw() will be executed on an interval. That means that we need to call animateSnake() inside the draw() function, under the lines where the canvas is cleared:animateSnake();Eating the Food:The next step in this tutorial is checking to see if the snake has eaten the food. When the snake eats the food we want new food to appear in another place (we will make the snake grow later). To do so, we will create a simple function called intersection that will check if the (x, y) coordinates of the food and snake are intersecting, and then will draw a new food square elsewhere on the canvas. This function will contain an if statement to check for intersection, and then will call the newFood() function to draw the new food square in a random position:To check for intersection, we need to check if 4 things are true simultaneously:The snake’s x coordinate is less than the food’s x coordinate plus the food’s width.The food’s x coordinate is less than the snake’s x coordinate plus the snake’s width. The snake’s y coordinate is less than the food’s y coordinate plus the food’s height. The food’s y coordinate is less than the snake’s y coordinate plus the snake’s height. These four conditions, if all true, mean that the snake is touching the food. Now we need to make a function. We will use the && operator when checking the conditions, because we want all of them to be true at the same time. If they are touching, we want to draw a new food square, which goes back to the newFood() function, one of the first functions that we defined:var intersection = function() {if (snake[0].x < foodPosX + foodWidth && foodPosX < snake[0].x + snakeWidth && snake[0].y < foodPosY + foodHeight && foodPosY < snake[0].y + snakeHeight) {newFood();}}Now we need to call the intersection function in our code. Since we want JavaScript to be constantly checking if our snake is intersecting the food, we must call the intersection function inside the draw function, because the draw function is being constantly called. Place the following statement under the call of the animateSnake() function. intersection();Now your snake should be able to eat the food, and a new food should appear in a new random position on the canvas. Adding Walls: If you have been experimenting with your program so far, you may have realized that the snake is able to leave the canvas and disappear. We need to solve this issue, by making the snake die when it hits the wall. We can create a simple function to check for this situation. We want to snake to die if either: the snake’s x coordinate < 0, the snake’s x coordinate > width of the canvas, the snake’s y coordinate < 0, or the snake’s y coordinate is > height of the canvas. Remember to use the || operator, because only one condition needs to be true for our snake to die. Once this condition is evaluated as true, we want to reset our entire game. This involves calling our initial() function again to return the snake to its starting position. We also want the user to know that they have died, so we use an alert to output “You died!” to the window. If these are the only statements that you have included in your function, the snake will get progressively faster and won’t stop each time the snake hits a wall. This is because our original interval is still set and we have set a new interval on top of it by calling the initial function again. Also, our snakeDirection is still set to the last direction it was going, so the animate function will continue to run. To fix this we must use a function called clearInterval to clear our previous interval and then reset it by calling initial(). The clearInterval takes one parameter, which is the variable we set the original interval to (step). We also must give snakeDirection a value that animateSnake() will not execute based off of. We can give snakeDirection the value of “still”, because that was our initial value. Our function should look like this:var checkWalls = function() {if (snake[0].x < 0 || snake[0].x > canvas.width - snakeWidth || snake[0].y < 0 || snake[0].y > canvas.height - snakeHeight) {alert("You died!"); snakeDirection = "still";clearInterval(step);initial();}}Make sure to call the checkWalls() inside your draw() function. Growing the Snake: Now, we want our snake to grow when it eats food. Up till this point we have been using a snake array with only one element, so our snake is just one square. We need to add snake elements to the array each time the snake eats the food. We also need to instruct JavaScript on how to draw a snake with multiple objects. So first we will create a global variable called snakeLength that will control the number of elements in our snake array. var snakeLength = 1;Next we will modify the code that assigns x and y attributes to a snake object, because currently all elements in the snake array have the same x and y coordinate. In your initial function change the for loop to this:for (var i = 0; i < snakeLength; i++) {snake[i] = {};snake[i].x = snakePosX – (i * snakeWidth);snake[i].y = snakePosY;}This will draw each new snake element behind the previous one. We also need to change the for loop in the draw() function to go up till the snakeLength, instead of 1:for (var i = 0; i < snakeLength; i++) {context.fillStyle = snakeColor; context.fillRect(snake[i].x, snake[i].y, snakeWidth, snakeHeight);}Now we need to make the new snake elements to move along with the first snake element, because currently only the first snake object moves around the canvas. To do this we need to assign (x, y) coordinates to all the objects after the first. We will do this in the animateSnake() function. When the snake is moving, the snake objects’ (x, y) coordinates will be equal to the (x, y) coordinates of the previous object in the previous time step. This creates a follow the leader effect. Follow this syntax at the top of the animateSnake() function:if (snakeDirection != "still") {for (var i = snakeLength - 1; i > 0; i--) { snake[i].x = snake[i-1].x; snake[i].y = snake[i-1].y; } }We also need to instruct JavaScript in creating a new object when the food is eaten. We will do this at the top of the if statement in the intersection() function: snakeLength++ snake[snakeLength - 1] = {}; snake[snakeLength - 1].x = snake[snakeLength-2].x; snake[snakeLength - 1].y = snake[snakeLength-2].y;The above code will create a new object in the last spot of the snake array, and will give it the (x, y) coordinates of the previous snake element, effectively adding a new object to the end of the snake. Lastly, we need to reset the value of snakeLength when the user dies. So in the checkWalls() function we need to set snakeLength to 2 or whatever default value you wish. snakeLength = 2;Make sure you place the above statement before calling the initial() function, otherwise the snakeLength will reset after the canvas is drawn, which is not what we want to occur. Now by refreshing your HTML webpage you should be able to play your snake game!!!!! The only things left are small tidbits, such as making a score, killing the snake when it hits itself, and using CSS to design the page. Take a break! Great job so far! You have made your first fully functional JavaScript project. Congrats!Score:Now we will implement a score element to our game, so users will be notified of their score once the game ends.First we will create a variable that will store the value of the score, and will increment each time the snake grows. Additionally, this score will reset each time the snake dies. Declare a new global variable called score, like so:var score = 0;Next, we need to increment score by 1, each time the snake eats a piece of food. So, inside our intersection() function, we can add the following code at the bottom of the if statement inside the intersection() function to increment the score variable: score++;Now we need to output the score in an alert when the snake hits a wall, and then subsequently reset the score variable back to zero, so when the user plays a new game they will have a new score. To do this, we will edit our current alert in the checkWalls() function to say this: alert(“You died! Score: ” + score);Then, we need to reset score to zero, right below where we reset snakeLength back to 2 in the checkWalls() function.score = 0; Lastly, we can display the score on the canvas, so the user will know their score throughout playing the game. To do this we will draw text on the canvas in the top right corner, inside the draw() function. Follow this syntax:context.fillStyle = "black"; context.fillText("Score: " + score, canvas.width - 50, 20) ;The first line defines the color of the text. The second line defines the content and position of the text. The fillText() function takes three parameters: the text to display, the x-coordinate of the text, and the y-coordinate of the text. Checking for Self Hit:The next aspect of our game we need to add is making the snake die if it runs into itself. To do this we will create a function that will loop through the x and y coordinates of each snake object and check to see if they are intersecting at any time step. If they are intersecting, the game will reset (same code as the checkWalls() function). First create a function called checkSelfHit() and inside write two for loops that will run through each object in the array’s x and y coordinates. var checkSelfHit = function() {for (var i = 0; i < snakeLength; i++) {for (var j = 0; j < snakeLength; j++) {}}}Inside the second for loop we will write an if statement that will check if the coordinates of two objects in the array are the same, and if they are we want to reset the game, because the snake is dead:if (snake[i].x == snake[j].x && snake[i].y && i!=j) {alert("You died! Score: " + score); snakeDirection = "still"; clearInterval(step); snakeLength = 3; score = 0; initial();}Notice the inclusion of the i!=j in the if statement. This ensures that the loop will be checking two different snake objects and not the same snake object. We will now go to the last aspect of our game: CSS.CSS:Our game is fully complete! Now we can design our webpage to make it look a little nicer. First we need to make a CSS file, called snake.css, and link our CSS to the HTML file. In the head of the HTML file, we can add the following code:<link type= “text/css” href= “snake.css” rel= “stylesheet” />Now, if we go to the CSS file, we will add styles to the canvas, header, and body. First, we will center our header on the page, like so:h1 {text-align: center;}Next, we can also center the canvas. Since the canvas is not a text element, we cannot use text-align. We must instead use margin, and display. To center the canvas we can use the following styles:#myCanvas {display: block;margin: auto;}Lastly, if you wish, we can add a background color to the body of the webpage. I will add a blue background to my snake game, which can be done, like so:body {background-color: #397eb9;}Congratulations, you have now completed all aspects of your snake program, from basic functionality to a CSS design! Feel free to add more aspects to your game, or change up the design. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download