├── .gitignore ├── Ch01_Programming_JS_jsBin ├── chapter1.md └── listing1.01.js ├── Ch02_Variables ├── chapter2.md ├── listing2.01.js ├── listing2.02.js ├── listing2.03.js ├── listing2.04.js ├── listing2.05.js ├── listing2.06.js ├── listing2.07.js ├── listing2.08.js └── listing2.09.js ├── Ch03_Objects ├── chapter3.md ├── listing3.01.js ├── listing3.02.js ├── listing3.03.js ├── listing3.04.js ├── listing3.05.js ├── listing3.06.js ├── listing3.07.js ├── listing3.08.js ├── listing3.09.js ├── listing3.10.js ├── listing3.11.js ├── listing3.12.js ├── listing3.13.js ├── listing3.14.js ├── listing3.15.js └── listing3.16.js ├── Ch04_Functions ├── chapter4.md ├── listing4.01.js ├── listing4.02.js ├── listing4.03.js ├── listing4.04.js ├── listing4.05.js ├── listing4.06.js ├── listing4.07.js ├── listing4.08.js ├── listing4.09.js ├── listing4.10.js ├── listing4.11.js ├── listing4.12.js ├── listing4.13.js └── listing4.14.js ├── Ch05_Arguments ├── chapter5.md ├── listing5.01.js ├── listing5.02.js ├── listing5.03.js ├── listing5.04.js ├── listing5.05.js ├── listing5.06.js ├── listing5.07.js ├── listing5.08.js ├── listing5.09.js ├── listing5.10.js ├── listing5.11.js ├── listing5.12.js ├── listing5.13.js └── listing5.14.js ├── Ch06_Return_values ├── chapter6.md ├── listing6.01.js ├── listing6.02.js ├── listing6.03.js ├── listing6.04.js ├── listing6.05.js ├── listing6.06.js ├── listing6.07.js ├── listing6.08.js ├── listing6.09.js └── listing6.10.js ├── Ch07_Object_arguments ├── chapter7.md ├── listing7.01.js ├── listing7.02.js ├── listing7.03.js ├── listing7.04.js ├── listing7.05.js ├── listing7.06.js ├── listing7.07.js ├── listing7.08.js ├── listing7.09.js ├── listing7.10.js └── listing7.11.js ├── Ch08_Arrays ├── chapter8.md ├── listing8.01.js ├── listing8.02.js ├── listing8.03.js ├── listing8.04.js ├── listing8.05.js ├── listing8.06.js ├── listing8.07.js ├── listing8.08.js ├── listing8.09.js ├── listing8.10.js ├── listing8.11.js ├── listing8.12.js └── listing8.13.js ├── Ch09_Constructors ├── chapter9.md ├── listing9.01.js ├── listing9.02.js ├── listing9.03.js ├── listing9.04.js ├── listing9.05.js ├── listing9.06.js ├── listing9.07.js ├── listing9.08.js ├── listing9.09.js ├── listing9.10.js ├── listing9.11.js └── listing9.12.js ├── Ch10_Bracket_notation ├── chapter10.md ├── listing10.01.js ├── listing10.02.js ├── listing10.03.js ├── listing10.04.js ├── listing10.05.js ├── listing10.06.js ├── listing10.07.js ├── listing10.08.js ├── listing10.09.js ├── listing10.10.js ├── listing10.11.js ├── listing10.12_10.13.js └── listing10.14.js ├── Ch11_Scope ├── chapter11.md ├── listing11.01.js ├── listing11.02.js ├── listing11.03.js ├── listing11.04.js ├── listing11.05.js ├── listing11.06.js ├── listing11.07.js ├── listing11.08.js ├── listing11.09.js ├── listing11.10.js ├── listing11.11.js ├── listing11.12.js ├── listing11.13.js ├── listing11.14.js ├── listing11.15.js ├── listing11.16.js ├── listing11.17.js └── listing11.18.js ├── Ch12_Conditions ├── chapter12.md ├── listing12.01.js ├── listing12.02.js ├── listing12.03.js ├── listing12.04.js ├── listing12.05.js ├── listing12.06.js ├── listing12.07.js └── listing12.08.js ├── Ch13_Modules ├── between.js ├── chapter13.md ├── listing13.01.html ├── listing13.02.js ├── listing13.03.html ├── listing13.04.js ├── listing13.05.html ├── listing13.06.js ├── listing13.07.html ├── listing13.08.js ├── listing13.09.html ├── listing13.10.js ├── listing13.11.js ├── listing13.12.js ├── listing13.13.html ├── listing13.14.js ├── listing13.15.js ├── listing13.16.js ├── listing13.17.html ├── listing13.18.js ├── listing13.19.js └── listing13.20.js ├── Ch14_Models ├── TheSparrow.html ├── TheSparrow.js ├── TheSparrowData.js ├── chapter14.md ├── listing14.01.js ├── listing14.02.html ├── listing14.03.js ├── listing14.04.js ├── listing14.05.js ├── listing14.06.js ├── listing14.07.js └── listing14.08.html ├── Ch15_Views ├── Listing 15.05.js ├── Listing15.01.js ├── Listing15.02.html ├── Listing15.03.js ├── Listing15.04.js ├── Listing15.06.js ├── Listing15.07.js ├── Listing15.08.js └── chapter15.md ├── Ch16_Controllers ├── Listing16.12.js ├── chapter16.md ├── listing16.01.js ├── listing16.02.html ├── listing16.03.js ├── listing16.11.html └── listings16.04to16.10.js ├── Ch17_HTML ├── chapter17.md ├── listing17.01.html ├── listing17.02.html ├── listing17.03.html ├── listing17.04.js ├── listing17.05.html ├── listing17.06.js ├── listing17.07.js ├── listing17.08.js ├── listing17.09.js ├── listing17.10.css └── listing17.11.js ├── Ch18_Controls ├── chapter18.md ├── listing18.01.html ├── listing18.02.js ├── listing18.03.html ├── listing18.04.js ├── listing18.05.js ├── listing18.06.html ├── listing18.07.html ├── listing18.08.js ├── listing18.09.js ├── theCrypt.html └── theCrypt.js ├── Ch19_Templates ├── chapter19.md ├── listing19.01.html ├── listing19.02.js ├── listing19.03.js ├── listing19.04.js ├── listing19.05.js ├── listing19.06.js ├── listing19.07.js ├── listing19.08.js ├── listing19.09.js ├── listing19.10.js ├── listing19.11.html ├── listing19.12.js ├── listing19.13.html ├── listing19.14.js ├── listing19.15.js └── listing19.16.js ├── Ch20_XHR ├── chapter20.md ├── listing20.01.js ├── listing20.02.js ├── listing20.03.js ├── listing20.04.js ├── listing20.05.html ├── listing20.06.js ├── listing20.07.json ├── listing20.08.js ├── listing20.09.js ├── listing20.10.html └── listing20.11.js ├── Ch21_Conclusion ├── TheCrypt │ ├── css │ │ └── theCrypt.css │ ├── img │ │ ├── rock2.jpg │ │ └── sand2.jpg │ ├── js │ │ ├── commands.js │ │ ├── gameController.js │ │ ├── mapManager.js │ │ ├── messageView.js │ │ ├── place.js │ │ ├── placeView.js │ │ ├── player.js │ │ ├── playerView.js │ │ └── template.js │ ├── maps │ │ └── TheDarkHouse.js │ └── theCrypt.html └── chapter21.md ├── Ch22_Node ├── between.js ├── chapter22.md ├── fruit.js ├── hello.js ├── jahvers-crypt │ ├── lib │ │ ├── game.js │ │ ├── mapBuilder.js │ │ ├── place.js │ │ ├── player.js │ │ └── playerGame.js │ ├── maps │ │ └── theDarkHouse.json │ └── replTest │ │ └── playerGameTest.js ├── multifruit.js ├── multifruitWhile.js ├── quiz.js └── quiz2.js ├── Ch23_Express ├── TheCrypt │ ├── gameServer.js │ ├── lib │ │ ├── game.js │ │ ├── mapBuilder.js │ │ ├── place.js │ │ ├── player.js │ │ └── playerGame.js │ ├── maps │ │ └── theDarkHouse.json │ ├── package.json │ └── public │ │ ├── css │ │ └── theCrypt.css │ │ ├── img │ │ ├── rock.jpg │ │ └── sand.jpg │ │ ├── jahvers-crypt.html │ │ └── js │ │ ├── commands.js │ │ ├── dataLoader-xhr.js │ │ ├── gameController.js │ │ ├── messageView.js │ │ ├── placeView.js │ │ ├── playerView.js │ │ └── templates.js ├── chapter23.md └── webserver │ ├── fitnessServer.js │ ├── hello.js │ ├── package.json │ ├── public │ ├── adventure.html │ ├── client-server-GET.png │ ├── client-server.html │ ├── fitnessData.html │ ├── index.html │ ├── js │ │ └── xhrPost.js │ └── moon.html │ ├── static.js │ └── threeRoutes.js ├── Ch24_Polling ├── HighFives_XHR │ ├── auctionApp.js │ ├── package.json │ └── public │ │ ├── auction.css │ │ ├── auction.html │ │ └── auction.js └── TheCrypt │ ├── gameServer.js │ ├── lib │ ├── game.js │ ├── gameManager.js │ ├── mapBuilder.js │ ├── place.js │ ├── player.js │ └── playerGame.js │ ├── maps │ └── theDarkHouse.json │ ├── package.json │ └── public │ ├── css │ └── theCrypt.css │ ├── img │ ├── rock.jpg │ └── sand.jpg │ ├── jahvers-crypt-xhr.html │ └── js │ ├── commands.js │ ├── dataLoader-xhr.js │ ├── gameController.js │ ├── mainView.js │ ├── messageView.js │ ├── placeView.js │ ├── playerView.js │ ├── startGame.js │ └── templates.js ├── Ch25_Sockets ├── HighFives_Sockets │ ├── auctionApp.js │ ├── package.json │ └── public │ │ ├── auction.css │ │ ├── auction.html │ │ └── auction.js ├── HighFives_SocketsRooms │ ├── auctionApp.js │ ├── package.json │ └── public │ │ ├── auction.css │ │ ├── auction.html │ │ └── auction.js └── TheCrypt │ ├── gameServer.js │ ├── lib │ ├── game.js │ ├── gameManager.js │ ├── mapBuilder.js │ ├── place.js │ ├── player.js │ ├── playerGame.js │ └── socketManager.js │ ├── maps │ └── theDarkHouse.json │ ├── package.json │ └── public │ ├── css │ └── theCrypt.css │ ├── img │ ├── rock.jpg │ └── sand.jpg │ ├── jahvers-crypt-socketio.html │ └── js │ ├── commands.js │ ├── dataLoader-socketio.js │ ├── gameController.js │ ├── mainView.js │ ├── messageView.js │ ├── placeView.js │ ├── playerView.js │ ├── startGame.js │ └── templates.js ├── README.md ├── js_next ├── README.md ├── listing2.10.js ├── listing2.11.js ├── listing2.12.js ├── listing3.17.js ├── listing3.18.js ├── listing3.19.js ├── listing3.20.js ├── listing4.15.js ├── listing4.16.js ├── listing4.17.js ├── listing5.15.js ├── listing5.16.js ├── listing5.17.js ├── listing5.18.js ├── listing5.19.js ├── listing6.11.js ├── listing6.12.js ├── listing6.13.js ├── listing6.14.js ├── listing7.12.js ├── listing7.13.js ├── listing7.14.js └── listing7.15.js └── projects └── theCrypt_Node ├── api └── index.js ├── index.js ├── lib ├── game.js ├── gameCache.js ├── gameController.js ├── mapBuilder.js ├── place.js └── player.js ├── maps └── theDarkHouse.json ├── package.json └── public ├── css └── theCrypt.css ├── img ├── rock.jpg └── sand.jpg ├── js ├── commands.js ├── dataLoader.js ├── gameController.js ├── messageView.js ├── placeView.js ├── playerView.js └── templates.js ├── maps └── TheDarkHouse.js └── theCrypt.html /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | .idea/ -------------------------------------------------------------------------------- /Ch01_Programming_JS_jsBin/chapter1.md: -------------------------------------------------------------------------------- 1 | # Programming, JavaScript and jsBin 2 | 3 | ### Using console.log 4 | [JS Bin: Listing 1.01](http://jsbin.com/mujepu/edit?js,console) - mujepu 5 | ```javascript 6 | /* Get Programming with JavaScript 7 | * Listing 1.01 8 | * Using console.log to display information 9 | */ 10 | 11 | console.log("Hello World!"); 12 | 13 | 14 | 15 | /* Further Adventures 16 | * 17 | * 1) Change the text between the parentheses. 18 | * 19 | * 2) Click Run on the console to run the 20 | * program again. 21 | * 22 | * 3) Add your own console.log statement 23 | * to the program, so there are two. 24 | * Don't forget the semicolon. 25 | * 26 | * 4) Click Run. 27 | * 28 | */ 29 | ``` 30 | -------------------------------------------------------------------------------- /Ch01_Programming_JS_jsBin/listing1.01.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 1.01 3 | * Using console.log to display information 4 | */ 5 | 6 | console.log("Hello World!"); 7 | 8 | 9 | 10 | /* Further Adventures 11 | * 12 | * 1) Change the text between the parentheses. 13 | * 14 | * 2) Click Run on the console to run the 15 | * program again. 16 | * 17 | * 3) Add your own console.log statement 18 | * to the program, so there are two. 19 | * Don't forget the semicolon. 20 | * 21 | * 4) Click Run. 22 | * 23 | */ 24 | -------------------------------------------------------------------------------- /Ch02_Variables/listing2.01.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 2.01 3 | * Declaring a variable 4 | */ 5 | 6 | var score; 7 | 8 | 9 | 10 | /* Further Adventures 11 | * 12 | * 1) Delete the semicolon at after the word score. 13 | * JS Bin should complain and show an error message. 14 | * Take a look at the message. 15 | * 16 | * 2) Add the semicolon back after the word score. 17 | * The semicolon shows the end of the statement. 18 | * 19 | * 3) Declare two more variables. 20 | * 21 | */ 22 | -------------------------------------------------------------------------------- /Ch02_Variables/listing2.02.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 2.02 3 | * Assigning a value to a variable 4 | */ 5 | 6 | var score; 7 | score = 100; 8 | 9 | 10 | 11 | /* Further Adventures 12 | * 13 | * 1) Click Run on the JS Bin Console panel. 14 | * Nothing will be displayed on the console 15 | * but the program will have run, 16 | * creating the score variable. 17 | * 18 | * 2) Click in the console, just to the right of the blue prompt > 19 | * The console should be highlighted and 20 | * a cursor should be blinking next to the prompt. 21 | * 22 | * 3) Type the word score to match your variable name 23 | * and press enter. 24 | * 100, the value assigned to score, should be displayed. 25 | * 26 | * 4) Change the value of score in the code above. 27 | * Repeat steps 1, 2 and 3. 28 | * 29 | */ 30 | -------------------------------------------------------------------------------- /Ch02_Variables/listing2.03.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 2.03 3 | * Using a variable 4 | */ 5 | 6 | var score; 7 | score = 100; 8 | console.log(score); 9 | 10 | 11 | 12 | /* Further Adventures 13 | * 14 | * 1) Change the value assigned to score. 15 | * Run the program again. 16 | * 17 | * 2) Declare a second variable, maybe score2. 18 | * 19 | * 3) Assign your variable a value. 20 | * 21 | * 4) Use console.log to display your variable on the console. 22 | * 23 | */ 24 | -------------------------------------------------------------------------------- /Ch02_Variables/listing2.04.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 2.04 3 | * Variables vary 4 | */ 5 | 6 | var score; 7 | score = 100; 8 | console.log(score); 9 | 10 | score = 150; 11 | console.log(score); 12 | 13 | 14 | 15 | /* Further Adventures 16 | * 17 | * 1) Change the value assigned to score. 18 | * Run the program again. 19 | * 20 | * 2) Declare a second variable, maybe score2. 21 | * 22 | * 3) Assign your variable a value. 23 | * 24 | * 4) Use console.log to display your 25 | * variable on the console. 26 | * 27 | * 5) Add a new line of code to alter the 28 | * value of your variable after it 29 | * has been displayed on the console. 30 | * 31 | * 6) Add a new line of code to display 32 | * the new value of your variable. 33 | * 34 | */ 35 | -------------------------------------------------------------------------------- /Ch02_Variables/listing2.05.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 2.05 3 | * Assigning text to variables 4 | */ 5 | 6 | var message; 7 | 8 | message = "Hello World!"; 9 | console.log(message); 10 | 11 | message = 'Congratulations! Your tweet has won a prize...'; 12 | console.log(message); 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * 1) Assign message a third value. Display it on the console. 19 | * 20 | * Pieces of text can be joined together using the + symbol. 21 | * e.g. "Hello " + "World!" 22 | * 23 | * 2) Split the first message into two pieces, 24 | * joined by + and run the program. 25 | * 26 | * 3) Split the second message into three pieces, 27 | * joined by + and run the program. 28 | * Be careful to use matching speech marks. 29 | * 30 | */ 31 | -------------------------------------------------------------------------------- /Ch02_Variables/listing2.06.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 2.06 3 | * Declaring and assigning in two steps 4 | */ 5 | 6 | var playerName; 7 | var locationName; 8 | 9 | playerName = "Kandra"; 10 | locationName = "The Dungeon of Doom"; 11 | 12 | console.log(playerName + " is in " + locationName); 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * 1) Declare a score variable. 19 | * 20 | * 2) Assign it a value. 21 | * 22 | * 3) Display an extra message on the console, 23 | * by combining variables and strings, to say 24 | * something like "Kandra has a score of 100" 25 | * 26 | */ 27 | -------------------------------------------------------------------------------- /Ch02_Variables/listing2.07.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 2.07 3 | * Declaring and assigning in one step 4 | */ 5 | 6 | var playerName = "Kandra"; 7 | var locationName = "The Dungeon of Doom"; 8 | 9 | console.log(playerName + " is in " + locationName); 10 | 11 | 12 | 13 | /* Further Adventures 14 | * 15 | * 1) Declare a health variable and assign it 16 | * a value in one step. 17 | * 18 | * 2) Declare a message variable. 19 | * 20 | * 3) Assign message a value created by joining 21 | * variables and text to say something like 22 | * "Kandra has health 50 and is in The Dungeon of Doom" 23 | * 24 | * 4) Replace the current console.log statement 25 | * with a new one to display the message variable. 26 | * 27 | */ 28 | -------------------------------------------------------------------------------- /Ch02_Variables/listing2.08.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 2.08 3 | * Using a variable’s current value to set its new value 4 | */ 5 | 6 | var score; 7 | score = 100; 8 | console.log("Your score was " + score); 9 | 10 | console.log("Great splat!!!"); 11 | score = score + 50; 12 | console.log("New score: " + score); 13 | 14 | console.log("Way to go!"); 15 | 16 | 17 | 18 | /* Further Adventures 19 | * 20 | * The player splats a kumquat. 21 | * Add code to: 22 | * 23 | * 1) Tell the player of a successful splat 24 | * 25 | * 2) Add 100 to the player's score 26 | * 27 | * 3) Show the new score 28 | * 29 | * 4) Display a message of congratulations 30 | * 31 | */ 32 | -------------------------------------------------------------------------------- /Ch02_Variables/listing2.09.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 2.09 3 | * Valid and invalid variable names 4 | */ 5 | 6 | var thisIsFine; 7 | var $noProblemHere; 8 | var _underscore56; 9 | var StartWithCapital; 10 | var z5; 11 | 12 | var 999; 13 | var 39Steps; 14 | var &nope; 15 | var single words only; 16 | var yield; 17 | 18 | 19 | 20 | /* Further Adventures 21 | * 22 | * 1) Take a look at the errors in the 23 | * error section of JS Bin below. 24 | * 25 | * 2) Click Run in the console 26 | * and see what errors appear there. 27 | * 28 | * 3) Delete the second block of variables 29 | * one by one from the code. 30 | * See how the errors change. 31 | * 32 | */ 33 | -------------------------------------------------------------------------------- /Ch03_Objects/listing3.01.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.01 3 | * Using variables to represent a book 4 | */ 5 | 6 | var bookTitle; 7 | var bookAuthor; 8 | 9 | bookTitle = "The Hobbit"; 10 | bookAuthor = "J. R. R. Tolkien"; 11 | 12 | console.log(bookTitle + " by " + bookAuthor); 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * 1) Declare variables for a second book 19 | * and assign them values. 20 | * 21 | * 2) Add code to log its details to the console. 22 | * 23 | * 3) Repeat steps 1 and 2 for a third book. 24 | * 25 | * 4) Consider the code needed for 10 books. 26 | * For 100 books. 27 | * 28 | */ 29 | -------------------------------------------------------------------------------- /Ch03_Objects/listing3.02.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.02 3 | * Using prefixes to tell book variables apart 4 | */ 5 | 6 | var book1Title = "The Hobbit"; 7 | var book1Author = "J.R.R.Tolkien"; 8 | 9 | var book2Title = "Northern Lights"; 10 | var book2Author = "Philip Pullman"; 11 | 12 | var book3Title = "The Adventures of Tom Sawyer"; 13 | var book3Author = "Mark Twain"; 14 | 15 | console.log("There are three books so far..."); 16 | console.log(book1Title + " by " + book1Author); 17 | console.log(book2Title + " by " + book2Author); 18 | console.log(book3Title + " by " + book3Author); 19 | 20 | 21 | 22 | /* Further Adventures 23 | * 24 | * 1) Add a fourth book. 25 | * 26 | * 2) Update the messages to include the new book. 27 | * 28 | */ 29 | -------------------------------------------------------------------------------- /Ch03_Objects/listing3.03.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.03 3 | * A book as an object 4 | */ 5 | 6 | var book; 7 | 8 | book = { 9 | title : "The Hobbit", 10 | author : "J. R. R. Tolkien", 11 | published : 1937 12 | }; 13 | 14 | console.log(book); 15 | 16 | 17 | 18 | /* Further Adventures 19 | * 20 | * 1) Change the title of book to 21 | * "The Hobbit, or There and Back Again". 22 | * Run the program again. 23 | * 24 | * 2) Try creating a book2 object. 25 | * 26 | * 3) Log book2 to the console. 27 | * 28 | */ 29 | -------------------------------------------------------------------------------- /Ch03_Objects/listing3.04.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.04 3 | * Creating an empty object 4 | */ 5 | 6 | var book; 7 | 8 | book = {}; 9 | 10 | 11 | 12 | /* Further Adventures 13 | * 14 | * 1) Log book to the console. 15 | * 16 | * 2) Place your cursor between the curly braces 17 | * in the code above and press enter. 18 | * JS Bin should add an empty line between 19 | * the braces. You can add more empty lines. 20 | * 21 | * 3) Run the program again, logging book 22 | * to the console. 23 | * The extra lines should make no difference 24 | * to the outcome. 25 | * 26 | */ 27 | -------------------------------------------------------------------------------- /Ch03_Objects/listing3.05.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.05 3 | * An object with a single property 4 | */ 5 | 6 | var book; 7 | 8 | book = { 9 | title : "The Hobbit" 10 | }; 11 | 12 | 13 | 14 | /* Further Adventures 15 | * 16 | * 1) Log book to the console. 17 | * 18 | * 2) Create a second book. 19 | * 20 | * 3) Log book2 to the console. 21 | * 22 | * 4) Run the program. 23 | * In the console tab, click after the prompt, >. 24 | * Type book and press Enter. 25 | * The book object should be displayed. 26 | * 27 | */ 28 | -------------------------------------------------------------------------------- /Ch03_Objects/listing3.06.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.06 3 | * Using a variable as a property value 4 | */ 5 | 6 | var book; 7 | var bookName; 8 | 9 | bookName = "The Adventures of Tom Sawyer"; 10 | 11 | book = { 12 | title : bookName 13 | }; 14 | 15 | 16 | 17 | /* Further Adventures 18 | * 19 | * 1) Run the program. 20 | * 21 | * 2) At the console prompt, type 'book' 22 | * and press enter. 23 | * 24 | * The book object should be displayed on the console. 25 | * Its title property should have the same 26 | * value as the bookName variable. 27 | * 28 | * 3) Change the value of the bookName variable 29 | * and try steps 1 and 2 again. 30 | * 31 | */ -------------------------------------------------------------------------------- /Ch03_Objects/listing3.07.js: -------------------------------------------------------------------------------- 1 | /* Get Programmimg with JavaScript 2 | * Listing 3.07 3 | * Objects with multiple properties 4 | */ 5 | 6 | var book1; 7 | var book2; 8 | 9 | book1 = { 10 | title : "The Hobbit", 11 | author : "J. R. R. Tolkien" 12 | }; 13 | 14 | book2 = { 15 | title : "Northern Lights", 16 | author : "Philip Pullman" 17 | }; 18 | 19 | 20 | 21 | /* Further Adventures 22 | * 23 | * 1) Add a third property to each book. 24 | * Don't forget the commas. 25 | * 26 | * 2) Add spaces so that the colons line up. 27 | * 28 | * 3) Log both objects to the console. 29 | * 30 | */ -------------------------------------------------------------------------------- /Ch03_Objects/listing3.08.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.08 3 | * Using dot notation to access property values 4 | */ 5 | 6 | var book; 7 | 8 | book = { 9 | title : "The Hobbit", 10 | author : "J. R. R. Tolkien", 11 | published : 1937 12 | }; 13 | 14 | console.log(book.title); 15 | console.log(book.author); 16 | 17 | 18 | 19 | /* Further Adventures 20 | * 21 | * 1) Log the published property to the console. 22 | * 23 | * 2) Add a second book. 24 | * 25 | * 3) Log its details to the console. 26 | * 27 | * 4) In the console tab, at the prompt, 28 | * type in book.title and press Enter. 29 | * Once the program is run, object properties 30 | * are available interactively via the console. 31 | * 32 | */ 33 | -------------------------------------------------------------------------------- /Ch03_Objects/listing3.09.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.09 3 | * Concatenating string properties 4 | */ 5 | 6 | var book1; 7 | var book2; 8 | 9 | book1 = { 10 | title: "The Hobbit", 11 | author: "J. R. R. Tolkien" 12 | }; 13 | 14 | book2 = { 15 | title: "Northern Lights", 16 | author: "Philip Pullman" 17 | }; 18 | 19 | console.log(book1.title + " by " + book1.author); 20 | console.log(book2.title + " by " + book2.author); 21 | 22 | 23 | 24 | /* Further Adventures 25 | * 26 | * 1) Add a third book. 27 | * 28 | * 2) Log its details to the console. 29 | * 30 | * 3) Add a third property. 31 | * 32 | * 4) Update the messages logged to include the 33 | * new property. 34 | * 35 | */ 36 | -------------------------------------------------------------------------------- /Ch03_Objects/listing3.10.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.10 3 | * Using dot notation to update a property 4 | */ 5 | 6 | var player1; 7 | 8 | player1 = { 9 | name: "Max", 10 | attempted: 0, 11 | correct: 0 12 | }; 13 | 14 | player1.attempted = 1; 15 | player1.correct = 1; 16 | player1.score = 50; 17 | 18 | 19 | 20 | /* Further Adventures 21 | * 22 | * 1) Run the program and then 23 | * click after the console prompt. 24 | * 25 | * 2) Change the value of the score property 26 | * by typing player1.score = 100; 27 | * at the prompt and pressing Enter. 28 | * 29 | * 3) Update other properties using the console. 30 | * 31 | */ 32 | -------------------------------------------------------------------------------- /Ch03_Objects/listing3.11.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.11 3 | * Using a property in a calculation 4 | */ 5 | 6 | var player1; 7 | 8 | player1 = { 9 | name: "Max", 10 | score: 0 11 | }; 12 | 13 | console.log(player1.name + " has scored " + player1.score); 14 | 15 | player1.score = player1.score + 50; 16 | 17 | console.log(player1.name + " has scored " + player1.score); 18 | 19 | 20 | 21 | /* Further Adventures 22 | * 23 | * 1) Write code to increase player1's score by 10%. 24 | * 25 | * 2) Add a second player. 26 | * 27 | * 3) Use the players' properties to find the sum 28 | * of their scores and log it to the console, 29 | * along with an appropriate message that includes 30 | * their names. 31 | * 32 | */ 33 | -------------------------------------------------------------------------------- /Ch03_Objects/listing3.12.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.12 3 | * A blog post 4 | */ 5 | 6 | var post = { 7 | id : 1, 8 | title : "My Crazy Space Adventure", 9 | author : "Philae", 10 | created : "2015-06-21", 11 | body : "You will not believe where I just woke up!! Only on a comet..." 12 | }; 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * 1) Display some of the properties. 19 | * 20 | * 2) Add a second post. 21 | * 22 | */ 23 | -------------------------------------------------------------------------------- /Ch03_Objects/listing3.13.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.13 3 | * A calendar event 4 | */ 5 | 6 | var event = { 7 | title : "Appraisal Meeting", 8 | startDate : "2016-10-04 16:00:00", 9 | endDate : "2016-10-04 17:00:00", 10 | location : "Martha's office", 11 | importance: 1, 12 | notes : 'Don\'t forget the portfolio!' 13 | }; 14 | 15 | 16 | 17 | /* Further Adventures 18 | * 19 | * 1) Remove the backslash from the notes property. 20 | * 21 | * 2) Take a look at the errors reported by JS Bin. 22 | * 23 | * 3) Put the backslash back. 24 | * 25 | * 4) See how the location property doesn't need 26 | * a backslash. What happens if you add one and 27 | * log the location property? 28 | * 29 | * 5) What if you want to show a backslash 30 | * as part of a string? 31 | * 32 | */ 33 | -------------------------------------------------------------------------------- /Ch03_Objects/listing3.15.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.15 3 | * A question and answer for a quiz app 4 | */ 5 | 6 | var questionAndAnswer = { 7 | question: "What is the capital of France?", 8 | answer1: "Bordeaux", 9 | answer2: "F", 10 | answer3: "Paris", 11 | answer4: "Brussels", 12 | correctAnswer: "Paris", 13 | marksForQuestion: 2 14 | }; 15 | 16 | 17 | 18 | /* Further Adventures 19 | * 20 | * 1) Use console.log to present the question 21 | * and answer options in a nicely formatted way. 22 | * 23 | */ 24 | -------------------------------------------------------------------------------- /Ch03_Objects/listing3.16.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.16 3 | * A player object 4 | */ 5 | 6 | var player; 7 | 8 | player = { 9 | name: "Kandra", 10 | health: 50, 11 | place: "The Dungeon of Doom", 12 | items: "a rusty key, The Sword of Destiny, a piece of cheese" 13 | }; 14 | 15 | console.log(player.name); 16 | console.log(player.name + " is in " + player.place); 17 | console.log(player.name + " has health " + player.health); 18 | console.log("Items: " + player.items); 19 | 20 | 21 | 22 | /* Further Adventures 23 | * 24 | * 1) Create a second player. 25 | * 26 | * 2) Log their details to the console. 27 | * 28 | * Notice how storing the items as a string 29 | * isn't a great approach. If the player 30 | * drops an item you'll have to manipulate 31 | * the string to remove the item. 32 | * 33 | * JavaScript has a way of storing lists 34 | * of items called an array. See Chapter 8. 35 | * 36 | */ 37 | -------------------------------------------------------------------------------- /Ch04_Functions/listing4.01.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 4.01 3 | * Displaying an object's properties on the console 4 | */ 5 | 6 | var movie1; 7 | 8 | movie1 = { 9 | title: "Inside Out", 10 | actors: "Amy Poehler, Bill Hader", 11 | directors: "Pete Doctor, Ronaldo Del Carmen" 12 | }; 13 | 14 | console.log("Movie information for " + movie1.title); 15 | console.log("------------------------------"); 16 | console.log("Actors: " + movie1.actors); 17 | console.log("Directors: " + movie1.directors); 18 | console.log("------------------------------"); 19 | 20 | 21 | 22 | /* Further Adventures 23 | * 24 | * 1) Add a second movie and display the same info for it. 25 | * 26 | * 2) Create an object to represent a blog post. 27 | * 28 | * 3) Write code to display info about the blog post. 29 | * 30 | */ 31 | -------------------------------------------------------------------------------- /Ch04_Functions/listing4.04.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 4.04 3 | * A simple function definition and assignment 4 | */ 5 | 6 | var sayHello; 7 | 8 | sayHello = function () { 9 | console.log("Hello World!"); 10 | }; 11 | 12 | 13 | 14 | /* Further Adventures 15 | * 16 | * 1) Run the program. 17 | * 18 | * Nothing will appear on the console. 19 | * You have defined a function. 20 | * You have assigned the function to a variable. 21 | * You have not yet made the function run. 22 | * 23 | * You can make the function run by 24 | * typing the name of the variable it has been 25 | * assigned to, followed by parentheses. 26 | * 27 | * sayHello(); 28 | * 29 | * 3) At the end of the program, add code to 30 | * make the function run. 31 | * 32 | * 4) Run the program. 33 | * 34 | */ -------------------------------------------------------------------------------- /Ch04_Functions/listing4.05.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 4.05 3 | * Two more function definitions and assignments 4 | */ 5 | 6 | var findTotal; 7 | var displayMenu; 8 | 9 | findTotal = function () { 10 | result = number1 + number2; 11 | }; 12 | 13 | displayMenu = function () { 14 | console.log("Please choose an option:"); 15 | console.log("(1) Print log"); 16 | console.log("(2) Upload file"); 17 | console.log("(9) Quit"); 18 | }; 19 | 20 | 21 | 22 | /* Further Adventures 23 | * 24 | * How to run a function, also called calling 25 | * or invoking the function, is explained in 26 | * Section 4.2.3. 27 | * If these exercises are too hard, you 28 | * can always come back to them later. 29 | * 30 | * 1) Declare number1, number2 and result variables. 31 | * 32 | * 2) Assign values to the variables. 33 | * 34 | * 3) Run the findTotal function by writing its name 35 | * followed by parentheses: findTotal(); 36 | * 37 | * 4) Display the result on the console. 38 | * 39 | * 5) Run the displayMenu function. 40 | * 41 | */ 42 | -------------------------------------------------------------------------------- /Ch04_Functions/listing4.06.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 4.06 3 | * Calling the sayHello function three times 4 | */ 5 | 6 | var sayHello; 7 | 8 | sayHello = function () { 9 | console.log("Hello World!"); 10 | }; 11 | 12 | sayHello(); 13 | sayHello(); 14 | sayHello(); 15 | 16 | 17 | 18 | /* Further Adventures 19 | * 20 | * 1) Change the message from the sayHello function. 21 | * 22 | * To add a line-break to a string, insert '\n' 23 | * e.g. "Line One\nLine Two" 24 | * 25 | * 2) Break the Hello World! message across two lines. 26 | * 27 | * 3) Create a function that prints the letters 28 | * of "Hello World!" one by one down the page 29 | * 30 | */ 31 | -------------------------------------------------------------------------------- /Ch04_Functions/listing4.07.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 4.07 3 | * Using the findTotal function to display a calculation 4 | */ 5 | 6 | var number1 = 1000; 7 | var number2 = 66; 8 | var result; 9 | var findTotal; 10 | 11 | findTotal = function () { 12 | result = number1 + number2; 13 | }; 14 | 15 | findTotal(); 16 | 17 | console.log(number1 + " + " + number2 + " = " + result); 18 | 19 | 20 | 21 | /* Further Adventures 22 | * 23 | * 1) Change number1 and number2 and run the program 24 | * 25 | * 2) Add a third variable, number3, and assign it a value 26 | * 27 | * 3) Update the findTotal function to add the three numbers 28 | * 29 | * 4) Update the console.log line to show the new calculation 30 | * 31 | */ 32 | -------------------------------------------------------------------------------- /Ch04_Functions/listing4.08.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 4.08 3 | * Displaying a menu 4 | */ 5 | 6 | var displayMenu; 7 | 8 | displayMenu = function () { 9 | console.log("Please choose an option:"); 10 | console.log("(1) Print log"); 11 | console.log("(2) Upload file"); 12 | console.log("(9) Quit"); 13 | }; 14 | 15 | displayMenu(); 16 | 17 | 18 | 19 | /* Further Adventures 20 | * 21 | * 1) Add two more options to the displayMenu 22 | * function and run the program. 23 | * 24 | * 2) Create your own displayMyMenu function. 25 | * 26 | * 3) Add a line to call your function as well. 27 | * Run the program 28 | * 29 | */ -------------------------------------------------------------------------------- /Ch04_Functions/listing4.09.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 4.09 3 | * Using a function to display object properties 4 | */ 5 | 6 | var showMovieInfo; 7 | 8 | showMovieInfo = function () { 9 | console.log("Movie information for " + movie.title); 10 | console.log("------------------------------"); 11 | console.log("Actors: " + movie.actors); 12 | console.log("Directors: " + movie.directors); 13 | console.log("------------------------------"); 14 | }; 15 | 16 | 17 | 18 | /* Further Adventures 19 | * 20 | * 1) Add a call to showMovieInfo and run the program. 21 | * What happens? 22 | * 23 | * 2) Declare a movie variable 24 | * but don't assign it a value. 25 | * Run the program. What happens now? 26 | * 27 | * 3) Create an empty object and 28 | * assign it to the movie variable. 29 | * Run the program again. 30 | * Does the output change? 31 | * 32 | * 4) Add title, actors and directors properties 33 | * to the movie object. Run one more time. 34 | * Is the output as expected? 35 | * 36 | */ 37 | -------------------------------------------------------------------------------- /Ch04_Functions/listing4.14.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 4.14 3 | * A function to display player information 4 | */ 5 | 6 | var player1; 7 | var player2; 8 | var player; 9 | var showPlayerInfo; 10 | 11 | player1 = { 12 | name: "Kandra", 13 | place: "The Dungeon of Doom", 14 | health: 50 15 | }; 16 | 17 | player2 = { 18 | name: "Dax", 19 | place: "The Old Library", 20 | health: 40 21 | }; 22 | 23 | showPlayerInfo = function () { 24 | console.log(player.name); 25 | console.log("------------------------------"); 26 | console.log(player.name + " is in " + player.place); 27 | console.log(player.name + " has health " + player.health); 28 | console.log("------------------------------"); 29 | console.log(""); 30 | }; 31 | 32 | player = player1; 33 | showPlayerInfo(); 34 | 35 | player = player2; 36 | showPlayerInfo(); 37 | 38 | 39 | 40 | /* Further Adventures 41 | * 42 | * 1) Write a function that just shows 43 | * where the player is. 44 | * 45 | * 2) Write a function that just shows 46 | * the player's health. 47 | * 48 | * 3) Change the showPlayerInfo function 49 | * to use your two functions. 50 | * 51 | */ 52 | -------------------------------------------------------------------------------- /Ch05_Arguments/listing5.01.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 5.01 3 | * Relying on a variable outside of the function 4 | */ 5 | 6 | var message; 7 | var showMessage; 8 | 9 | message = "It's full of stars!"; 10 | 11 | showMessage = function () { 12 | console.log(message); 13 | }; 14 | 15 | showMessage(); 16 | 17 | 18 | 19 | /* Further Adventures 20 | * 21 | * 1) Change the message and run the program. 22 | * 23 | * 2) Change the variable name in the 24 | * parentheses for console.log. 25 | * e.g. console.log(msg); 26 | * 27 | * 3) Run the program 28 | * 29 | * The showMessage function relies on 30 | * the variable name it uses with 31 | * console.log matching one that exists 32 | * outside of the function body. 33 | * 34 | */ 35 | -------------------------------------------------------------------------------- /Ch05_Arguments/listing5.02.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 5.02 3 | * Breaking a function by changing a variable name 4 | */ 5 | 6 | var msg; 7 | var showMessage; 8 | 9 | msg = "It's full of stars!"; 10 | 11 | showMessage = function () { 12 | console.log(message); 13 | }; 14 | 15 | showMessage(); 16 | 17 | 18 | 19 | /* Further Adventures 20 | * 21 | * 1) Update the console.log so the program works. 22 | * 23 | * 2) Declare another message variable 24 | * and assign it a value. 25 | * 26 | * 3) Display the new message as well as the old one. 27 | * 28 | * 4) Display a single message created by joining 29 | * the two strings. 30 | * 31 | */ 32 | -------------------------------------------------------------------------------- /Ch05_Arguments/listing5.03.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 5.03 3 | * Passing information to a function 4 | */ 5 | 6 | var showMessage; 7 | 8 | showMessage = function (message) { 9 | console.log("The message is: " + message); 10 | }; 11 | 12 | showMessage("It's full of stars!"); 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * 1) Change the message in the parentheses 19 | * when showMessage is called on line 12. 20 | * 21 | * The value in the parentheses when showMessage is called 22 | * is an argument. "It's full of stars!" was the 23 | * original argument on line 12. 24 | * 25 | * 2) Add two more calls to the showMessage function 26 | * with different arguments each time. 27 | * 28 | * 3) Change the showMessage function itself. 29 | * Make it add some extra text after the 30 | * message passed in. 31 | * 32 | */ -------------------------------------------------------------------------------- /Ch05_Arguments/listing5.04.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 5.04 3 | * Calling the same function with different arguments 4 | */ 5 | 6 | var showMessage; 7 | 8 | showMessage = function (message) { 9 | console.log("The message is: " + message); 10 | }; 11 | 12 | showMessage("It's full of stars!"); 13 | showMessage("Hello to Jason Isaacs"); 14 | showMessage("Hello to Jason Isaacs and Stephen Fry"); 15 | 16 | 17 | 18 | /* Further Adventures 19 | * 20 | * 1) Change the showMessage function to 21 | * display its prefixed text on a 22 | * separate line to the message. 23 | * 24 | * 2) Declare a myMessage variable and 25 | * assign it a string value. 26 | * 27 | * 3) Call the showMessage function with 28 | * myMessage as the argument. 29 | * 30 | */ -------------------------------------------------------------------------------- /Ch05_Arguments/listing5.05.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 5.05 3 | * Using the square function 4 | */ 5 | 6 | var square; 7 | 8 | square = function (numberToSquare) { 9 | var result; 10 | result = numberToSquare * numberToSquare; 11 | console.log(numberToSquare + " * " + numberToSquare + " = " + result); 12 | }; 13 | 14 | square(10); 15 | square(-2); 16 | square(1111); 17 | square(0.5); 18 | 19 | 20 | 21 | /* Further Adventures 22 | * 23 | * 1) Define a cube function that cubes 24 | * any number passed in as an argument. 25 | * 26 | * 2) Call your cube function four times 27 | * with different arguments to test it. 28 | * 29 | * Math.sqrt is a built-in function to find 30 | * the square root of a number. 31 | * e.g. Math.sqrt(9) finds the square root of 9. 32 | * 33 | * 3) Define and test a squareRoot function 34 | * to find square roots and display 35 | * them on the console. 36 | * e.g. The square root of 9 is 3. 37 | * 38 | */ 39 | -------------------------------------------------------------------------------- /Ch05_Arguments/listing5.06.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 5.06 3 | * A function with two arguments 4 | */ 5 | 6 | var showSum; 7 | 8 | showSum = function (number1, number2) { 9 | var total = number1 + number2; 10 | console.log("The sum is " + total); 11 | }; 12 | 13 | showSum(30, 23); 14 | showSum(2.8, -5); 15 | 16 | 17 | 18 | /* Further Adventures 19 | * 20 | * 1) Use the showSum function to add 56 and 74. 21 | * 22 | * To multiply two numbers, use the * symbol. 23 | * e.g. 3 * 5 is 3 multiplied by 5. 24 | * 25 | * 2) Create a showProduct function to multiply two numbers. 26 | * 27 | * 3) Use your function to multiply three pairs of numbers. 28 | * 29 | * To divide one number by another, use /. 30 | * e.g. 10 / 2 is 10 divided by 2. 31 | * 32 | * 4) What about showDifference and showQuotient 33 | * for subtraction and division? 34 | * 35 | */ -------------------------------------------------------------------------------- /Ch05_Arguments/listing5.07.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 5.07 3 | * Displaying a player's name 4 | */ 5 | 6 | var showPlayerName; 7 | 8 | showPlayerName = function (playerName) { 9 | console.log(playerName); 10 | }; 11 | 12 | showPlayerName("Kandra"); 13 | showPlayerName("Dax"); 14 | 15 | 16 | 17 | /* Further Adventures 18 | * 19 | * 1) Update the text logged so that it is 20 | * of the form: 21 | * The player's name is Kandra 22 | * 23 | * Strings have a length property that gives 24 | * the number of characters in the string. 25 | * e.g. playerName.length. 26 | * 27 | * 2) Make the function show the number 28 | * of letters in the player's name. 29 | * 30 | */ -------------------------------------------------------------------------------- /Ch05_Arguments/listing5.08.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 5.08 3 | * Displaying a player's name via an object property 4 | */ 5 | 6 | var player1; 7 | var player2; 8 | var showPlayerName; 9 | 10 | showPlayerName = function (playerName) { 11 | console.log(playerName); 12 | }; 13 | 14 | player1 = { 15 | name: "Kandra", 16 | place: "The Dungeon of Doom", 17 | health: 50 18 | }; 19 | 20 | player2 = { 21 | name: "Dax", 22 | place: "The Old Library", 23 | health: 40 24 | }; 25 | 26 | showPlayerName(player1.name); 27 | showPlayerName(player2.name); 28 | 29 | 30 | 31 | /* Further Adventures 32 | * 33 | * 1) In the showPlayerName function, 34 | * change playerName to playerName.toUpperCase(). 35 | * Run the function. 36 | * 37 | * 2) Change the function to show the player's 38 | * name in lower case. 39 | * 40 | */ 41 | -------------------------------------------------------------------------------- /Ch05_Arguments/listing5.09.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 5.09 3 | * Displaying a player's health 4 | */ 5 | 6 | var showPlayerHealth; 7 | 8 | showPlayerHealth = function (playerName, playerHealth) { 9 | console.log(playerName + " has health " + playerHealth); 10 | }; 11 | 12 | showPlayerHealth("Kandra", 50); 13 | showPlayerHealth("Dax", 40); 14 | 15 | 16 | 17 | /* Further Adventures 18 | * 19 | * 1) Change the showPlayerHealth function 20 | * so it shows information of the form: 21 | * Kandra: health 50. 22 | * 23 | * 2) Call the showPlayerHealth function 24 | * using your own arguments. 25 | * 26 | * 3) Declare a variable called healthInfo 27 | * inside the showPlayerHealth function. 28 | * 29 | * var healthInfo; 30 | * 31 | * 4) Assign healthInfo the string that 32 | * will be displayed. 33 | * 34 | * healthInfo = playerName + ": health " + playerHealth; 35 | * 36 | * 5) Change the call to console.log so that 37 | * it uses the healthInfo variable. 38 | * 39 | */ 40 | -------------------------------------------------------------------------------- /Ch05_Arguments/listing5.11.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 5.11 3 | * Displaying a player's location 4 | */ 5 | 6 | var showPlayerPlace; 7 | 8 | showPlayerPlace = function (playerName, playerPlace) { 9 | console.log(playerName + " is in " + playerPlace); 10 | }; 11 | 12 | showPlayerPlace("Kandra", "The Dungeon of Doom"); 13 | showPlayerPlace("Dax", "The Old Library"); 14 | 15 | 16 | 17 | /* Further Adventures 18 | * 19 | * 1) Inside the console.log brackets, 20 | * change playerName to playerName[0] 21 | * Run the program. 22 | * What effect do the brackets have? 23 | * 24 | * 2) Change the number in the brackets to 1. 25 | * 26 | * 3) What happens when you change the 27 | * number to 3? Why? 28 | * 29 | */ 30 | -------------------------------------------------------------------------------- /Ch06_Return_values/listing6.01.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 6.01 3 | * Returning a value from a function 4 | */ 5 | 6 | var getMessage; 7 | var response; 8 | 9 | getMessage = function () { 10 | return "I’m going on an adventure!"; 11 | }; 12 | 13 | response = getMessage(); 14 | 15 | console.log(response); 16 | 17 | 18 | 19 | /* Further Adventures 20 | * 21 | * 1) Write a getMyMessage function 22 | * that returns a message of 23 | * your choosing. 24 | * 25 | * We can call functions at the console prompt. 26 | * Run the program, then click in the Console panel 27 | * and enter commands after the prompt, > 28 | * 29 | * 2) Call getMessage at the prompt. 30 | * 31 | * > getMessage() 32 | * 33 | * When a function is called at the prompt, 34 | * its return value is displayed. 35 | * 36 | * 3) Call getMyMessage at the prompt. 37 | * 38 | */ -------------------------------------------------------------------------------- /Ch06_Return_values/listing6.02.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 6.02 3 | * Using an argument to determine the return value 4 | */ 5 | 6 | var getHelloTo; 7 | var fullMessage; 8 | 9 | getHelloTo = function (name) { 10 | return "Hello to " + name; 11 | }; 12 | 13 | fullMessage = getHelloTo("Kandra"); 14 | 15 | console.log(fullMessage); 16 | 17 | 18 | 19 | /* Further Adventures 20 | * 21 | * 1) Change the definition of getHelloTo 22 | * to accept two parameters, name1 and name2. 23 | * 24 | * 2) Make the function return a string of 25 | * the form "Hello to Kandra and Dax" 26 | * 27 | */ 28 | -------------------------------------------------------------------------------- /Ch06_Return_values/listing6.03.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 6.03 3 | * Using the return value as an argument 4 | */ 5 | 6 | var getHelloTo; 7 | 8 | getHelloTo = function (name) { 9 | return "Hello to " + name; 10 | }; 11 | 12 | console.log(getHelloTo("Kandra")); 13 | console.log(getHelloTo("Dax")); 14 | 15 | 16 | 17 | /* Further Adventures 18 | * 19 | * The JavaScript replace function will 20 | * replace one string with another. 21 | * e.g. "Hello Bob".replace("Bob", "Babs"); 22 | * returns the string "Hello Babs" 23 | * 24 | * 1) Declare a variable called template 25 | * in the function body of getHelloTo. 26 | * i.e. var template; 27 | * 28 | * 2) Assign it the value "Hello to {{name}}" 29 | * 30 | * 3) Replace the {{name}} placeholder 31 | * with the value passed in as name. i.e. 32 | * template = template.replace("{{name}}", name); 33 | * 34 | * 4) Return template from the function. 35 | * i.e. return template; 36 | * 37 | * 5) Run the function. 38 | * Does it still work? 39 | * 40 | */ 41 | -------------------------------------------------------------------------------- /Ch06_Return_values/listing6.04.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 6.04 3 | * Returning the sum of two numbers 4 | */ 5 | 6 | var add; 7 | 8 | add = function (number1, number2) { 9 | var total = number1 + number2; 10 | 11 | return total; 12 | }; 13 | 14 | var sum = add(50, 23); 15 | 16 | console.log(sum); 17 | 18 | 19 | 20 | /* Further Adventures 21 | * 22 | * 1) Find and display the sum of 23 | * a different pair of numbers 24 | * 25 | * 2) Change the call to console.log so that 26 | * the display on the console reads: 27 | * 'The sum of 50 and 23 is 73' 28 | * using the add function to generate the answer. 29 | * 30 | * 3) Can you use the add function as it is 31 | * to add more than two numbers? 32 | * Hint: You can nest calls to add. 33 | * 34 | * 4) Create a function to return the sum of 35 | * three numbers given as arguments. 36 | * 37 | */ -------------------------------------------------------------------------------- /Ch06_Return_values/listing6.05.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 6.05 3 | * A function with three arguments 4 | */ 5 | 6 | var totalCost; 7 | 8 | totalCost = function (callOutCharge, costPerHour, numberOfHours) { 9 | return callOutCharge + costPerHour * numberOfHours; 10 | }; 11 | 12 | console.log("$" + totalCost(30, 40, 3)); 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * 1) What is the cost for 12 hours work? 19 | * 20 | * 2) The plumber sometimes issues discount coupons. 21 | * Add a fourth parameter to the totalCost 22 | * function definition to account for discounts. 23 | * 24 | * 3) Update the function to subtract the discount 25 | * from the total before returning it. 26 | * 27 | * 4) If a customer has a $20 off coupon, 28 | * update the call to totalCost 29 | * to display the total cost. 30 | * It should now be $130 for 3 hours. 31 | * 32 | */ -------------------------------------------------------------------------------- /Ch06_Return_values/listing6.07.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 6.07 3 | * Getting a string for a player’s name 4 | */ 5 | 6 | var getPlayerName; 7 | 8 | getPlayerName = function (playerName) { 9 | return playerName; 10 | }; 11 | 12 | console.log(getPlayerName("Kandra")); 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * 1) Update the getPlayerName function 19 | * so it adds a prefix and suffix 20 | * made up of the = character. 21 | * The length of the prefix and suffix 22 | * should be 4. 23 | * 24 | * getPlayerName("Kiki") should return 25 | * ==== Kiki ==== 26 | * 27 | * getPlayerName("Mahesha") should return 28 | * ==== Mahesha ==== 29 | * 30 | * 2) Update the getPlayerName function 31 | * so it includes a border on the left 32 | * when displaying the name. 33 | * 34 | * getPlayerName("Jahver") should return 35 | * 36 | * | 37 | * | Jahver 38 | * | 39 | * 40 | * Note: to add a new-line character to a 41 | * string, use the escape sequence '\n' 42 | * 43 | * var msg = "\na\nb\n"; 44 | * console.log(msg) would display: 45 | * " 46 | * a 47 | * b 48 | * " 49 | * 50 | */ -------------------------------------------------------------------------------- /Ch06_Return_values/listing6.08.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 6.08 3 | * Getting strings for a player’s health and location 4 | */ 5 | 6 | var getPlayerHealth; 7 | var getPlayerPlace; 8 | 9 | getPlayerHealth = function (playerName, playerHealth) { 10 | return playerName + " has health " + playerHealth; 11 | }; 12 | 13 | getPlayerPlace = function (playerName, playerPlace) { 14 | return playerName + " is in " + playerPlace; 15 | }; 16 | 17 | console.log(getPlayerHealth("Kandra", 50)); 18 | console.log(getPlayerPlace("Kandra", "The Dungeon of Doom")); 19 | 20 | 21 | 22 | /* Further Adventures 23 | * 24 | * 1) Create a showPlayerInfo function with three 25 | * parameters, playerName, playerHealth and 26 | * playerPlace. 27 | * 28 | * 2) Call getPlayerHealth and getPlayerPlace 29 | * from your new showPlayerInfo function. 30 | * 31 | * e.g. showPlayerInfo("Dax", 50, "The Bath") 32 | * should produce the output 33 | * 34 | * Dax has health 50 35 | * Dax is in The Bath 36 | * 37 | */ -------------------------------------------------------------------------------- /Ch07_Object_arguments/listing7.01.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 7.01 3 | * Passing a function an object as an argument 4 | */ 5 | 6 | var planet1; 7 | var getPlanetInfo; 8 | 9 | planet1 = { 10 | name: "Jupiter", 11 | position: 5, 12 | type: "Gas Giant", 13 | radius: 69911, 14 | sizeRank: 1 15 | }; 16 | 17 | getPlanetInfo = function (planet) { 18 | return planet.name + ": planet number " + planet.position; 19 | }; 20 | 21 | console.log(getPlanetInfo(planet1)); 22 | 23 | 24 | 25 | /* Further Adventures 26 | * 27 | * 1) Create a second planet object. 28 | * 29 | * 2) Use getPlanetInfo to log details of 30 | * the second planet. 31 | * 32 | * 3) Update the getPlanetInfo function to 33 | * include more information about 34 | * each planet. 35 | * 36 | */ -------------------------------------------------------------------------------- /Ch07_Object_arguments/listing7.02.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 7.02 3 | * A function that adds properties to an object 4 | */ 5 | 6 | var planet1 = { name: "Jupiter", radius: 69911 }; 7 | 8 | var calculateSizes = function (planet) { 9 | var r = planet.radius; 10 | planet.area = 4 * 3.142 * r * r; 11 | planet.volume = 4 * 3.142 * r * r * r / 3; 12 | }; 13 | 14 | var displaySizes = function (planet) { 15 | console.log(planet.name); 16 | console.log("surface area = " + planet.area + " square km"); 17 | console.log("volume = " + planet.volume + " cubic km"); 18 | }; 19 | 20 | calculateSizes(planet1); 21 | displaySizes(planet1); 22 | 23 | 24 | 25 | /* Further Adventures 26 | * 27 | * The diameter of a planet is double its radius. 28 | * 29 | * 1) Update the calculateSizes function so it also 30 | * adds a diameter property to the planet. 31 | * 32 | * 2) Update the displaySizes function so it also 33 | * displays the diameter on the console. 34 | * 35 | */ -------------------------------------------------------------------------------- /Ch07_Object_arguments/listing7.03.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 7.03 3 | * A function to create planets 4 | */ 5 | 6 | var buildPlanet; 7 | var getPlanetInfo; 8 | var planet1; 9 | var planet2; 10 | 11 | buildPlanet = function (name, position, type, radius, rank) { 12 | return { 13 | name: name, 14 | position: position, 15 | type: type, 16 | radius: radius, 17 | sizeRank: rank 18 | }; 19 | }; 20 | 21 | getPlanetInfo = function (planet) { 22 | return planet.name.toUpperCase() + ": planet " + planet.position; 23 | }; 24 | 25 | planet1 = buildPlanet("Jupiter", 5, "Gas Giant", 69911, 1); 26 | planet2 = buildPlanet("Neptune", 8, "Ice Giant", 24622, 4); 27 | 28 | console.log(getPlanetInfo(planet1)); 29 | console.log(getPlanetInfo(planet2)); 30 | 31 | 32 | 33 | /* Further Adventures 34 | * 35 | * 1) Write a similar program to create and 36 | * display objects that represent cars. 37 | * 38 | */ -------------------------------------------------------------------------------- /Ch07_Object_arguments/listing7.04.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 7.04 3 | * Moving a point in 2D 4 | */ 5 | 6 | var point1; 7 | var point2; 8 | var move; 9 | var showPoint; 10 | 11 | move = function (point, change) { 12 | return { 13 | x: point.x + change.x, 14 | y: point.y + change.y 15 | }; 16 | }; 17 | 18 | showPoint = function (point) { 19 | console.log("( " + point.x + " , " + point.y + " )"); 20 | }; 21 | 22 | point1 = { x : 2, y : 5 }; 23 | 24 | point2 = move(point1, { x : 4, y : -2 }); 25 | 26 | showPoint(point1); 27 | console.log("Move 4 across and 2 down"); 28 | showPoint(point2); 29 | 30 | 31 | 32 | /* Further Adventures 33 | * 34 | * 1) Change the amount by which the point is moved 35 | * by altering the x and y properties of 36 | * the object literal passed to the move function. 37 | * 38 | * 2) Write a reflectX function that reflects 39 | * a point in the x-axis, returning the new point. 40 | * 41 | * 3) How about a rotate90 function that rotates 42 | * the point by 90 degrees anticlockwise 43 | * around ( 0 , 0 )? 44 | * 45 | */ -------------------------------------------------------------------------------- /Ch07_Object_arguments/listing7.05.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 7.05 3 | * Using Math.min and Math.max 4 | */ 5 | 6 | var showSmaller = function (num1, num2) { 7 | var smaller = Math.min(num1, num2); 8 | var larger = Math.max(num1, num2); 9 | 10 | console.log(smaller + " is smaller than " + larger); 11 | }; 12 | 13 | showSmaller(12, 3); 14 | showSmaller(-10, 3); 15 | 16 | 17 | 18 | /* Further Adventures 19 | * 20 | * 1) Try out some different arguments. 21 | * 22 | * 2) Write a showLarger function. 23 | * 24 | * 3) Write a showSmallest function that takes 25 | * three arguments and displays the smallest 26 | * of the three. 27 | * 28 | */ -------------------------------------------------------------------------------- /Ch07_Object_arguments/listing7.06.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 7.06 3 | * Using Math.min and Math.max to constrain an argument 4 | */ 5 | 6 | var line = function (lineLength) { 7 | var line = "========================================"; 8 | lineLength = Math.max(0, lineLength); 9 | lineLength = Math.min(40, lineLength); 10 | return line.substr(0, lineLength); 11 | }; 12 | 13 | console.log(line(30)); 14 | console.log(line(40)); 15 | console.log(line(50)); 16 | 17 | 18 | 19 | /* Further Adventures 20 | * 21 | * 1) Test line lengths from -20 to 60 22 | * in steps of 10. 23 | * 24 | * 2) Define a spaces function that returns a string 25 | * made up of a specified number of space characters. 26 | * The line of spaces returned can have a length 27 | * between 0 and 40. 28 | * 29 | * 3) Add an emptyBox function 30 | * that draws an empty box of specified 31 | * width and height 5. 32 | * 33 | * emptyBox(12); 34 | * 35 | * > ============ 36 | * > = = 37 | * > = = 38 | * > = = 39 | * > ============ 40 | * 41 | */ -------------------------------------------------------------------------------- /Ch07_Object_arguments/listing7.07.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 7.07 3 | * Converting a string to upper case 4 | */ 5 | 6 | var planet = "Jupiter"; 7 | var bigPlanet = planet.toUpperCase(); 8 | 9 | console.log(planet + " becomes " + bigPlanet); 10 | 11 | 12 | 13 | /* Further Adventures 14 | * 15 | * 1) Create a getBig function that accepts a 16 | * string as an argument and returns it 17 | * converted to upper case. 18 | * 19 | * There is also a toLowerCase string method. 20 | * 21 | * 2) Create a getSmall function that accepts a 22 | * string as an argument and returns it 23 | * converted to lower case. 24 | * 25 | */ -------------------------------------------------------------------------------- /Ch07_Object_arguments/listing7.08.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 7.08 3 | * Finding substrings 4 | */ 5 | 6 | var message = "We choose to go to the Moon!"; 7 | 8 | console.log(message.substr(3, 12)); 9 | 10 | 11 | 12 | /* Further Adventures 13 | * 14 | * 1) Use substr to log the following parts of 15 | * the message string to the console: 16 | * 17 | * > Moon! 18 | * > go to the 19 | * > We choose 20 | * 21 | * 2) Investigate what happens if you omit the 22 | * second argument when calling substr. 23 | * 24 | * 3) What happens if you use negative numbers 25 | * as arguments? 26 | * 27 | */ -------------------------------------------------------------------------------- /Ch07_Object_arguments/listing7.09.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 7.09 3 | * Finding a character with indexOf 4 | */ 5 | 6 | var message = "We choose to go to the Moon!"; 7 | 8 | var charIndex = message.indexOf("M"); 9 | 10 | console.log(message.substr(charIndex, 3)); 11 | 12 | 13 | 14 | /* Further Adventures 15 | * 16 | * 1) Use indexOf to find the index of where the 17 | * word 'go' starts in the message string. 18 | * 19 | * 2) Use indexOf and substr to display the word 20 | * 'choose' from the message string. 21 | * 22 | * There is also a lastIndexOf string method. 23 | * 24 | * 3) Use lastIndexOf to find the index of the 25 | * 'oo' in the word 'Moon' of the message string. 26 | * 27 | */ -------------------------------------------------------------------------------- /Ch08_Arrays/listing8.01.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 8.01 3 | * Creating arrays 4 | */ 5 | 6 | var scores; 7 | var names; 8 | 9 | scores = [ 3, 1, 8, 2 ]; 10 | names = [ "Kandra", "Dax", "Blinky" ]; 11 | 12 | console.log(scores); 13 | console.log(names); 14 | 15 | 16 | 17 | /* Further Adventures 18 | * 19 | * 1) Add an extra element to each array. 20 | * 21 | * 2) Declare a third variable, akaScores. 22 | * 23 | * 3) Assign the scores array to akaScores. 24 | * akaScores = scores 25 | * 26 | * 4) Log akaScores to the console. 27 | * 28 | */ -------------------------------------------------------------------------------- /Ch08_Arrays/listing8.02.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 8.02 3 | * Using existing objects in an array 4 | */ 5 | 6 | var place1 = { name : "The Pyramids", country : "Egypt" }; 7 | var place2 = { name : "The Grand Canyon", country : "USA" }; 8 | var place3 = { name : "Bondi Beach", country : "Australia" }; 9 | 10 | var thisYear = [ place1, place2 ]; 11 | var nextYear = [ place3 ]; 12 | 13 | console.log(thisYear); 14 | console.log(nextYear); 15 | 16 | 17 | 18 | /* Further Adventures 19 | * 20 | * 1) Add place1 to the nextYear array. 21 | * Can it be in two arrays at once? 22 | * 23 | * 2) Run the program again to check if an 24 | * object can be in two arrays at once. 25 | * 26 | */ -------------------------------------------------------------------------------- /Ch08_Arrays/listing8.03.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 8.03 3 | * Accessing array elements 4 | */ 5 | 6 | var scores = [ 3, 1, 8, 2 ]; 7 | 8 | console.log("There are " + scores.length + " scores:"); 9 | console.log("The first score is " + scores[0]); 10 | console.log("The second score is " + scores[1]); 11 | console.log("The third score is " + scores[2]); 12 | console.log("The fourth score is " + scores[3]); 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * 1) Add a fifth score to the array. 19 | * 20 | * 2) Add an extra console.log to display the new score. 21 | * 22 | * The index of the last element is one less than 23 | * the length of the array. 24 | * 25 | * 3) Log the value of the last element to the console. 26 | * Start the message with "The last score is " and 27 | * concatenate the score to the string. 28 | * Use an expression involving scores.length 29 | * as the index for the last element. 30 | * 31 | * 4) Add an extra score to the array and 32 | * run the program again. 33 | * 34 | */ -------------------------------------------------------------------------------- /Ch08_Arrays/listing8.04.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 8.04 3 | * Using a variable as an index 4 | */ 5 | 6 | var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]; 7 | var dayInWeek = 4; 8 | 9 | console.log( days[dayInWeek] ); 10 | console.log( days[dayInWeek - 1] ); 11 | 12 | 13 | 14 | /* Further Adventures 15 | * 16 | * 1) Change the value of the dayInWeek variable 17 | * to display a different day. 18 | * 19 | * 2) Write a function that accepts a number for the 20 | * day of the week to be displayed and returns 21 | * the day as a string. Assign the function to 22 | * a getDay variable. 23 | * 24 | * 3) Call your function, passing it 4 as the day 25 | * of the week, and log the value it returns. 26 | * 27 | */ -------------------------------------------------------------------------------- /Ch08_Arrays/listing8.06.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 8.06 3 | * Manipulating arrays with push, pop and join 4 | */ 5 | 6 | var items = []; 7 | var item = "The Pyramids"; 8 | var removed; 9 | 10 | items.push(item); 11 | items.push("The Grand Canyon"); 12 | items.push("Bondi Beach"); 13 | 14 | console.log(items); 15 | 16 | removed = items.pop(); 17 | 18 | console.log(removed + " was removed"); 19 | console.log(items.join(" and ")); 20 | 21 | 22 | 23 | /* Further Adventures 24 | * 25 | * 1) Push another item onto the array. 26 | * 27 | * 2) Log the joined items. 28 | * 29 | * You can set an array element by using its index. 30 | * items[2] = "The Taj Mahal" 31 | * 32 | * 3) Set one of the items using square brackets. 33 | * 34 | * 4) Can you push more than one item at a time? 35 | * 36 | */ -------------------------------------------------------------------------------- /Ch08_Arrays/listing8.07.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 8.07 3 | * Iterating over an array with forEach 4 | */ 5 | 6 | var items; 7 | var showInfo; 8 | 9 | items = [ 10 | "The Pyramids", 11 | "The Grand Canyon", 12 | "Bondi Beach" 13 | ]; 14 | 15 | showInfo = function (itemToShow) { 16 | console.log(itemToShow); 17 | }; 18 | 19 | items.forEach(showInfo); 20 | 21 | 22 | 23 | /* Further Adventures 24 | * 25 | * 1) Add a few extra items to the array, some 26 | * using push and some using square brackets. 27 | * Run the program. 28 | * 29 | * Strings also have a length property 30 | * which gives the number of characters in the string. 31 | * 32 | * 2) Update the showInfo function to also 33 | * display the number of letters in each item. 34 | * 35 | * 3) Write a new function that finds the total 36 | * number of letters of the elements in 37 | * the items array. 38 | * 39 | */ -------------------------------------------------------------------------------- /Ch08_Arrays/listing8.08.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 8.08 3 | * Calling forEach with an inline function 4 | */ 5 | 6 | var items = [ "The Pyramids", "The Grand Canyon", "Bondi Beach" ]; 7 | 8 | console.log("Dream destinations:"); 9 | 10 | items.forEach(function (item) { 11 | console.log(" – " + item); 12 | }); 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * 1) Change the program to show the number of 19 | * places to visit as well as the places themselves. 20 | * 21 | * 2) Wrap the display code in a function 22 | * and assign it to the showItems variable. 23 | * 24 | * 3) Click after the prompt on the console, 25 | * type showItems() and press Enter. 26 | * Can you run your function from the console? 27 | * 28 | * 4) Add and remove array items via the console 29 | * and display the current state of the array 30 | * with the showItems function. 31 | * 32 | * You can press the up arrow when working at the 33 | * console prompt to show previous commands used. 34 | * 35 | */ -------------------------------------------------------------------------------- /Ch08_Arrays/listing8.09.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 8.09 3 | * Using the arguments passed by forEach 4 | */ 5 | 6 | var players; 7 | var showArguments; 8 | 9 | players = [ "Dax", "Jahver", "Kandra" ]; 10 | 11 | showArguments = function (item, index, wholeArray) { 12 | console.log("Item: " + item); 13 | console.log("Index: " + index); 14 | console.log("Array: " + wholeArray); 15 | }; 16 | 17 | players.forEach(showArguments); 18 | 19 | 20 | /* Further Adventures 21 | * 22 | * 1) Add two more names to the players array. 23 | * 24 | * 2) Run the program. 25 | * 26 | * 3) Change the first console.log so 27 | * it uses wholeArray and index 28 | * to display the current item in 29 | * the array. Don't use the item 30 | * parameter. 31 | * 32 | */ -------------------------------------------------------------------------------- /Ch08_Arrays/listing8.10.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 8.10 3 | * Using the arguments passed by forEach - compact 4 | */ 5 | 6 | [ "Dax", "Jahver", "Kandra" ].forEach(function (item, index, wholeArray) { 7 | console.log("Item: " + item); 8 | console.log("Index: " + index); 9 | console.log("Array: " + wholeArray); 10 | }); 11 | 12 | 13 | 14 | /* Further Adventures 15 | * 16 | * 1) Create an array of rectangle objects. 17 | * Each rectangle should have a length 18 | * property and a width property. 19 | * 20 | * 2) Define an assignArea function that 21 | * takes a rectangle as an argument and 22 | * assigns an area property holding 23 | * the area of the rectangle. 24 | * 25 | * 3) Define a showInfo function that 26 | * takes a rectangle as an argument and 27 | * displays its properties on the console. 28 | * 29 | * 4) Use forEach and your two functions 30 | * to display info about each of 31 | * the rectangles in the array. 32 | * 33 | */ -------------------------------------------------------------------------------- /Ch08_Arrays/listing8.11.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 8.11 3 | * Finding the total shopping bill 4 | */ 5 | 6 | var getTotalBill = function (itemCosts, itemCounts) { 7 | var total = 0; 8 | 9 | itemCosts.forEach(function (cost, i) { 10 | total += cost * itemCounts[i]; 11 | }); 12 | 13 | return total; 14 | }; 15 | 16 | var costs = [ 1.99, 4.95, 2.50, 9.87 ]; 17 | var numOfEach = [ 2, 1, 5, 2 ]; 18 | 19 | console.log("The total cost is $" + getTotalBill(costs, numOfEach)); 20 | 21 | 22 | 23 | /* Further Adventures 24 | * 25 | * 1) Add an extra item to the shopping trip. 26 | * 27 | * 2) Change the function so that forEach iterates 28 | * over itemCounts instead of itemCosts. 29 | * Can you make it work? 30 | * 31 | * 3) Create a single array of objects with 32 | * cost and numberBought properties. 33 | * 34 | * items = [ { cost: 1.99, numberBought: 2 }, 35 | * { cost: 4.95, numberBought: 1 } ]; 36 | * 37 | * 4) Update getTotalBill to accept a single array 38 | * of items. 39 | * 40 | */ -------------------------------------------------------------------------------- /Ch08_Arrays/listing8.12.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 8.12 3 | * Displaying a multiple choice question 4 | */ 5 | 6 | var displayQuestion = function (questionAndAnswer) { 7 | var options = [ "A", "B", "C", "D", "E" ]; 8 | 9 | console.log(questionAndAnswer.question); 10 | 11 | questionAndAnswer.answers.forEach( 12 | function (answer, i) { 13 | console.log(options[i] + " - " + answer); 14 | } 15 | ); 16 | }; 17 | 18 | var question1 = { 19 | question : "What is the capital of France?", 20 | answers : [ 21 | "Bordeaux", 22 | "F", 23 | "Paris", 24 | "Brussels" 25 | ], 26 | correctAnswer : "Paris" 27 | }; 28 | 29 | displayQuestion(question1); 30 | 31 | 32 | 33 | /* Further Adventures 34 | * 35 | * 1) Add two more question objects. 36 | * 37 | * 2) Create an array with your question objects. 38 | * 39 | * 3) Use forEach to call displayQuestion on 40 | * each of your questions. 41 | * 42 | * 4) Can you execute a command at the prompt 43 | * to display a particular question? 44 | */ -------------------------------------------------------------------------------- /Ch09_Constructors/listing9.01.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 9.01 3 | * Using a function to create an object 4 | */ 5 | 6 | var buildPlanet = function (name, position, type) { 7 | var planet = {}; 8 | 9 | planet.name = name; 10 | planet.position = position; 11 | planet.type = type; 12 | 13 | return planet; 14 | }; 15 | 16 | var planet1 = buildPlanet( 17 | "Jupiter", 18 | 5, 19 | "Gas Giant" 20 | ); 21 | 22 | console.log(planet1.name); 23 | console.log(planet1.position); 24 | console.log(planet1.type); 25 | 26 | 27 | 28 | /* Further Adventures 29 | * 30 | * 1) Build a second planet, 31 | * using the buildPlanet function. 32 | * 33 | * 2) Log its name and type. 34 | * 35 | */ -------------------------------------------------------------------------------- /Ch09_Constructors/listing9.02.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 9.02 3 | * Adding methods to our constructed object 4 | */ 5 | 6 | var buildPlanet = function (name, position, type) { 7 | var planet = {}; 8 | 9 | planet.name = name; 10 | planet.position = position; 11 | planet.type = type; 12 | 13 | planet.showPlanet = function () { 14 | var info = planet.name; 15 | info += ": planet " + planet.position; 16 | info += " - " + planet.type; 17 | console.log(info); 18 | }; 19 | 20 | return planet; 21 | }; 22 | 23 | var planet1 = buildPlanet( 24 | "Jupiter", 25 | 5, 26 | "Gas Giant" 27 | ); 28 | 29 | planet1.showPlanet(); 30 | 31 | 32 | 33 | /* Further Adventures 34 | * 35 | * 1) Create a second planet. 36 | * Use the buildPlanet function. 37 | * 38 | * 2) Call the showPlanet method on your 39 | * new planet. 40 | * 41 | */ -------------------------------------------------------------------------------- /Ch09_Constructors/listing9.03.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 9.03 3 | * An array of constructed objects 4 | */ 5 | 6 | var buildPlanet = function (name, position, type) { 7 | var planet = {}; 8 | 9 | planet.name = name; 10 | planet.position = position; 11 | planet.type = type; 12 | 13 | planet.showPlanet = function () { 14 | var info = planet.name; 15 | info += ": planet " + planet.position; 16 | info += " - " + planet.type; 17 | console.log(info); 18 | }; 19 | 20 | return planet; 21 | }; 22 | 23 | var planets = [ 24 | buildPlanet( "Jupiter", 5, "Gas Giant" ), 25 | buildPlanet( "Neptune", 8, "Ice Giant" ), 26 | buildPlanet( "Mercury", 1, "Terrestrial" ) 27 | ]; 28 | 29 | planets.forEach(function (planet) { 30 | planet.showPlanet(); 31 | }); 32 | 33 | 34 | 35 | /* Further Adventures 36 | * 37 | * 1) Add two more planets to the planets array. 38 | * 39 | * 2) Run the program to display them. 40 | * 41 | * 3) Add code to visually separate each planet 42 | * from the next. 43 | * 44 | */ -------------------------------------------------------------------------------- /Ch09_Constructors/listing9.04.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 9.04 3 | * A Planet constructor 4 | */ 5 | 6 | var Planet = function (name, position, type) { 7 | this.name = name; 8 | this.position = position; 9 | this.type = type; 10 | 11 | this.showPlanet = function () { 12 | var info = this.name + ": planet " + this.position; 13 | info += " - " + this.type; 14 | console.log(info); 15 | }; 16 | }; 17 | 18 | var planet = new Planet( "Jupiter", 5, "Gas Giant" ); 19 | 20 | planet.showPlanet(); 21 | 22 | 23 | 24 | /* Further Adventures 25 | * 26 | * 1) Use the Planet constructor function 27 | * to create a second planet. 28 | * Don't forget the 'new' keyword. 29 | * 30 | * 2) Call the showPlanet method on your 31 | * newly created planet. 32 | * 33 | */ -------------------------------------------------------------------------------- /Ch09_Constructors/listing9.08.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 9.08 3 | * A calendar event constructor 4 | */ 5 | 6 | var CalendarEvent = function (title, startDate, startTime, endTime) { 7 | this.title = title; 8 | this.startDate = startDate; 9 | this.startTime = startTime; 10 | this.endTime = endTime; 11 | 12 | this.showEvent = function () { 13 | var dateString = [ 14 | this.startDate, 15 | ", from ", 16 | this.startTime, 17 | " to ", 18 | this.endTime 19 | ].join(""); 20 | 21 | console.log(this.title); 22 | console.log(dateString); 23 | }; 24 | }; 25 | 26 | var calEvent = new CalendarEvent( 27 | "Annual Review", 28 | "3/5/16", 29 | "4.00pm", 30 | "5.00pm" 31 | ); 32 | 33 | calEvent.showEvent(); 34 | 35 | 36 | 37 | /* Further Adventures 38 | * 39 | * 1) Add a second event. 40 | * 41 | * 2) Call the showEvent method on your 42 | * new calendar event. 43 | * 44 | * 3) Update the showEvent method so that 45 | * its output looks like this: 46 | * Annual Review: 3/5/16 - (4.00pm - 5.00pm) 47 | * 48 | */ -------------------------------------------------------------------------------- /Ch09_Constructors/listing9.09.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 9.09 3 | * A Place constructor part 1 4 | */ 5 | 6 | var Place = function (title, description) { 7 | this.title = title; 8 | this.description = description; 9 | 10 | this.getInfo = function () { 11 | var infoString = this.title + "\n"; 12 | infoString += this.description + "\n"; 13 | return infoString; 14 | }; 15 | }; 16 | 17 | var library = new Place( 18 | "The Old Library", 19 | "You are in a library. Dusty books line the walls." 20 | ); 21 | 22 | console.log(library.getInfo()); 23 | 24 | 25 | 26 | /* Further Adventures 27 | * 28 | * 1) Add a second place. 29 | * 30 | * 2) Call the getInfo method on your 31 | * new place. 32 | * 33 | */ -------------------------------------------------------------------------------- /Ch10_Bracket_notation/listing10.01.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 10.01 3 | * Bracket notation for object properties 4 | */ 5 | 6 | var ages = {}; 7 | 8 | ages["Kandra"] = 56; 9 | ages["Dax"] = 21; 10 | 11 | console.log(ages.Kandra); 12 | console.log(ages.Dax); 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * 1) Add a couple more properties to 19 | * the ages object. 20 | * 21 | * 2) Change the calls to console.log 22 | * to use square bracket notation as well. 23 | * 24 | */ -------------------------------------------------------------------------------- /Ch10_Bracket_notation/listing10.02.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 10.02 3 | * Longer strings as keys 4 | */ 5 | 6 | var ages = {}; 7 | 8 | ages["Kandra Smith"] = 56; 9 | ages["Dax Aniaku"] = 21; 10 | 11 | console.log(ages["Kandra Smith"]); 12 | console.log(ages["Dax Aniaku"]); 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * 1) Add a couple more properties to the ages object. 19 | * Include spaces and other characters 20 | * in the keys. 21 | * 22 | * 2) Log the values to the console. 23 | * 24 | * 3) Try changing the properties so they 25 | * use dot notation. What happens? 26 | * 27 | */ -------------------------------------------------------------------------------- /Ch10_Bracket_notation/listing10.03.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 10.03 3 | * Using a function to add ages 4 | */ 5 | 6 | var ages = {}; 7 | 8 | var addAge = function (name, age) { 9 | ages[name] = age; 10 | }; 11 | 12 | addAge("Kandra Smith", 56); 13 | addAge("Dax Aniaku", 21); 14 | 15 | console.log(ages["Kandra Smith"]); 16 | console.log(ages["Dax Aniaku"]); 17 | 18 | 19 | 20 | /* Further Adventures 21 | * 22 | * 1) Use the addAge function to add a couple 23 | * more people and their ages. 24 | * 25 | * 2) Log the new info to the console. 26 | * 27 | * 3) At the console prompt, 28 | * type in 'ages' and press Enter. 29 | * The ages object should be displayed. 30 | * 31 | * 4) Still at the console, 32 | * use the addAge function to add new info. 33 | * e.g. > addAge("Bob", 99); 34 | * 35 | * 5) Type 'ages' again to see the updated 36 | * ages object. 37 | * 38 | */ -------------------------------------------------------------------------------- /Ch10_Bracket_notation/listing10.04.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 10.04 3 | * Using Object.keys 4 | */ 5 | 6 | var ages = { 7 | "Kandra Smith" : 56, 8 | "Dax Aniaku" : 210, 9 | "Blinky" : 36 10 | }; 11 | 12 | var keys = Object.keys(ages); 13 | 14 | console.log(keys); 15 | 16 | 17 | 18 | /* Further Adventures 19 | * 20 | * 1) Add a couple more key-value pairs 21 | * to the ages object. 22 | * 23 | * 2) Add another property to the ages object 24 | * using square bracket notation. 25 | * Add the code before the call to 26 | * Object.keys, so the new key will 27 | * be logged to the console. 28 | * 29 | * 3) At the console prompt, 30 | * access individual elements of the 31 | * keys array by using index notation. 32 | * e.g. > keys[2]; 33 | * 34 | */ -------------------------------------------------------------------------------- /Ch10_Bracket_notation/listing10.05.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 10.05 3 | * Iterating over Object.keys with forEach 4 | */ 5 | 6 | var ages = { 7 | "Kandra Smith" : 56, 8 | "Dax Aniaku" : 21, 9 | "Blinky" : 36 10 | }; 11 | 12 | var keys = Object.keys(ages); 13 | 14 | keys.forEach(function (key) { 15 | console.log(key); 16 | }); 17 | 18 | 19 | 20 | /* Further Adventures 21 | * 22 | * 1) Add three more people to the ages object: 23 | * One directly to the object, 24 | * one using square brackets and 25 | * one using dot notation. 26 | * 27 | * 2) Update the call to console.log so it 28 | * shows the age of each person. 29 | * Remember, the key lets you access 30 | * the value from the ages object. 31 | * 32 | * 3) Update the call to console.log so it 33 | * shows the person's name along with 34 | * the length of their name. 35 | * e.g. Blinky: 6 36 | 37 | */ -------------------------------------------------------------------------------- /Ch10_Bracket_notation/listing10.08.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 10.08 3 | * An exits object 4 | */ 5 | 6 | var Place = function (title) { 7 | this.title = title; 8 | }; 9 | 10 | var kitchen = new Place("The Kitchen"); 11 | var dungeon = new Place("The Dungeon"); 12 | 13 | var exits = {}; 14 | 15 | exits["north"] = kitchen; 16 | exits["the trapdoor"] = dungeon; 17 | 18 | var keys = Object.keys(exits); 19 | 20 | keys.forEach(function (key) { 21 | console.log(key + " goes to " + exits[key].title); 22 | }); 23 | 24 | 25 | 26 | /* Further Adventures 27 | * 28 | * 1) Add a couple more places. 29 | * 30 | * 2) Add a couple more exits. 31 | * 32 | * 3) At the console prompt, 33 | * type 'exits' to see the exits object. 34 | * It has a number of keys with the 35 | * corresponding values being place objects. 36 | * 37 | * 4) Access one of the exits like this: 38 | * > exits["north"]; 39 | * A single object will be displayed. 40 | * 41 | * 5) Access the title property: 42 | * > exits["north"].title; 43 | * 44 | * 6) Or use square brackets: 45 | * > exits["north"]["title"] 46 | * 47 | */ -------------------------------------------------------------------------------- /Ch11_Scope/listing11.01.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 11.01 3 | * Declare, assign and use a variable 4 | */ 5 | 6 | var mountain; 7 | 8 | mountain = "Ben Nevis"; 9 | 10 | console.log(mountain); 11 | 12 | 13 | /* Further Adventures 14 | * 15 | * Run the program, then at the console prompt: 16 | * 17 | * 1) Type mountain and press enter. 18 | * 19 | * The value assigned to the mountain variable 20 | * should be displayed. 21 | * 22 | * mountain is a global variable. 23 | * It can be accessed anywhere in the program. 24 | * 25 | * 2) Assign the mountain variable a new value. 26 | * e.g. mountain = "Everest" 27 | * 28 | * 3) Type mountain and press enter. 29 | * 30 | */ -------------------------------------------------------------------------------- /Ch11_Scope/listing11.02.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 11.02 3 | * Accessing a variable from within a function 4 | */ 5 | 6 | var mountain = "Ben Nevis"; 7 | 8 | var showMountain = function () { 9 | console.log(mountain); 10 | }; 11 | 12 | showMountain(); 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * The mountain and showMountain variables are 19 | * accessible anywhere in the program. 20 | * 21 | * 1) At the console prompt, 22 | * type 'showMountain' and press enter. 23 | * 24 | * The function definition is displayed. 25 | * (JS Bin may have changed it to use its 26 | * own log function) 27 | * 28 | * 2) Type 'showMountain()' and press enter. 29 | * 30 | * "Ben Nevis" is displayed, followed by the 31 | * return value of the function, undefined. 32 | * 33 | * 3) Change the definition of the showMountain 34 | * function to return the value of 35 | * the mountain variable. 36 | * i.e. return mountain; 37 | * 38 | * 4) Run the program and clear the console. 39 | * 40 | * 5) Type 'showMountain()' and press enter. 41 | * 42 | */ -------------------------------------------------------------------------------- /Ch11_Scope/listing11.03.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 11.03 3 | * A tiny quiz 4 | */ 5 | 6 | var question = "What is the highest mountain in Wales?"; 7 | var answer = "Snowdon"; 8 | 9 | console.log(question); 10 | 11 | 12 | 13 | /* Further Adventures 14 | * 15 | * 1) At the prompt, 16 | * type 'answer' and press enter. 17 | * 18 | * 2) Assign answer a new value. 19 | * 20 | * Both question and answer are accessible 21 | * anywhere in the program, including inside functions. 22 | * 23 | * 3) Define a showQandA function to display 24 | * the question and answer. 25 | * 26 | * 4) Run the program. 27 | * 28 | * 5) Call the showQandA function at the console prompt. 29 | * 30 | */ -------------------------------------------------------------------------------- /Ch11_Scope/listing11.05.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 11.05 3 | * The variable is visible within the function 4 | */ 5 | 6 | var show = function () { 7 | var mountain = "Devils Tower"; 8 | console.log(mountain); 9 | }; 10 | 11 | show(); 12 | 13 | 14 | /* Further Adventures 15 | * 16 | * 1) Declare another variable called mountain, 17 | * outside of the function, at the end 18 | * of the program. 19 | * e.g. var mountain = "Everest"; 20 | * 21 | * 2) Run the program. 22 | * 23 | * 3) At the prompt, type 'mountain' and press enter. 24 | * 25 | * Within the show function, the local version 26 | * of mountain is used. 27 | * 28 | * Outside the show function, the global version 29 | * of mountain is used. 30 | * 31 | */ -------------------------------------------------------------------------------- /Ch11_Scope/listing11.06.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 11.06 3 | * Global and local variables 4 | */ 5 | 6 | var mountain; 7 | var show; 8 | 9 | mountain = "Ben Nevis"; 10 | 11 | show = function () { 12 | var secretMountain = "Devils Tower"; 13 | 14 | console.log(mountain); 15 | console.log(secretMountain); 16 | }; 17 | 18 | show(); 19 | 20 | console.log(mountain); 21 | console.log(secretMountain); 22 | 23 | 24 | 25 | /* Further Adventures 26 | * 27 | * 1) At the prompt, assign mountain a new value. 28 | * 29 | * 2) Call show at the prompt. 30 | * 31 | */ -------------------------------------------------------------------------------- /Ch11_Scope/listing11.07.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 11.07 3 | * A counter 4 | */ 5 | 6 | var counter = 0; 7 | 8 | var count = function () { 9 | counter = counter + 1; 10 | return counter; 11 | }; 12 | 13 | 14 | 15 | /* Further Adventures 16 | * 17 | * 1) Type the following commands at the prompt: 18 | * 19 | * > count() 20 | * > count() 21 | * > count() 22 | * 23 | * The current value of counter is displayed on the 24 | * console for each call to count. 25 | * 26 | * 2) Type the following commands at the prompt: 27 | * 28 | * > counter = 99 29 | * > count() 30 | * > count() 31 | * 32 | * Because counter is a global variable, you can 33 | * change it at the console. 34 | * 35 | */ -------------------------------------------------------------------------------- /Ch11_Scope/listing11.08.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 11.08 3 | * Hiding the counter variable 4 | */ 5 | 6 | var getCounter = function () { 7 | var counter = 0; 8 | 9 | var countUpBy1 = function () { 10 | counter = counter + 1; 11 | return counter; 12 | }; 13 | 14 | return countUpBy1; 15 | }; 16 | 17 | var count = getCounter(); 18 | 19 | 20 | 21 | /* Further Adventures 22 | * 23 | * 1) At the prompt, type the following commands: 24 | * 25 | * > count() 26 | * > count() 27 | * > count() 28 | * 29 | * Each time count is called, the current value of 30 | * counter is displayed on the console. 31 | * 32 | * 2) At the prompt, type the following commands: 33 | * 34 | * > counter 35 | * 36 | * The counter variable is local to the getCounter 37 | * function; that's where it was declared. It can't 38 | * be accessed from the console because it is not 39 | * a global variable. 40 | * 41 | */ -------------------------------------------------------------------------------- /Ch11_Scope/listing11.09.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 11.09 3 | * Multiple counters 4 | */ 5 | 6 | var getCounter = function () { 7 | var counter = 0; 8 | 9 | return function () { 10 | counter = counter + 1; 11 | return counter; 12 | }; 13 | }; 14 | 15 | var peakCount = getCounter(); 16 | var climbCount = getCounter(); 17 | 18 | 19 | 20 | /* Further Adventures 21 | * 22 | * 1) At the prompt, type these commands: 23 | * 24 | * > peakCount() 25 | * > peakCount() 26 | * > peakCount() 27 | * > climbCount() 28 | * > peakCount() 29 | * 30 | * Each count function gets its own counter variable. 31 | * They do not interfere with each other. 32 | * 33 | * 2) Call getCounter a third time and assign the 34 | * function returned to a new variable. 35 | * 36 | * 3) Use the new variable to count up. 37 | * 38 | */ -------------------------------------------------------------------------------- /Ch11_Scope/listing11.10.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 11.10 3 | * A Counter constructor 4 | */ 5 | 6 | var Counter = function () { 7 | var counter = 0; 8 | 9 | this.count = function () { 10 | counter = counter + 1; 11 | return counter; 12 | }; 13 | }; 14 | 15 | var peaks = new Counter(); 16 | var climbs = new Counter(); 17 | 18 | 19 | 20 | /* Further Adventures 21 | * 22 | * 1) At the console prompt, 23 | * call peaks.count and climbs.count 24 | * a number of times. 25 | * 26 | * 2) Add a countDown method to the 27 | * Counter constructor. 28 | * The method should decrease the counter 29 | * by 1 each time it is called. 30 | * 31 | * 3) Add a countUpBy method that counts up 32 | * by a specified amont. 33 | * e.g. 34 | * > peaks.count() 35 | * 1 36 | * > peaks.countUpBy(5) 37 | * 6 38 | * > peaks.countDown() 39 | * 5 40 | * 41 | */ -------------------------------------------------------------------------------- /Ch12_Conditions/listing12.01.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 12.01 3 | * Guess the number 4 | */ 5 | 6 | var secret = 8; 7 | 8 | var guess = function (userNumber) { 9 | if (userNumber === secret) { 10 | console.log("Well done!"); 11 | } 12 | }; 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * 1) Click run. 19 | * 20 | * 2) Call the guess function at the prompt. 21 | * e.g. guess(2) 22 | * 23 | * 3) Try a few different numbers as arguments. 24 | * 25 | * The program only prints "Well done!" when the 26 | * number you guess matches the secret number. 27 | * 28 | * The strict equality operator, ===, checks if 29 | * two values are equal. 30 | * 31 | * 4) Change the condition in parentheses to now 32 | * check if the guess is greater than the secret. 33 | * 34 | * if (userNumber > secret) 35 | * 36 | * 5) Change the message logged to "Too high!" 37 | * 38 | * 6) Run and test the updated program. 39 | * 40 | */ -------------------------------------------------------------------------------- /Ch12_Conditions/listing12.02.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 12.02 3 | * Guess the number - the else clause 4 | */ 5 | 6 | var secret = 8; 7 | 8 | var guess = function (userNumber) { 9 | if (userNumber === secret) { 10 | console.log("Well done!"); 11 | } else { 12 | console.log("Unlucky, try again."); 13 | } 14 | }; 15 | 16 | 17 | 18 | /* Further Adventures 19 | * 20 | * 1) Run the program and try a few guesses at the prompt. 21 | * e.g. guess(2) 22 | * 23 | * You can check if two values are NOT equal 24 | * by using the !== operator. 25 | * 26 | * 2) Change the condition in parentheses to check 27 | * if the guess is not equal to the secret. 28 | * 29 | * if (userNumber !== secret) 30 | * 31 | * 3) Run and test the updated program. 32 | * 33 | * 4) Change the messages to fit the new condition. 34 | * 35 | */ -------------------------------------------------------------------------------- /Ch12_Conditions/listing12.04.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 12.04 3 | * Guess the random number 4 | */ 5 | 6 | var getGuesser = function () { 7 | var secret = Math.floor(Math.random() * 10 + 1); 8 | 9 | return function (userNumber) { 10 | if (userNumber === secret) { 11 | return "Well done!"; 12 | } else { 13 | return "Unlucky, try again."; 14 | } 15 | }; 16 | }; 17 | 18 | var guess = getGuesser(); 19 | 20 | 21 | 22 | /* Further Adventures 23 | * 24 | * 1) Run the program. 25 | * 26 | * 2) Play the game a few times on the console. 27 | * e.g. guess(2) 28 | * 29 | * 3) Change the code so the secret number is 30 | * between 30 and 50. 31 | * 32 | * 4) Test your changes. 33 | * 34 | * CHALLENGE: Create a function called 'between' 35 | * that returns a random whole number between two 36 | * numbers passed as arguments. 37 | * 38 | * e.g. between(1, 5) // 1 <= whole number <= 5 39 | * between(100, 200) // 100 <= whole number <= 200 40 | * 41 | */ -------------------------------------------------------------------------------- /Ch12_Conditions/listing12.05.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 12.05 3 | * Higher or Lower 4 | */ 5 | 6 | var getGuesser = function () { 7 | var secret = Math.floor(Math.random() * 10 + 1); 8 | 9 | return function (userNumber) { 10 | if (userNumber === secret) { 11 | return "Well done!"; 12 | } else { 13 | if (userNumber > secret) { 14 | return "Too high!"; 15 | } else { 16 | return "Too low!"; 17 | } 18 | } 19 | }; 20 | }; 21 | 22 | var guess = getGuesser(); 23 | 24 | 25 | 26 | /* Further Adventures 27 | * 28 | * 1) Run the program 29 | * 30 | * 2) Play the game a few times. 31 | * e.g. guess(2) 32 | * 33 | * There are three blocks of code covering the 34 | * three outcomes for a guess: 35 | * too low, too high or correct. 36 | * 37 | * 3) Update the second condition to 38 | * (userNumber < secret) 39 | * 40 | * 4) Update the messages to match the 41 | * new condition. 42 | * 43 | * 5) Swap the first and second conditions so 44 | * the second condition uses the strict 45 | * equality operator. 46 | * 47 | * 6) Update the messages to match the 48 | * new condition. 49 | * 50 | */ -------------------------------------------------------------------------------- /Ch13_Modules/between.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * The 'between' function 3 | */ 4 | 5 | var between = function (lowest, highest) { 6 | var range = highest - lowest + 1; 7 | return lowest + Math.floor(Math.random() * range); 8 | }; 9 | -------------------------------------------------------------------------------- /Ch13_Modules/listing13.01.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Ch13_Modules/listing13.02.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 13.02 3 | * Loading JavaScript with a script tag 4 | * Requires the 'between' function 5 | */ 6 | 7 | var num = between(3, 7); 8 | console.log(num); 9 | 10 | 11 | /* Further Adventures 12 | * 13 | * 1) Run the program 4 or 5 times. 14 | * 15 | * A random number between 3 and 7 inclusive 16 | * should be generated each time. 17 | * 18 | * The 'between' function that generates 19 | * the number is loaded via a 20 | * script element in the HTML panel. 21 | * 22 | * 2) Create a rectangle object with random 23 | * length and width properties each 24 | * between 1 and 10 units long. 25 | * 26 | * 3) Define a showArea function that accepts 27 | * a rectangle as an argument and logs its 28 | * area to the console. 29 | * 30 | * > a 3 by 7 rectangle has area 21 31 | * 32 | */ -------------------------------------------------------------------------------- /Ch13_Modules/listing13.03.html: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Ch13_Modules/listing13.05.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /Ch13_Modules/listing13.06.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listings 13.05 and 13.06 3 | // Using the number generator in the guessing game 4 | // tixina 5 | 6 | var getGuesser = function (lowest, highest) { 7 | var secret = between(lowest, highest); 8 | 9 | return function (userNumber) { 10 | if (userNumber === secret) { 11 | return "Well done!"; 12 | } else if (userNumber > secret) { 13 | return "Too high!"; 14 | } else { 15 | return "Too low!"; 16 | } 17 | }; 18 | }; 19 | 20 | var guess = getGuesser(5, 10); 21 | 22 | 23 | 24 | /* Further Adventures 25 | * 26 | * 1) Run the program and play the game. 27 | * 28 | * 2) Change the arguments to getGuesser so that 29 | * the number to guess is in a bigger range. 30 | * 31 | * 3) Update the game so that it keeps track of 32 | * the number of guesses a player takes to 33 | * find the secret number. 34 | * 35 | * > Well done! You took 6 guesses. 36 | * 37 | */ 38 | -------------------------------------------------------------------------------- /Ch13_Modules/listing13.07.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Ch13_Modules/listing13.08.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listings 13.07 and 13.08 3 | // Using spacer and between in the guessing game 4 | // Uses Number Generator and spacer 5 | 6 | var getGuesser = function (lowest, highest) { 7 | var secret = between(lowest, highest); 8 | 9 | return function (userNumber) { 10 | if (userNumber === secret) { 11 | return spacer.box("Well done!", 14, "="); 12 | } else if (userNumber > secret) { 13 | return spacer.box("Too high!", 13, "+"); 14 | } else { 15 | return spacer.box("Too low!", 12, "-"); 16 | } 17 | }; 18 | }; 19 | 20 | var guess = getGuesser(5, 10); 21 | 22 | 23 | 24 | /* Further Adventures 25 | * 26 | * 1) Report the number of guesses taken 27 | * at each stage. 28 | * 29 | * > guess(6) 30 | * 31 | * ------------------------ 32 | * - Too low! (2 guesses) - 33 | * ------------------------ 34 | * 35 | * 2) End the game after a certain number 36 | * of guesses. 37 | * 38 | * ****************** 39 | * ! Out Of Guesses ! 40 | * ****************** 41 | * 42 | */ 43 | -------------------------------------------------------------------------------- /Ch13_Modules/listing13.09.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Ch13_Modules/listing13.10.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listings 13.09 and 13.10 3 | * Using Kallie's code 4 | */ 5 | 6 | var getGuesser = function (lowest, highest) { 7 | var secret = between(lowest, highest); 8 | 9 | return function (userNumber) { 10 | var msg; 11 | if (userNumber === secret) { 12 | msg = dasher("Well done!"); 13 | return spacer.wrap(msg, msg.length + 4, "="); 14 | } else if (userNumber > secret) { 15 | msg = dasher("Too high!"); 16 | return spacer.wrap(msg, msg.length + 4, "+"); 17 | } else { 18 | msg = dasher("Too low!"); 19 | return spacer.wrap(msg, msg.length + 4, "-"); 20 | } 21 | }; 22 | }; 23 | 24 | 25 | var guess = getGuesser(5, 10); 26 | 27 | 28 | 29 | /* Further Adventures 30 | * 31 | * 1) Run the program. 32 | * 33 | * 2) Make a guess. 34 | * 35 | * !!! Where has spacer.wrap gone? !!! 36 | * 37 | */ 38 | -------------------------------------------------------------------------------- /Ch13_Modules/listing13.11.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listing 13.11 3 | // Kallie's formatting code 4 | 5 | var spreader = function (text, character) { 6 | return text.split("").join(character); 7 | }; 8 | 9 | var spacer = function (text) { 10 | return spreader(text, " "); 11 | }; 12 | 13 | var dasher = function (text) { 14 | return spreader(text, "-"); 15 | }; 16 | 17 | 18 | 19 | /* Further Adventures 20 | * 21 | * 1) Run the program. 22 | * 23 | * 2) Test out the three functions 24 | * at the prompt. 25 | * 26 | * > spacer("Too high!") 27 | * T o o h i g h ! 28 | * 29 | * > dasher("Too low!") 30 | * T-o-o- -l-o-w-! 31 | * 32 | * > spreader("Well done!", "*") 33 | * W*e*l*l* *d*o*n*e*! 34 | * 35 | */ 36 | -------------------------------------------------------------------------------- /Ch13_Modules/listing13.12.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listing 13.12 3 | // Kallie's formatting code in a namespace 4 | 5 | var kalliesCode = { 6 | spreader: function (text, character) { 7 | return text.split("").join(character); 8 | }, 9 | 10 | spacer: function (text) { 11 | return kalliesCode.spreader(text, " "); 12 | }, 13 | 14 | dasher: function (text) { 15 | return kalliesCode.spreader(text, "-"); 16 | } 17 | }; 18 | 19 | 20 | 21 | /* Further Adventures 22 | * 23 | * 1) Run the program. 24 | * 25 | * 2) Test out the three functions 26 | * at the prompt. 27 | * 28 | * > kalliesCode.spacer("Too high!") 29 | * T o o h i g h ! 30 | * 31 | * > kalliesCode.dasher("Too low!") 32 | * T-o-o- -l-o-w-! 33 | * 34 | * > kalliesCode.spreader("Well done!", "*") 35 | * W*e*l*l* *d*o*n*e*! 36 | * 37 | * 3) Create a function called squasher 38 | * that removes characters added by spreader. 39 | * 40 | * > kalliesCode.squasher("T-o-o- -h-i-g-h-!", "-") 41 | * Too high! 42 | * 43 | */ 44 | -------------------------------------------------------------------------------- /Ch13_Modules/listing13.13.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Ch13_Modules/listing13.17.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Ch13_Modules/listing13.18.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listings 13.17 and 13.18 3 | * Importing modules for The Crypt 4 | */ 5 | 6 | var game = theCrypt.getGame(); 7 | 8 | 9 | 10 | /* Further Adventures 11 | * 12 | * 1) Run the program and play the game. 13 | * 14 | * > game.get() 15 | * > game.go("east") 16 | * 17 | */ 18 | -------------------------------------------------------------------------------- /Ch14_Models/TheSparrow.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Ch14_Models/TheSparrow.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Chapter 14 3 | * The Sparrow 4 | */ 5 | 6 | var game = theCrypt.getGame(); 7 | 8 | 9 | 10 | /* Further Adventures 11 | * 12 | * 1) Play the game, Using the public methods: 13 | * 14 | * > game.get() 15 | * > game.go("up") 16 | * 17 | */ 18 | -------------------------------------------------------------------------------- /Ch14_Models/listing14.01.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listing 14.01 3 | // The User constructor 4 | 5 | var User = function (name) { 6 | var sessions = []; 7 | var totalDuration = 0; 8 | 9 | this.addSession = function (sessionDate, duration) { 10 | sessions.push({ 11 | "sessionDate" : sessionDate, 12 | "duration" : duration 13 | }); 14 | totalDuration += duration; 15 | return totalDuration; 16 | }; 17 | 18 | this.getData = function () { 19 | return { 20 | "name" : name, 21 | "total" : totalDuration, 22 | "sessions": sessions.slice() 23 | }; 24 | }; 25 | }; 26 | 27 | 28 | 29 | /* Further Adventures 30 | * 31 | * 1) Run the program. 32 | * 33 | * 2) Test the constructor at the console prompt: 34 | * 35 | * > var user = new User("Mahesha") 36 | * > user.addSession("2017-02-05", 120) 37 | * > user.addSession("2017-02-06", 35) 38 | * > user.getData() 39 | * > user.getData().total 40 | * 41 | */ 42 | -------------------------------------------------------------------------------- /Ch14_Models/listing14.02.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /Ch14_Models/listing14.03.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listings 14.02 and 14.03 3 | // A function to build a user model from user data 4 | // Requires the User constructor 5 | 6 | var buildUser = function (userData) { 7 | var user = new User(userData.name); 8 | 9 | userData.sessions.forEach(function (sesh) { 10 | user.addSession(sesh.sessionDate, sesh.duration); 11 | }); 12 | 13 | return user; 14 | }; 15 | 16 | var userData = { 17 | "name" : "Mahesha", 18 | "sessions" : [ 19 | { "sessionDate" : "2017-02-05", "duration" : 120 }, 20 | { "sessionDate" : "2017-02-06", "duration" : 35 }, 21 | { "sessionDate" : "2017-02-06", "duration" : 45 } 22 | ] 23 | }; 24 | 25 | var user = buildUser(userData); 26 | 27 | console.log(user.addSession("2017-02-15", 40)); 28 | 29 | 30 | 31 | /* Further Adventures 32 | * 33 | * 1) Run the program. 34 | * 35 | * 2) Add a couple more sessions to the user data 36 | * and run the program again. 37 | * 38 | * 3) Use buildUser to create a second user from 39 | * a new user data object. 40 | * 41 | */ 42 | -------------------------------------------------------------------------------- /Ch14_Models/listing14.08.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Ch15_Views/Listing15.02.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Ch15_Views/Listing15.03.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listings 15.02 and 15.03 3 | // Testing two user views 4 | 5 | var user = new fitnessApp.User("Mahesha"); 6 | 7 | user.addSession("2017-02-05", 35); 8 | user.addSession("2017-02-06", 45); 9 | 10 | fitnessApp.userView.render(user); 11 | fitnessApp.userViewEnhanced.render(user); 12 | 13 | 14 | 15 | /* Further Adventures 16 | * 17 | * 1) Add a couple more sessions 18 | * for the user and run the 19 | * program again. 20 | * 21 | * 2) Take a look at the code for 22 | * the enhanced view (it's imported 23 | * on the HTML panel). 24 | * Can you follow it? 25 | * 26 | */ 27 | -------------------------------------------------------------------------------- /Ch15_Views/Listing15.08.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 15.08 3 | * A message view 4 | */ 5 | 6 | (function () { 7 | 8 | var getMessageInfo = function (messageData) { 9 | return "*** " + messageData + " ***"; 10 | }; 11 | 12 | var render = function (message) { 13 | console.error(getMessageInfo(message)); 14 | }; 15 | 16 | if (window.theCrypt === undefined) { 17 | window.theCrypt = {}; 18 | } 19 | 20 | theCrypt.messageView = { 21 | render: render 22 | }; 23 | 24 | })(); 25 | 26 | 27 | 28 | /* Further Adventures 29 | * 30 | * 1) Run the program. 31 | * 32 | * 2) Create a shortcut variable 33 | * for the message view. 34 | * 35 | * > var mv = theCrypt.messageView 36 | * 37 | * 3) Display some messages. 38 | * 39 | * > mv.render("Hello") 40 | * > mv.render("wassup wassup wassup") 41 | * 42 | * 4) Change the program to display 43 | * messages like this: 44 | * 45 | * > mv.render("Hello") 46 | * The message is: Hello 47 | * 48 | * 5) Change the program to display 49 | * messages in upper case. 50 | * 51 | * > mv.render("Hello") 52 | * HELLO 53 | * 54 | */ 55 | -------------------------------------------------------------------------------- /Ch16_Controllers/Listing16.12.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 16.12 3 | * Running the game 4 | */ 5 | 6 | var playerName = "Jahver"; 7 | var map = theCrypt.mapData; 8 | 9 | game.init(map, playerName); 10 | 11 | 12 | 13 | /* Further Adventures 14 | * 15 | * 1) Run the program. 16 | * 17 | * 2) Play the game. 18 | * 19 | */ 20 | -------------------------------------------------------------------------------- /Ch16_Controllers/listing16.02.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Ch16_Controllers/listing16.03.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listings 16.02 and 16.03 3 | // The fitness app 4 | 5 | var app = fitnessApp.init(fitnessApp.userData); 6 | 7 | 8 | 9 | /* Further Adventures 10 | * 11 | * 1) Create your own user data file 12 | * on JS Bin and import it instead 13 | * of the current data file. 14 | * 15 | * 2) Log some sessions for your user. 16 | * 17 | */ 18 | -------------------------------------------------------------------------------- /Ch16_Controllers/listing16.11.html: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Ch17_HTML/listing17.01.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Listing 17.01 6 | 7 | 8 | 9 |

My Movie Ratings

10 | 11 |

Brief info about my favorite movies.

12 | 13 |

Movies

14 | 15 |

Inside Out

16 | 17 |

An emotional adventure inside the head of a young girl.

18 | 19 | 20 | 21 | 22 | 23 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Ch17_HTML/listing17.03.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | My Movie Ratings 7 | 8 | 9 | 10 |

Welcome!

11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Ch17_HTML/listing17.04.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listings 17.03 and 17.04 3 | // Adding content to a paragraph with JavaScript 4 | 5 | (function () { 6 | 7 | function getGreeting () { 8 | var hellos = [ 9 | "Nanu nanu!", 10 | "Wassup!", 11 | "Yo!", 12 | "Hello movie lover!", 13 | "Ay up me duck!", 14 | "Hola!" 15 | ]; 16 | 17 | var index = Math.floor(Math.random() * hellos.length); 18 | 19 | return hellos[index]; 20 | } 21 | 22 | function updateGreeting () { 23 | para.innerHTML = getGreeting(); 24 | } 25 | 26 | var para = document.getElementById("greeting"); 27 | 28 | updateGreeting(); 29 | 30 | })(); 31 | 32 | 33 | 34 | /* Further Adventures 35 | * 36 | * 1) Add a heading to the HTML, 37 | * before the paragraph. 38 | * 39 | * 2) Give the heading an id attribute. 40 | * 41 | * 3) Use JavaScript to update the heading. 42 | * 43 | */ 44 | -------------------------------------------------------------------------------- /Ch17_HTML/listing17.05.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Listings 17.05 and 17.06 6 | 7 | 8 | 9 |

My Movie Ratings

10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 | 31 | -------------------------------------------------------------------------------- /Ch17_HTML/listing17.06.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listings 17.05 and 17.06 3 | * Building HTML with JavaScript 4 | */ 5 | 6 | var moviesData = [ 7 | { 8 | "title" : "Inside Out", 9 | "summary" : "An emotional adventure inside the head of a young girl." 10 | }, 11 | { 12 | "title" : "Tomorrowland", 13 | "summary" : "Recreating the hope and wonder of previous generations." 14 | }, 15 | { 16 | "title" : "The Wizard of Oz", 17 | "summary" : "Strangers find friendship and strength on a long walk." 18 | } 19 | ]; 20 | 21 | function getMovieHTML (movie) { 22 | var html = "

" + movie.title + "

"; 23 | html += "

" + movie.summary + "

"; 24 | return html; 25 | } 26 | 27 | function getMoviesHTML (movies) { 28 | var html = ""; 29 | 30 | movies.forEach(function (movie) { 31 | html += "
  • " + getMovieHTML(movie) + "
  • "; 32 | }); 33 | 34 | return ""; 35 | } 36 | 37 | function render (movies) { 38 | var moviesDiv = document.getElementById("movies"); 39 | moviesDiv.innerHTML = getMoviesHTML(movies); 40 | } 41 | 42 | render(moviesData); 43 | -------------------------------------------------------------------------------- /Ch17_HTML/listing17.10.css: -------------------------------------------------------------------------------- 1 | div { 2 | white-space: pre; 3 | font-family: monospace; 4 | } 5 | -------------------------------------------------------------------------------- /Ch17_HTML/listing17.11.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 17.11 3 | * A web-based message view 4 | */ 5 | 6 | (function () { 7 | "use strict"; 8 | 9 | function renderMessage (message) { 10 | return "*** " + message + " ***"; 11 | } 12 | 13 | function render (message) { 14 | var messageDiv = document.getElementById("messages"); 15 | messageDiv.innerHTML = renderMessage(message); 16 | } 17 | 18 | function clear () { 19 | var messageDiv = document.getElementById("messages"); 20 | messageDiv.innerHTML = ""; 21 | } 22 | 23 | if (window.theCrypt === undefined) { 24 | window.theCrypt = {}; 25 | } 26 | 27 | theCrypt.messageView = { 28 | render: render, 29 | clear: clear 30 | }; 31 | 32 | })(); 33 | 34 | 35 | /* Further Adventures 36 | * 37 | * 1) Run the program. 38 | * 39 | * 2) Display a message on the 40 | * output panel. 41 | * 42 | * > theCrypt.messageView.render("Hello") 43 | * 44 | */ 45 | -------------------------------------------------------------------------------- /Ch18_Controls/listing18.01.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | My Movie Ratings 7 | 8 | 9 | 10 | 11 | 12 |

    Welcome!

    13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /Ch18_Controls/listing18.03.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | My Movie Ratings 7 | 8 | 9 | 10 |

    My Movie Ratings

    11 | 12 |

    Brief info about my favorite movies.

    13 | 14 |

    Movies

    15 | 16 |
    17 |

    Inside Out

    18 |

    An emotional adventure inside the head of a young girl.

    19 |

    Actors

    20 | 24 |

    Directors

    25 | 29 |
    30 | 37 | 38 |
    39 |
    40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /Ch18_Controls/listing18.04.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listing 18.04 3 | // My Movie Ratings with a drop-down list 4 | 5 | (function () { 6 | "use strict"; 7 | 8 | var rateButton = document.getElementById("rate"); 9 | var ratingList = document.getElementById("rating"); 10 | var movie = document.getElementById("movie"); 11 | 12 | function rateMovie () { 13 | var rating = ratingList.value; 14 | var movieTitle = movie.innerHTML; 15 | alert("You gave " + movieTitle + " " + rating + " stars!"); 16 | } 17 | 18 | rateButton.addEventListener("click", rateMovie); 19 | 20 | })(); 21 | 22 | 23 | 24 | /* Further Adventures 25 | * 26 | * 1) Run the program and rate the movie. 27 | * 28 | * 2) Change which rating is automatically 29 | * selected in the drop-down list. 30 | * 31 | * 3) Add a paragraph element just before 32 | * the closing body tag. 33 | * 34 | * 4) Change the program so that your rating 35 | * is shown in the paragraph rather than 36 | * as a pop-up alert. 37 | * 38 | */ 39 | -------------------------------------------------------------------------------- /Ch18_Controls/listing18.08.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listing 18.08 3 | // Converting a command string into a command object 4 | 5 | function parseCommand (commandString) { 6 | var commandWords = commandString.split(" "); 7 | var command = { 8 | type: commandWords.shift() 9 | }; 10 | 11 | if (command.type === "go" || command.type === "use") { 12 | command.direction = commandWords.pop(); 13 | } 14 | 15 | command.item = commandWords.join(" "); 16 | 17 | return command; 18 | } 19 | 20 | 21 | /* Further Adventures 22 | * 23 | * 1) Run the program. 24 | * 25 | * 2) At the prompt, test the parseCommand 26 | * function. Check the returned 27 | * objects to make sure they have 28 | * the correct type, direction and item. 29 | * 30 | * > parseCommand("go north") 31 | * > parseCommand("get a rusty key") 32 | * > parseCommand("use a rusty key north") 33 | * 34 | * 4) Assign the returned object to 35 | * a variable and then access 36 | * its properties. 37 | * 38 | * > var cmd = parseCommand("use a rusty key north") 39 | * > cmd.type 40 | * > cmd.direction 41 | * > cmd.item 42 | * 43 | */ 44 | -------------------------------------------------------------------------------- /Ch18_Controls/theCrypt.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Chapter 18 3 | // The Crypt with text box interface 4 | 5 | var playerName = "Jahver"; 6 | var map = theCrypt.mapData; 7 | 8 | game.init(map, playerName); 9 | -------------------------------------------------------------------------------- /Ch19_Templates/listing19.01.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Fitness App News 7 | 8 | 9 | 10 |

    Fitness App News

    11 | 12 |
    13 | 14 | 15 | 23 | 24 | 25 | 26 | 27 | 28 | 45 | -------------------------------------------------------------------------------- /Ch19_Templates/listing19.02.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 19.02 3 | * Replacing one string with another 4 | */ 5 | 6 | var before = "

    {{title}}

    "; 7 | 8 | var after = before.replace("{{title}}", "Fitness App v1.0 Live!"); 9 | 10 | console.log(before); 11 | console.log(after); 12 | 13 | 14 | 15 | /* Further Adventures 16 | * 17 | * 1) Run the program. 18 | * 19 | * 2) Declare a title variable and assign it 20 | * a value; 21 | * 22 | * 3) Use before.replace to replace the {{title}} 23 | * placeholder with the value of the title 24 | * variable, rather than with a string literal. 25 | * 26 | * 4) Include a second placeholder in the 27 | * original string. 28 | * 29 | * 5) Use the replace method to fill both your 30 | * placeholder and {{title}} with a value. 31 | * 32 | */ 33 | -------------------------------------------------------------------------------- /Ch19_Templates/listing19.03.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 19.03 3 | * Chaining calls to replace 4 | */ 5 | 6 | var data = { 7 | author : "Oskar", 8 | social : "@appOskar51" 9 | }; 10 | 11 | var before = "Follow {{author}} {{social}}"; 12 | 13 | var after = before 14 | .replace("{{author}}", data.author) 15 | .replace("{{social}}", data.social); 16 | 17 | console.log(before); 18 | console.log(after); 19 | 20 | 21 | 22 | /* Further Adventures 23 | * 24 | * 1) Run the program. 25 | * 26 | * 2) Replace the author property in the data 27 | * with two new properties: firstName 28 | * and lastName. 29 | * 30 | * 3) Update the placeholders in the before 31 | * string to use the new properties. 32 | * 33 | * 4) Update the calls to the replace method 34 | * so all three placeholders are filled 35 | * with data. 36 | * 37 | */ 38 | -------------------------------------------------------------------------------- /Ch19_Templates/listing19.05.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listing 19.05 3 | // Using a while loop to count 4 | 5 | var count = 1; 6 | 7 | while (count < 11) { 8 | console.log(count); 9 | count++; 10 | } 11 | 12 | 13 | 14 | /* Further Adventures 15 | * 16 | * 1) Run the program. 17 | * 18 | * 2) Change the program so it 19 | * counts down from 10 to 1. 20 | * 21 | * 3) Change it so it shows all 22 | * the odd numbers from 1 to 100. 23 | * 24 | * 4) Create an array of numbers and 25 | * assign it to a variable. 26 | * 27 | * e.g. var nums = [2, 7, 1, 9]; 28 | * 29 | * 5) Use a while loop to display 30 | * the elements of the array. 31 | * 32 | * Hint: console.log(nums[count]) 33 | * 34 | */ 35 | -------------------------------------------------------------------------------- /Ch19_Templates/listing19.06.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listing 19.06 3 | // Using a while loop with replace 4 | 5 | var template = "{{title}} by {{author}}. Follow {{author}} {{social}}"; 6 | 7 | var filled = template; 8 | 9 | console.log("Starting replacement..."); 10 | 11 | while (filled.indexOf("{{author}}") !== -1) { 12 | filled = filled.replace("{{author}}", "Oskar"); 13 | console.log(filled); 14 | } 15 | 16 | console.log("...replacement finished."); 17 | 18 | 19 | 20 | 21 | /* Further Adventures 22 | * 23 | * 1) Run the program. 24 | * 25 | * 2) Create your own replace function. Move 26 | * the while loop into your function. The 27 | * function should accept three arguments: 28 | * template, placeholder and data. 29 | * 30 | * Declaration: 31 | * function replace (template, placeholder, data) { 32 | * // use a while loop to replace 33 | * // the placeholder in the template 34 | * // with its data 35 | * } 36 | * 37 | * Invocation: 38 | * var filled = replace(myTemplate, "{{title}}", "My Title") 39 | * 40 | */ 41 | -------------------------------------------------------------------------------- /Ch19_Templates/listing19.11.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Fitness App News 7 | 8 | 9 | 10 |

    Fitness App News

    11 | 12 |
    13 | 14 | 15 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Ch19_Templates/listing19.12.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listings 19.11 and 19.12 3 | * A modular news page 4 | */ 5 | 6 | (function () { 7 | "use strict"; 8 | 9 | var templateScript = document.getElementById("newsItemTemplate"); 10 | var templateString = templateScript.innerHTML; 11 | var newsContainer = document.getElementById("news"); 12 | 13 | 14 | var newsData = fitnessApp.news.getItems(3); 15 | 16 | newsContainer.innerHTML = gpwj.templates.fillList(templateString, newsData); 17 | 18 | })(); 19 | 20 | 21 | 22 | /* Further Adventures 23 | * 24 | * 1) Create a showItems function that 25 | * displays a specified number of 26 | * news items on the page. 27 | * 28 | * e.g. showItems(3) 29 | * 30 | * 2) Add a drop-down list to the page 31 | * so the reader can choose the number 32 | * of items to display. 33 | * 34 | * 3) Create an update function that reads 35 | * the number of items to display from 36 | * the drop-down list and then calls 37 | * showItems with the specified number. 38 | * 39 | * 4) Add a 'show' button that calls the 40 | * update function when clicked. 41 | * 42 | */ 43 | -------------------------------------------------------------------------------- /Ch19_Templates/listing19.14.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listing 19.14 3 | // A message view using templates 4 | // Depends on gpwj.templates 5 | 6 | (function () { 7 | "use strict"; 8 | 9 | var messageDiv = document.getElementById("messages"); 10 | var templateScript = document.getElementById("messageTemplate"); 11 | var template = templateScript.innerHTML; 12 | 13 | function render (message) { 14 | var data = { message: message }; 15 | messageDiv.innerHTML = gpwj.templates.fill(template, data); 16 | } 17 | 18 | function clear () { 19 | messageDiv.innerHTML = ""; 20 | } 21 | 22 | if (window.theCrypt === undefined) { 23 | window.theCrypt = {}; 24 | } 25 | 26 | theCrypt.messageView = { 27 | render: render, 28 | clear: clear 29 | }; 30 | 31 | })(); 32 | -------------------------------------------------------------------------------- /Ch19_Templates/listing19.15.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listing 19.15 3 | // A player view using templates 4 | // Depends on gpwj.templates 5 | 6 | (function () { 7 | "use strict"; 8 | 9 | var playerDiv = document.getElementById("player"); 10 | var playerScript = document.getElementById("playerTemplate"); 11 | var itemScript = document.getElementById("itemTemplate"); 12 | 13 | var playerTemplate = playerScript.innerHTML; 14 | var itemTemplate = itemScript.innerHTML; 15 | 16 | function render (player) { 17 | var data = player.getData(); 18 | var itemsDiv; 19 | 20 | var items = data.items.map(function (itemName) { 21 | return { item : itemName }; 22 | }); 23 | 24 | playerDiv.innerHTML = gpwj.templates.fill(playerTemplate, data); 25 | 26 | itemsDiv = document.getElementById("playerItems"); 27 | itemsDiv.innerHTML = gpwj.templates.fillList(itemTemplate, items); 28 | } 29 | 30 | if (window.theCrypt === undefined) { 31 | window.theCrypt = {}; 32 | } 33 | 34 | theCrypt.playerView = { 35 | render: render 36 | }; 37 | 38 | })(); 39 | -------------------------------------------------------------------------------- /Ch20_XHR/listing20.01.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listing 20.01 3 | // Using an XHR object to load user data 4 | 5 | var xhr = new XMLHttpRequest(); 6 | var url = "http://output.jsbin.com/qiwizo.json"; 7 | 8 | xhr.addEventListener("load", function () { 9 | console.log(xhr.responseText); 10 | }); 11 | 12 | xhr.open("GET", url); 13 | xhr.send(); 14 | 15 | 16 | 17 | /* Further Adventures 18 | * 19 | * 1) Run the program to see the data load. 20 | * 21 | * 2) Change the URL to pobapa.json 22 | * instead of qiwizo.json and 23 | * run the program again. 24 | * 25 | */ 26 | -------------------------------------------------------------------------------- /Ch20_XHR/listing20.02.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listing 20.02 3 | // Parsing JSON text to obtain a JavaScript object 4 | 5 | var xhr = new XMLHttpRequest(); 6 | var url = "http://output.jsbin.com/qiwizo.json"; 7 | 8 | xhr.addEventListener("load", function () { 9 | var data = JSON.parse(xhr.responseText); 10 | console.log(data); 11 | }); 12 | 13 | xhr.open("GET", url); 14 | xhr.send(); 15 | 16 | 17 | /* Further Adventures 18 | * 19 | * 1) Run the program. 20 | * 21 | * Once loaded, the data is converted 22 | * into a JavaScript object you can use. 23 | * 24 | * 2) Add more console.log lines inside 25 | * the event listener function: 26 | * 27 | * console.log(data.name); 28 | * console.log(data.duration); 29 | * console.log(data.sessions[0]); 30 | * 31 | * 3) At the console prompt, 32 | * try to access the data variable: 33 | * 34 | * > data 35 | * 36 | * Why is there an error? 37 | * 38 | */ 39 | -------------------------------------------------------------------------------- /Ch20_XHR/listing20.05.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Ch20_XHR/listing20.06.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listings 20.05 and 20.06 3 | // The fitness app 4 | 5 | var app = fitnessApp.init("qiwizo"); 6 | 7 | // pobapa - Obinna 8 | // qapavi - Liang 9 | // qiwizo - Mahesha 10 | 11 | 12 | /* Further Adventures 13 | * 14 | * 1) Run the program. 15 | * 16 | * 2) Log some sessions: 17 | * 18 | * > app.log("2017-02-07", 20) 19 | * 20 | * 3) Load another user: 21 | * 22 | * > app.loadUser("pobapa") 23 | * > app.log("2017-02-10", 45) 24 | * 25 | */ 26 | -------------------------------------------------------------------------------- /Ch20_XHR/listing20.07.json: -------------------------------------------------------------------------------- 1 | { 2 | "title" : "The Kitchen", 3 | "id" : "qulude", 4 | "description" : "You are in a kitchen. There is a disturbing smell.", 5 | "items" : [ "a piece of cheese" ], 6 | "exits" : [ 7 | { 8 | "direction" : "south", 9 | "to" : "The Old Library", 10 | "id" : "kacaluy" 11 | }, 12 | { 13 | "direction" : "west", 14 | "to" : "The Kitchen Garden", 15 | "id" : "xulare" 16 | }, 17 | { 18 | "direction" : "east", 19 | "to" : "The Kitchen Cupboard", 20 | "id" : "jodeyo" 21 | } 22 | ] 23 | } 24 | -------------------------------------------------------------------------------- /Ch20_XHR/listing20.11.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Listing 20.11 3 | // The Crypt 4 | 5 | var playerName = "Kandra"; 6 | var firstPlaceId = "vitewib"; 7 | 8 | game.init(firstPlaceId, playerName); 9 | -------------------------------------------------------------------------------- /Ch21_Conclusion/TheCrypt/img/rock2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrlarsen/GetProgramming/9f89c8aaaaecd518c6fea61de94a4ecd129ab03a/Ch21_Conclusion/TheCrypt/img/rock2.jpg -------------------------------------------------------------------------------- /Ch21_Conclusion/TheCrypt/img/sand2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrlarsen/GetProgramming/9f89c8aaaaecd518c6fea61de94a4ecd129ab03a/Ch21_Conclusion/TheCrypt/img/sand2.jpg -------------------------------------------------------------------------------- /Ch21_Conclusion/TheCrypt/js/messageView.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Chapter 21 3 | // A message view using templates 4 | // Depends on gpwj.templates 5 | 6 | (function () { 7 | "use strict"; 8 | 9 | var messageDiv = document.getElementById("messages"); 10 | var templateScript = document.getElementById("messageTemplate"); 11 | var template = templateScript.innerHTML; 12 | 13 | function render (message) { 14 | var data = { message: message }; 15 | messageDiv.innerHTML = gpwj.templates.fill(template, data); 16 | } 17 | 18 | function clear () { 19 | messageDiv.innerHTML = ""; 20 | } 21 | 22 | if (window.theCrypt === undefined) { 23 | window.theCrypt = {}; 24 | } 25 | 26 | theCrypt.messageView = { 27 | render: render, 28 | clear: clear 29 | }; 30 | 31 | })(); 32 | -------------------------------------------------------------------------------- /Ch21_Conclusion/TheCrypt/js/playerView.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Chapter 21 3 | // A player view using templates 4 | // Depends on gpwj.templates 5 | 6 | (function () { 7 | "use strict"; 8 | 9 | var playerDiv = document.getElementById("player"); 10 | var playerScript = document.getElementById("playerTemplate"); 11 | var itemScript = document.getElementById("itemTemplate"); 12 | 13 | var playerTemplate = playerScript.innerHTML; 14 | var itemTemplate = itemScript.innerHTML; 15 | 16 | function render (player) { 17 | var data = player.getData(); 18 | var itemsDiv; 19 | 20 | var items = data.items.map(function (itemName) { 21 | return { item : itemName }; 22 | }); 23 | 24 | playerDiv.innerHTML = gpwj.templates.fill(playerTemplate, data); 25 | 26 | itemsDiv = document.getElementById("playerItems"); 27 | itemsDiv.innerHTML = gpwj.templates.fillList(itemTemplate, items); 28 | } 29 | 30 | if (window.theCrypt === undefined) { 31 | window.theCrypt = {}; 32 | } 33 | 34 | theCrypt.playerView = { 35 | render: render 36 | }; 37 | 38 | })(); 39 | -------------------------------------------------------------------------------- /Ch21_Conclusion/TheCrypt/js/template.js: -------------------------------------------------------------------------------- 1 | // Get Programming with JavaScript 2 | // Chapter 21 3 | // The templates module 4 | 5 | (function () { 6 | "use strict"; 7 | 8 | function fill (template, data) { 9 | Object.keys(data).forEach(function (key) { 10 | var placeholder = "{{" + key + "}}"; 11 | var value = data[key]; 12 | 13 | while (template.indexOf(placeholder) !== -1) { 14 | template = template.replace(placeholder, value); 15 | } 16 | }); 17 | 18 | return template; 19 | } 20 | 21 | function fillList (template, dataArray) { 22 | var listString = ""; 23 | 24 | dataArray.forEach(function (data) { 25 | listString += fill(template, data); 26 | }); 27 | 28 | return listString; 29 | } 30 | 31 | if (window.gpwj === undefined) { 32 | window.gpwj = {}; 33 | } 34 | 35 | gpwj.templates = { 36 | fill: fill, 37 | fillList: fillList 38 | }; 39 | 40 | })(); 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Ch21_Conclusion/chapter21.md: -------------------------------------------------------------------------------- 1 | # Chapter 21 - Conclusion: get programming with JavaScript 2 | 3 | The folder called The Crypt contains the modules needed to play the game. Open theCrypt.html in a browser. 4 | -------------------------------------------------------------------------------- /Ch22_Node/between.js: -------------------------------------------------------------------------------- 1 | var between = function (lowest, highest) { 2 | var range = highest - lowest + 1; 3 | return lowest + Math.floor(Math.random() * range); 4 | }; 5 | 6 | module.exports = between; -------------------------------------------------------------------------------- /Ch22_Node/chapter22.md: -------------------------------------------------------------------------------- 1 | # Chapter 22 - Node: running JavaScript outside the browser -------------------------------------------------------------------------------- /Ch22_Node/fruit.js: -------------------------------------------------------------------------------- 1 | var between = require('./between'); 2 | 3 | var fruit = ['Apple', 'Orange', 'Lime', 'Lemon', 'Strawberry', 4 | 'Cranberry', 'Banana', 'Pineapple', 'Mango', 'Kumquat']; 5 | 6 | var fruitIndex = between(0, 9); 7 | 8 | console.log(fruit[fruitIndex]); -------------------------------------------------------------------------------- /Ch22_Node/hello.js: -------------------------------------------------------------------------------- 1 | console.log("Hello World!"); -------------------------------------------------------------------------------- /Ch22_Node/jahvers-crypt/lib/game.js: -------------------------------------------------------------------------------- 1 | var buildMap = require('./mapBuilder'); 2 | 3 | function Game (id, mapData) { 4 | this.id = id; 5 | this._players = []; 6 | 7 | this._firstPlace = buildMap(mapData); 8 | } 9 | 10 | Game.prototype = { 11 | getPlayersInPlace: function (placeTitle, playerToOmit) { 12 | var playersInPlace = []; 13 | 14 | this._players.forEach(function (player) { 15 | 16 | if (player !== playerToOmit) { 17 | 18 | var playerPlace = player.getPlace().getData(); 19 | 20 | if (playerPlace.title === placeTitle) { 21 | playersInPlace.push(player.getData()); 22 | } 23 | 24 | } 25 | 26 | }); 27 | 28 | return playersInPlace; 29 | }, 30 | 31 | addPlayer: function (player) { 32 | this._players.push(player); 33 | player.setPlace(this._firstPlace); 34 | } 35 | }; 36 | 37 | module.exports = Game; -------------------------------------------------------------------------------- /Ch22_Node/jahvers-crypt/lib/place.js: -------------------------------------------------------------------------------- 1 | var Place = function (title, description) { 2 | var exits = {}; 3 | var items = []; 4 | var challenges = {}; 5 | 6 | this.addItem = function (item) { 7 | items.push(item); 8 | }; 9 | 10 | this.getLastItem = function () { 11 | return items.pop(); 12 | }; 13 | 14 | this.addExit = function (direction, exit) { 15 | exits[direction] = exit; 16 | }; 17 | 18 | this.getExit = function (direction) { 19 | return exits[direction]; 20 | }; 21 | 22 | this.addChallenge = function (direction, challenge) { 23 | challenges[direction] = challenge; 24 | }; 25 | 26 | this.getChallenge = function (direction) { 27 | return challenges[direction]; 28 | }; 29 | 30 | this.getData = function () { 31 | var data = { 32 | "title" : title, 33 | "description" : description, 34 | "items" : items.slice(), 35 | "exits" : Object.keys(exits) 36 | }; 37 | 38 | return data; 39 | }; 40 | }; 41 | 42 | module.exports = Place; -------------------------------------------------------------------------------- /Ch22_Node/jahvers-crypt/lib/player.js: -------------------------------------------------------------------------------- 1 | var Player = function (name, health) { 2 | var items = []; 3 | var place = null; 4 | 5 | this.addItem = function (item) { 6 | items.push(item); 7 | }; 8 | 9 | this.hasItem = function (item) { 10 | return items.indexOf(item) !== -1; 11 | }; 12 | 13 | this.removeItem = function (item) { 14 | var itemIndex = items.indexOf(item); 15 | if (itemIndex !== -1) { 16 | items.splice(itemIndex, 1); 17 | } 18 | }; 19 | 20 | this.setPlace = function (destination) { 21 | place = destination; 22 | }; 23 | 24 | this.getPlace = function () { 25 | return place; 26 | }; 27 | 28 | this.applyDamage = function (damage) { 29 | health = health - damage; 30 | }; 31 | 32 | this.getData = function () { 33 | var data = { 34 | "name" : name, 35 | "health" : health, 36 | "items" : items.slice() 37 | }; 38 | 39 | if (place !== null) { 40 | data.place = place.getData().title; 41 | } 42 | 43 | return data; 44 | }; 45 | }; 46 | 47 | module.exports = Player; -------------------------------------------------------------------------------- /Ch22_Node/jahvers-crypt/replTest/playerGameTest.js: -------------------------------------------------------------------------------- 1 | var Game = require('../lib/game'); 2 | var PlayerGame = require('../lib/playerGame'); 3 | var mapData = require('../maps/theDarkHouse'); 4 | 5 | var game = new Game(1, mapData); 6 | 7 | var dax = new PlayerGame('Dax', game); 8 | var kandra = new PlayerGame('Kandra', game); 9 | var jahver = new PlayerGame('Jahver', game); -------------------------------------------------------------------------------- /Ch22_Node/multifruit.js: -------------------------------------------------------------------------------- 1 | var between = require('./between'); 2 | 3 | var fruit = ['Apple', 'Orange', 'Lime', 'Lemon', 'Strawberry', 4 | 'Cranberry', 'Banana', 'Pineapple', 'Mango', 'Kumquat']; 5 | 6 | var i, fruitIndex; 7 | 8 | for (i = 1; i < 6; i++) { 9 | fruitIndex = between(0, 9); 10 | console.log(fruit[fruitIndex]); 11 | } -------------------------------------------------------------------------------- /Ch22_Node/multifruitWhile.js: -------------------------------------------------------------------------------- 1 | var between = require('./between'); 2 | 3 | var fruit = ['Apple', 'Orange', 'Lime', 'Lemon', 'Strawberry', 4 | 'Cranberry', 'Banana', 'Pineapple', 'Mango', 'Kumquat']; 5 | 6 | var i, fruitIndex; 7 | 8 | i = 1; 9 | 10 | while (i < 6) { 11 | 12 | fruitIndex = between(0, 9); 13 | console.log(fruit[fruitIndex]); 14 | 15 | i++; 16 | } -------------------------------------------------------------------------------- /Ch22_Node/quiz.js: -------------------------------------------------------------------------------- 1 | var displayQuestion = function (questionAndAnswer) { 2 | var options = [ "A", "B", "C", "D", "E" ]; 3 | 4 | console.log(questionAndAnswer.question); 5 | 6 | questionAndAnswer.answers.forEach( 7 | function (answer, i) { 8 | console.log(options[i] + " - " + answer); 9 | } 10 | ); 11 | }; 12 | 13 | var question1 = { 14 | question : "What is the capital of France?", 15 | answers : [ 16 | "Bordeaux", 17 | "F", 18 | "Paris", 19 | "Brussels" 20 | ], 21 | correctAnswer : "Paris" 22 | }; 23 | 24 | displayQuestion(question1); -------------------------------------------------------------------------------- /Ch22_Node/quiz2.js: -------------------------------------------------------------------------------- 1 | var between = require('./between'); 2 | 3 | var qIndex = 0; 4 | 5 | var questions = [ 6 | { question: "7 x 8", answer: "56" }, 7 | { question: "12 x 12", answer: "144" }, 8 | { question: "5 x 6", answer: "30" }, 9 | { question: "9 x 3", answer: "27" } 10 | ]; 11 | 12 | var getQuestion = function () { 13 | qIndex = between(0, questions.length - 1); 14 | return questions[qIndex].question; 15 | }; 16 | 17 | var checkAnswer = function (userAnswer) { 18 | if (userAnswer === questions[qIndex].answer) { 19 | return "Correct!"; 20 | } else { 21 | return "No, the answer is " + questions[qIndex].answer; 22 | } 23 | }; 24 | 25 | module.exports = { 26 | quizMe: getQuestion, 27 | submit: checkAnswer 28 | }; -------------------------------------------------------------------------------- /Ch23_Express/TheCrypt/gameServer.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | 4 | var bodyParser = require('body-parser'); 5 | app.use(bodyParser.json()); 6 | 7 | var mapData = require('./maps/theDarkHouse'); 8 | var Game = require('./lib/game'); 9 | var PlayerGame = require('./lib/playerGame'); 10 | 11 | var game = new Game(1, mapData); 12 | var playerGame = new PlayerGame("Kandra", game); 13 | 14 | 15 | app.post('/api/get', get); 16 | app.post('/api/go', go); 17 | app.post('/api/use', use); 18 | app.get('/api/start', start); 19 | 20 | function get (req, res) { 21 | playerGame.clearMessages(); 22 | res.json(playerGame.get()); 23 | } 24 | 25 | function go (req, res) { 26 | playerGame.clearMessages(); 27 | var command = req.body.command; 28 | res.json(playerGame.go(command.direction)); 29 | } 30 | 31 | function use (req, res) { 32 | playerGame.clearMessages(); 33 | var command = req.body.command; 34 | res.json(playerGame.use(command.item, command.direction)); 35 | } 36 | 37 | function start (req, res) { 38 | res.json(playerGame.getData()); 39 | } 40 | 41 | 42 | app.use(express.static("public")); 43 | 44 | app.listen(1337); -------------------------------------------------------------------------------- /Ch23_Express/TheCrypt/lib/game.js: -------------------------------------------------------------------------------- 1 | var buildMap = require('../lib/mapBuilder'); 2 | 3 | function Game (id, mapData) { 4 | this.id = id; 5 | this._players = []; 6 | 7 | this._firstPlace = buildMap(mapData); 8 | } 9 | 10 | Game.prototype = { 11 | getPlayersInPlace: function (placeTitle, playerToOmit) { 12 | var playersInPlace = []; 13 | 14 | this._players.forEach(function (player) { 15 | if (player === undefined || player !== playerToOmit) { 16 | var playerPlace = player.getPlace().getData(); 17 | 18 | if (playerPlace.title === placeTitle) { 19 | playersInPlace.push(player.getData()); 20 | } 21 | } 22 | }); 23 | 24 | return playersInPlace; 25 | }, 26 | 27 | addPlayer: function (player) { 28 | this._players.push(player); 29 | player.setPlace(this._firstPlace); 30 | } 31 | }; 32 | 33 | 34 | // exports 35 | 36 | module.exports = Game; -------------------------------------------------------------------------------- /Ch23_Express/TheCrypt/lib/place.js: -------------------------------------------------------------------------------- 1 | var Place = function (title, description) { 2 | var exits = {}; 3 | var items = []; 4 | var challenges = {}; 5 | 6 | this.addItem = function (item) { 7 | items.push(item); 8 | }; 9 | 10 | this.getLastItem = function () { 11 | return items.pop(); 12 | }; 13 | 14 | this.addExit = function (direction, exit) { 15 | exits[direction] = exit; 16 | }; 17 | 18 | this.getExit = function (direction) { 19 | return exits[direction]; 20 | }; 21 | 22 | this.addChallenge = function (direction, challenge) { 23 | challenges[direction] = challenge; 24 | }; 25 | 26 | this.getChallenge = function (direction) { 27 | return challenges[direction]; 28 | }; 29 | 30 | this.getData = function () { 31 | var data = { 32 | "title" : title, 33 | "description" : description, 34 | "items" : items.slice(), 35 | "exits" : Object.keys(exits) 36 | }; 37 | 38 | return data; 39 | }; 40 | }; 41 | 42 | module.exports = Place; -------------------------------------------------------------------------------- /Ch23_Express/TheCrypt/lib/player.js: -------------------------------------------------------------------------------- 1 | var Player = function (name, health) { 2 | var items = []; 3 | var place = null; 4 | 5 | this.addItem = function (item) { 6 | items.push(item); 7 | }; 8 | 9 | this.hasItem = function (item) { 10 | return items.indexOf(item) !== -1; 11 | }; 12 | 13 | this.removeItem = function (item) { 14 | var itemIndex = items.indexOf(item); 15 | if (itemIndex !== -1) { 16 | items.splice(itemIndex, 1); 17 | } 18 | }; 19 | 20 | this.setPlace = function (destination) { 21 | place = destination; 22 | }; 23 | 24 | this.getPlace = function () { 25 | return place; 26 | }; 27 | 28 | this.applyDamage = function (damage) { 29 | health = health - damage; 30 | }; 31 | 32 | this.getData = function () { 33 | var data = { 34 | "name" : name, 35 | "health" : health, 36 | "items" : items.slice() 37 | }; 38 | 39 | if (place !== null) { 40 | data.place = place.getData().title; 41 | } 42 | 43 | return data; 44 | }; 45 | }; 46 | 47 | module.exports = Player; -------------------------------------------------------------------------------- /Ch23_Express/TheCrypt/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jahvers-crypt-express", 3 | "version": "1.0.0", 4 | "description": "A text-based adventure game", 5 | "main": "gameServer.js", 6 | "dependencies": { 7 | "body-parser": "^1.15.1", 8 | "express": "^4.13.4" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Ch23_Express/TheCrypt/public/img/rock.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrlarsen/GetProgramming/9f89c8aaaaecd518c6fea61de94a4ecd129ab03a/Ch23_Express/TheCrypt/public/img/rock.jpg -------------------------------------------------------------------------------- /Ch23_Express/TheCrypt/public/img/sand.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrlarsen/GetProgramming/9f89c8aaaaecd518c6fea61de94a4ecd129ab03a/Ch23_Express/TheCrypt/public/img/sand.jpg -------------------------------------------------------------------------------- /Ch23_Express/TheCrypt/public/js/commands.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | function parseCommand (commandString) { 5 | var commandWords = commandString.split(" "); 6 | var command = { 7 | type: commandWords.shift() 8 | }; 9 | 10 | if (command.type === "go" || command.type === "use") { 11 | command.direction = commandWords.pop(); 12 | } 13 | 14 | command.item = commandWords.join(" "); 15 | 16 | return command; 17 | } 18 | 19 | function doAction () { 20 | var txtCommand = document.getElementById("txtCommand"); 21 | var commandString = txtCommand.value; 22 | var command = parseCommand(commandString); 23 | 24 | theCrypt.messageView.clear(); 25 | 26 | game.do(command); 27 | 28 | txtCommand.value = ""; 29 | txtCommand.focus(); 30 | } 31 | 32 | var commandButton = document.getElementById("btnCommand"); 33 | commandButton.addEventListener("click", doAction); 34 | 35 | })(); -------------------------------------------------------------------------------- /Ch23_Express/TheCrypt/public/js/gameController.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | function render (data) { 5 | if (data.place) { 6 | theCrypt.placeView.render(data.place); 7 | } 8 | 9 | if (data.players) { 10 | theCrypt.playerView.render(data.players); 11 | } 12 | 13 | if (data.messages && data.messages.length) { 14 | theCrypt.messageView.render(data.messages.join('
    ')); 15 | } 16 | } 17 | 18 | function updateState (data) { 19 | theCrypt.gameID = data.gameID; 20 | render(data); 21 | } 22 | 23 | function init (playerName, gameID) { 24 | theCrypt.playerName = playerName; 25 | theCrypt.gameID = gameID; 26 | 27 | theCrypt.data.getStartData(updateState); 28 | } 29 | 30 | function doAction (command) { 31 | theCrypt.data.postAction(command, updateState); 32 | } 33 | 34 | // Assign the public interface 35 | window.game = { 36 | do: doAction, 37 | init: init 38 | }; 39 | 40 | })(); -------------------------------------------------------------------------------- /Ch23_Express/TheCrypt/public/js/messageView.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | var messageDiv = document.getElementById("messages"); 5 | var templateScript = document.getElementById("messageTemplate"); 6 | var template = templateScript.innerHTML; 7 | 8 | function render (message) { 9 | var data = { message: message }; 10 | messageDiv.innerHTML = gpwj.templates.fill(template, data); 11 | } 12 | 13 | function clear () { 14 | messageDiv.innerHTML = ""; 15 | } 16 | 17 | if (window.theCrypt === undefined) { 18 | window.theCrypt = {}; 19 | } 20 | 21 | theCrypt.messageView = { 22 | render: render, 23 | clear: clear 24 | }; 25 | 26 | })(); -------------------------------------------------------------------------------- /Ch23_Express/TheCrypt/public/js/templates.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | function fill (template, data) { 5 | Object.keys(data).forEach(function (key) { 6 | var placeholder = "{{" + key + "}}"; 7 | var value = data[key]; 8 | 9 | while (template.indexOf(placeholder) !== -1) { 10 | template = template.replace(placeholder, value); 11 | } 12 | }); 13 | 14 | return template; 15 | } 16 | 17 | function fillList (template, dataArray) { 18 | var listString = ""; 19 | 20 | dataArray.forEach(function (data) { 21 | listString += fill(template, data); 22 | }); 23 | 24 | return listString; 25 | } 26 | 27 | if (window.gpwj === undefined) { 28 | window.gpwj = {}; 29 | } 30 | 31 | gpwj.templates = { 32 | fill: fill, 33 | fillList: fillList 34 | }; 35 | 36 | })(); -------------------------------------------------------------------------------- /Ch23_Express/chapter23.md: -------------------------------------------------------------------------------- 1 | # Chapter 23 - Express: building an API -------------------------------------------------------------------------------- /Ch23_Express/webserver/fitnessServer.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | var bodyParser = require('body-parser'); 4 | 5 | app.use(express.static('public')); 6 | app.use(bodyParser.json()); 7 | 8 | app.post('/fitness', processSession); 9 | 10 | function processSession (req, res) { 11 | console.log(req.body); 12 | 13 | // this code is added later 14 | // in the chapter 15 | res.json({ 16 | 'status': 'OK', 17 | 'message': 'Session received for ' + req.body.name 18 | }); 19 | 20 | }; 21 | 22 | app.listen(1337); -------------------------------------------------------------------------------- /Ch23_Express/webserver/hello.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | 3 | var app = express(); 4 | 5 | app.get('/', sayHello); 6 | 7 | function sayHello (req, res) { 8 | res.send('

    Hello World!

    '); 9 | } 10 | 11 | app.listen(1337); -------------------------------------------------------------------------------- /Ch23_Express/webserver/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hello-server", 3 | "version": "1.0.0", 4 | "dependencies": { 5 | "express": "^4.13.4" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Ch23_Express/webserver/public/adventure.html: -------------------------------------------------------------------------------- 1 |

    I'm going on an adventure!

    -------------------------------------------------------------------------------- /Ch23_Express/webserver/public/client-server-GET.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrlarsen/GetProgramming/9f89c8aaaaecd518c6fea61de94a4ecd129ab03a/Ch23_Express/webserver/public/client-server-GET.png -------------------------------------------------------------------------------- /Ch23_Express/webserver/public/client-server.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Client-Server Interaction 6 | 7 | 8 | 9 | 10 |

    Client-Server Interaction

    11 |

    The steps involved in requesting a resource.

    12 |

    13 | Client-Server Interaction 17 |

    18 | 19 | 20 | -------------------------------------------------------------------------------- /Ch23_Express/webserver/public/fitnessData.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Fitness Data 6 | 7 | 8 | 9 |

    Fitness Data

    10 |

    The data is sent to the server automatically.

    11 | 12 | 13 | -------------------------------------------------------------------------------- /Ch23_Express/webserver/public/index.html: -------------------------------------------------------------------------------- 1 |

    Hello World!

    -------------------------------------------------------------------------------- /Ch23_Express/webserver/public/js/xhrPost.js: -------------------------------------------------------------------------------- 1 | var data = { 2 | name: "Mahesha", 3 | sessionDate: "2017-02-07", 4 | duration: 60 5 | }; 6 | var json = JSON.stringify(data); 7 | 8 | var url = "/fitness"; 9 | 10 | var xhr = new XMLHttpRequest(); 11 | xhr.open("POST", url); 12 | 13 | xhr.setRequestHeader('Content-Type', 'application/json'); 14 | 15 | /* code added later in chapter */ 16 | xhr.addEventListener("load", function () { 17 | var responseData = JSON.parse(xhr.responseText); 18 | alert(responseData.message); 19 | }); 20 | /* end */ 21 | 22 | xhr.send(json); -------------------------------------------------------------------------------- /Ch23_Express/webserver/public/moon.html: -------------------------------------------------------------------------------- 1 |

    Moon Quote

    2 |

    We choose to go to the moon

    -------------------------------------------------------------------------------- /Ch23_Express/webserver/static.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | 4 | app.use(express.static('public')); 5 | 6 | app.listen(1337); -------------------------------------------------------------------------------- /Ch23_Express/webserver/threeRoutes.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | 4 | app.get('/', sayHello); 5 | app.get('/moon', goMoon); 6 | app.get('/adventure', setOff); 7 | 8 | function sayHello (req, res) { 9 | res.send('

    Hello World!

    '); 10 | } 11 | 12 | function goMoon (req, res) { 13 | var html = '

    Moon Quote

    '; 14 | html += '

    We choose to go to the moon.

    '; 15 | res.send(html); 16 | } 17 | 18 | function setOff (req, res) { 19 | res.send('

    I’m going on an adventure!

    '); 20 | } 21 | 22 | app.listen(1337); -------------------------------------------------------------------------------- /Ch24_Polling/HighFives_XHR/auctionApp.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | 4 | var bid = 5; 5 | 6 | app.get('/state', getState); 7 | app.post('/bid', makeBid); 8 | 9 | function makeBid (req, res) { 10 | bid = bid + 5; 11 | res.json({ bid: bid }); 12 | } 13 | 14 | function getState (req, res) { 15 | res.json({ bid: bid }); 16 | } 17 | 18 | app.use(express.static("public")); 19 | 20 | app.listen(1337); -------------------------------------------------------------------------------- /Ch24_Polling/HighFives_XHR/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "high-fives", 3 | "version": "1.0.0", 4 | "dependencies": { 5 | "express": "^4.13.4" 6 | } 7 | } -------------------------------------------------------------------------------- /Ch24_Polling/HighFives_XHR/public/auction.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin:0; 3 | padding: 0; 4 | text-align:center; 5 | font-family:"Helvetica Neue", Helvetica, sans-serif; 6 | } 7 | 8 | h1 { 9 | background-color:rebeccapurple; 10 | color: #ffc; 11 | padding:0.5em; 12 | margin:0 0 1em; 13 | } 14 | 15 | table { 16 | width: 80%; 17 | margin:0 auto; 18 | border-collapse: collapse; 19 | } 20 | 21 | th, td { 22 | padding:0.3em; 23 | } 24 | 25 | th { 26 | background-color:rebeccapurple; 27 | color: #ffc; 28 | } 29 | 30 | td { 31 | border-bottom:1px solid rebeccapurple; 32 | } 33 | 34 | #bid { 35 | background-color: #eef; 36 | width:20%; 37 | } 38 | 39 | #asking { 40 | background-color: #fee; 41 | width:20%; 42 | } -------------------------------------------------------------------------------- /Ch24_Polling/HighFives_XHR/public/auction.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | High Fives Auctions 6 | 7 | 8 | 9 |

    High Fives Auctions

    10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
    ItemBidAskingAction
    The Fruitinator! Action Figure...loading......loading...
    29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Ch24_Polling/HighFives_XHR/public/auction.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | var bid = document.getElementById("bid"); 5 | var asking = document.getElementById("asking"); 6 | var bidButton = document.getElementById("btnBid"); 7 | 8 | function loadData(url, method, callback) { 9 | var xhr = new XMLHttpRequest(); 10 | xhr.open(method, url); 11 | 12 | xhr.addEventListener("load", function () { 13 | var data = JSON.parse(xhr.responseText); 14 | callback(data); 15 | }); 16 | 17 | xhr.send(); 18 | } 19 | 20 | function updateDisplay(data) { 21 | bid.innerHTML = data.bid; 22 | asking.innerHTML = data.bid + 5; 23 | } 24 | 25 | function sendBid() { 26 | loadData("/bid", "POST", updateDisplay); 27 | } 28 | 29 | function getState() { 30 | loadData("/state", "GET", updateDisplay); 31 | } 32 | 33 | bidButton.addEventListener("click", sendBid); 34 | 35 | getState(); 36 | 37 | setInterval(getState, 1000); 38 | 39 | })(); -------------------------------------------------------------------------------- /Ch24_Polling/TheCrypt/lib/game.js: -------------------------------------------------------------------------------- 1 | var buildMap = require('../lib/mapBuilder'); 2 | 3 | function Game (id, mapData) { 4 | this.id = id; 5 | this._players = []; 6 | 7 | this._firstPlace = buildMap(mapData); 8 | } 9 | 10 | Game.prototype = { 11 | getPlayersInPlace: function (placeTitle, playerToOmit) { 12 | var playersInPlace = []; 13 | 14 | this._players.forEach(function (player) { 15 | if (player === undefined || player !== playerToOmit) { 16 | var playerPlace = player.getPlace().getData(); 17 | 18 | if (playerPlace.title === placeTitle) { 19 | playersInPlace.push(player.getData()); 20 | } 21 | } 22 | }); 23 | 24 | return playersInPlace; 25 | }, 26 | 27 | addPlayer: function (player) { 28 | this._players.push(player); 29 | player.setPlace(this._firstPlace); 30 | } 31 | }; 32 | 33 | 34 | // exports 35 | 36 | module.exports = Game; -------------------------------------------------------------------------------- /Ch24_Polling/TheCrypt/lib/gameManager.js: -------------------------------------------------------------------------------- 1 | var Game = require('./game'); 2 | var PlayerGame = require('./playerGame'); 3 | var mapData = require('../maps/theDarkHouse.json'); 4 | 5 | var games = {}; 6 | var playerGames = {}; 7 | 8 | function getID () { 9 | var id; 10 | 11 | do { 12 | id = Math.floor(Math.random() * 100000 + 1); 13 | } while (games[id]); 14 | 15 | return id; 16 | } 17 | 18 | function getNewGame () { 19 | var game = new Game(getID(), mapData); 20 | games[game.id] = game; 21 | 22 | return game; 23 | } 24 | 25 | function joinGame (playerName, id) { 26 | var game = games[id] || getNewGame(); 27 | 28 | var playerGame = new PlayerGame(playerName, game); 29 | playerGames[game.id + "_" + playerName] = playerGame; 30 | 31 | return playerGame; 32 | } 33 | 34 | function getPlayerGame (playerName, id) { 35 | return playerGames[id + "_" + playerName]; 36 | } 37 | 38 | module.exports = { 39 | join: joinGame, 40 | getPlayerGame: getPlayerGame 41 | }; -------------------------------------------------------------------------------- /Ch24_Polling/TheCrypt/lib/place.js: -------------------------------------------------------------------------------- 1 | var Place = function (title, description) { 2 | var exits = {}; 3 | var items = []; 4 | var challenges = {}; 5 | 6 | this.addItem = function (item) { 7 | items.push(item); 8 | }; 9 | 10 | this.getLastItem = function () { 11 | return items.pop(); 12 | }; 13 | 14 | this.addExit = function (direction, exit) { 15 | exits[direction] = exit; 16 | }; 17 | 18 | this.getExit = function (direction) { 19 | return exits[direction]; 20 | }; 21 | 22 | this.addChallenge = function (direction, challenge) { 23 | challenges[direction] = challenge; 24 | }; 25 | 26 | this.getChallenge = function (direction) { 27 | return challenges[direction]; 28 | }; 29 | 30 | this.getData = function () { 31 | var data = { 32 | "title" : title, 33 | "description" : description, 34 | "items" : items.slice(), 35 | "exits" : Object.keys(exits) 36 | }; 37 | 38 | return data; 39 | }; 40 | }; 41 | 42 | module.exports = Place; -------------------------------------------------------------------------------- /Ch24_Polling/TheCrypt/lib/player.js: -------------------------------------------------------------------------------- 1 | var Player = function (name, health) { 2 | var items = []; 3 | var place = null; 4 | 5 | this.addItem = function (item) { 6 | items.push(item); 7 | }; 8 | 9 | this.hasItem = function (item) { 10 | return items.indexOf(item) !== -1; 11 | }; 12 | 13 | this.removeItem = function (item) { 14 | var itemIndex = items.indexOf(item); 15 | if (itemIndex !== -1) { 16 | items.splice(itemIndex, 1); 17 | } 18 | }; 19 | 20 | this.setPlace = function (destination) { 21 | place = destination; 22 | }; 23 | 24 | this.getPlace = function () { 25 | return place; 26 | }; 27 | 28 | this.applyDamage = function (damage) { 29 | health = health - damage; 30 | }; 31 | 32 | this.getData = function () { 33 | var data = { 34 | "name" : name, 35 | "health" : health, 36 | "items" : items.slice() 37 | }; 38 | 39 | if (place !== null) { 40 | data.place = place.getData().title; 41 | } 42 | 43 | return data; 44 | }; 45 | }; 46 | 47 | module.exports = Player; -------------------------------------------------------------------------------- /Ch24_Polling/TheCrypt/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jahvers-crypt-express", 3 | "version": "1.0.0", 4 | "description": "A text-based adventure game", 5 | "main": "gameServer.js", 6 | "dependencies": { 7 | "body-parser": "^1.15.1", 8 | "express": "^4.13.4" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Ch24_Polling/TheCrypt/public/img/rock.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrlarsen/GetProgramming/9f89c8aaaaecd518c6fea61de94a4ecd129ab03a/Ch24_Polling/TheCrypt/public/img/rock.jpg -------------------------------------------------------------------------------- /Ch24_Polling/TheCrypt/public/img/sand.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrlarsen/GetProgramming/9f89c8aaaaecd518c6fea61de94a4ecd129ab03a/Ch24_Polling/TheCrypt/public/img/sand.jpg -------------------------------------------------------------------------------- /Ch24_Polling/TheCrypt/public/js/commands.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | function parseCommand (commandString) { 5 | var commandWords = commandString.split(" "); 6 | var command = { 7 | type: commandWords.shift() 8 | }; 9 | 10 | if (command.type === "go" || command.type === "use") { 11 | command.direction = commandWords.pop(); 12 | } 13 | 14 | command.item = commandWords.join(" "); 15 | 16 | return command; 17 | } 18 | 19 | function doAction () { 20 | var txtCommand = document.getElementById("txtCommand"); 21 | var commandString = txtCommand.value; 22 | var command = parseCommand(commandString); 23 | 24 | theCrypt.messageView.clear(); 25 | 26 | game.do(command); 27 | 28 | txtCommand.value = ""; 29 | txtCommand.focus(); 30 | } 31 | 32 | var commandButton = document.getElementById("btnCommand"); 33 | commandButton.addEventListener("click", doAction); 34 | 35 | })(); -------------------------------------------------------------------------------- /Ch24_Polling/TheCrypt/public/js/gameController.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | function render (data) { 5 | theCrypt.mainView.render(); 6 | 7 | if (data.place) { 8 | theCrypt.placeView.render(data.place); 9 | } 10 | 11 | if (data.players) { 12 | theCrypt.playerView.render(data.players); 13 | } 14 | 15 | if (data.messages && data.messages.length) { 16 | theCrypt.messageView.render(data.messages.join('
    ')); 17 | } 18 | } 19 | 20 | function updateState (data) { 21 | theCrypt.gameID = data.gameID; 22 | render(data); 23 | } 24 | 25 | function init (playerName, gameID) { 26 | theCrypt.playerName = playerName; 27 | theCrypt.gameID = gameID; 28 | 29 | theCrypt.data.getStartData(updateState); 30 | } 31 | 32 | function doAction (command) { 33 | theCrypt.data.postAction(command, updateState); 34 | } 35 | 36 | // Assign the public interface 37 | window.game = { 38 | do: doAction, 39 | init: init 40 | }; 41 | 42 | })(); -------------------------------------------------------------------------------- /Ch24_Polling/TheCrypt/public/js/mainView.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | var mainDiv = document.getElementById("main"); 5 | var startFormDiv = document.getElementById("startControls"); 6 | 7 | var userDetailsTemplate = document.getElementById("userDetailsTemplate").innerHTML; 8 | 9 | function showMain () { 10 | mainDiv.className = ""; 11 | } 12 | 13 | function renderUser () { 14 | startFormDiv.innerHTML = gpwj.templates.fill(userDetailsTemplate, { 15 | playerName: theCrypt.playerName, 16 | gameID: theCrypt.gameID 17 | }); 18 | } 19 | 20 | function render () { 21 | showMain(); 22 | renderUser(); 23 | } 24 | 25 | if (window.theCrypt === undefined) { 26 | window.theCrypt = {}; 27 | } 28 | 29 | theCrypt.mainView = { 30 | render: render 31 | }; 32 | 33 | })(); -------------------------------------------------------------------------------- /Ch24_Polling/TheCrypt/public/js/messageView.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | var messageDiv = document.getElementById("messages"); 5 | var templateScript = document.getElementById("messageTemplate"); 6 | var template = templateScript.innerHTML; 7 | 8 | function render (message) { 9 | var data = { message: message }; 10 | messageDiv.innerHTML = gpwj.templates.fill(template, data); 11 | } 12 | 13 | function clear () { 14 | messageDiv.innerHTML = ""; 15 | } 16 | 17 | if (window.theCrypt === undefined) { 18 | window.theCrypt = {}; 19 | } 20 | 21 | theCrypt.messageView = { 22 | render: render, 23 | clear: clear 24 | }; 25 | 26 | })(); -------------------------------------------------------------------------------- /Ch24_Polling/TheCrypt/public/js/startGame.js: -------------------------------------------------------------------------------- 1 | var btnStart = document.getElementById('btnStart'); 2 | 3 | btnStart.addEventListener('click', function () { 4 | var playerName = document.getElementById('txtPlayerName').value; 5 | var gameID = document.getElementById('txtGameID').value; 6 | 7 | game.init(playerName, gameID); 8 | }); -------------------------------------------------------------------------------- /Ch24_Polling/TheCrypt/public/js/templates.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | function fill (template, data) { 5 | Object.keys(data).forEach(function (key) { 6 | var placeholder = "{{" + key + "}}"; 7 | var value = data[key]; 8 | 9 | while (template.indexOf(placeholder) !== -1) { 10 | template = template.replace(placeholder, value); 11 | } 12 | }); 13 | 14 | return template; 15 | } 16 | 17 | function fillList (template, dataArray) { 18 | var listString = ""; 19 | 20 | dataArray.forEach(function (data) { 21 | listString += fill(template, data); 22 | }); 23 | 24 | return listString; 25 | } 26 | 27 | if (window.gpwj === undefined) { 28 | window.gpwj = {}; 29 | } 30 | 31 | gpwj.templates = { 32 | fill: fill, 33 | fillList: fillList 34 | }; 35 | 36 | })(); -------------------------------------------------------------------------------- /Ch25_Sockets/HighFives_Sockets/auctionApp.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | 4 | var server = require('http').Server(app); 5 | var io = require('socket.io')(server); 6 | 7 | var bid = 5; 8 | 9 | io.on('connection', socketsRouter); 10 | 11 | function socketsRouter (socket) { 12 | 13 | socket.on('bid', makeBid); 14 | socket.on('state', getState); 15 | 16 | function makeBid () { 17 | bid = bid + 5; 18 | io.emit('update', { bid: bid }); 19 | } 20 | 21 | function getState () { 22 | socket.emit('update', { bid: bid }); 23 | } 24 | 25 | } 26 | 27 | app.use(express.static("public")); 28 | 29 | server.listen(1337); -------------------------------------------------------------------------------- /Ch25_Sockets/HighFives_Sockets/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "high-fives", 3 | "version": "1.0.0", 4 | "dependencies": { 5 | "express": "^4.13.4", 6 | "socket.io": "^1.4.6" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Ch25_Sockets/HighFives_Sockets/public/auction.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin:0; 3 | padding: 0; 4 | text-align:center; 5 | font-family:"Helvetica Neue", Helvetica, sans-serif; 6 | } 7 | 8 | h1 { 9 | background-color:rebeccapurple; 10 | color: #ffc; 11 | padding:0.5em; 12 | margin:0 0 1em; 13 | } 14 | 15 | table { 16 | width: 80%; 17 | margin:0 auto; 18 | border-collapse: collapse; 19 | } 20 | 21 | th, td { 22 | padding:0.3em; 23 | } 24 | 25 | th { 26 | background-color:rebeccapurple; 27 | color: #ffc; 28 | } 29 | 30 | td { 31 | border-bottom:1px solid rebeccapurple; 32 | } 33 | 34 | #bid { 35 | background-color: #eef; 36 | width:20%; 37 | } 38 | 39 | #asking { 40 | background-color: #fee; 41 | width:20%; 42 | } -------------------------------------------------------------------------------- /Ch25_Sockets/HighFives_Sockets/public/auction.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | High Fives Auctions 6 | 7 | 8 | 9 |

    High Fives Auctions

    10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
    ItemBidAskingAction
    The Fruitinator! Action Figure...loading......loading...
    29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Ch25_Sockets/HighFives_Sockets/public/auction.js: -------------------------------------------------------------------------------- 1 | var bid = document.getElementById("bid"); 2 | var asking = document.getElementById("asking"); 3 | var bidButton = document.getElementById("btnBid"); 4 | var socket = io('http://localhost:1337'); 5 | 6 | function updateDisplay (data) { 7 | bid.innerHTML = data.bid; 8 | asking.innerHTML = data.bid + 5; 9 | } 10 | 11 | function sendBid () { 12 | socket.emit('bid'); 13 | } 14 | 15 | bidButton.addEventListener("click", sendBid); 16 | 17 | socket.on('update', updateDisplay); 18 | socket.emit('state'); -------------------------------------------------------------------------------- /Ch25_Sockets/HighFives_SocketsRooms/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "high-fives", 3 | "version": "1.0.0", 4 | "dependencies": { 5 | "express": "^4.13.4", 6 | "socket.io": "^1.4.6" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Ch25_Sockets/HighFives_SocketsRooms/public/auction.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin:0; 3 | padding: 0; 4 | text-align:center; 5 | font-family:"Helvetica Neue", Helvetica, sans-serif; 6 | } 7 | 8 | h1 { 9 | background-color:rebeccapurple; 10 | color: #ffc; 11 | padding:0.5em; 12 | margin:0 0 1em; 13 | } 14 | 15 | table { 16 | width: 80%; 17 | margin:0 auto; 18 | border-collapse: collapse; 19 | } 20 | 21 | th, td { 22 | padding:0.3em; 23 | } 24 | 25 | th { 26 | background-color:rebeccapurple; 27 | color: #ffc; 28 | } 29 | 30 | td { 31 | border-bottom:1px solid rebeccapurple; 32 | } 33 | 34 | #item { 35 | width:50%; 36 | } 37 | 38 | #bid { 39 | background-color: #eef; 40 | width:20%; 41 | } 42 | 43 | #asking { 44 | background-color: #fee; 45 | width:20%; 46 | } -------------------------------------------------------------------------------- /Ch25_Sockets/HighFives_SocketsRooms/public/auction.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | High Fives Auctions 6 | 7 | 8 | 9 |

    High Fives Auctions

    10 | 11 |

    12 | 13 | 14 | 15 |

    16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 |
    ItemBidAskingAction
    35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Ch25_Sockets/TheCrypt/lib/game.js: -------------------------------------------------------------------------------- 1 | var buildMap = require('../lib/mapBuilder'); 2 | 3 | function Game (id, mapData) { 4 | this.id = id; 5 | this._players = []; 6 | 7 | this._firstPlace = buildMap(mapData); 8 | } 9 | 10 | Game.prototype = { 11 | getPlayersInPlace: function (placeTitle, playerToOmit) { 12 | var playersInPlace = []; 13 | 14 | this._players.forEach(function (player) { 15 | if (player === undefined || player !== playerToOmit) { 16 | var playerPlace = player.getPlace().getData(); 17 | 18 | if (playerPlace.title === placeTitle) { 19 | playersInPlace.push(player.getData()); 20 | } 21 | } 22 | }); 23 | 24 | return playersInPlace; 25 | }, 26 | 27 | addPlayer: function (player) { 28 | this._players.push(player); 29 | player.setPlace(this._firstPlace); 30 | } 31 | }; 32 | 33 | 34 | // exports 35 | 36 | module.exports = Game; -------------------------------------------------------------------------------- /Ch25_Sockets/TheCrypt/lib/gameManager.js: -------------------------------------------------------------------------------- 1 | var Game = require('./game'); 2 | var PlayerGame = require('./playerGame'); 3 | var mapData = require('../maps/theDarkHouse.json'); 4 | 5 | var games = {}; 6 | var playerGames = {}; 7 | 8 | 9 | // handy function 10 | 11 | function getID () { 12 | var id; 13 | 14 | do { 15 | id = Math.floor(Math.random() * 100000 + 1); 16 | } while (games[id]); 17 | 18 | return id; 19 | } 20 | 21 | 22 | // creating games for players 23 | 24 | function getNewGame () { 25 | var game = new Game(getID(), mapData); 26 | games[game.id] = game; 27 | 28 | return game; 29 | } 30 | 31 | function joinGame (playerName, id) { 32 | var game = games[id] || getNewGame(playerName); 33 | 34 | var playerGame = new PlayerGame(playerName, game); 35 | playerGames[game.id + "_" + playerName] = playerGame; 36 | 37 | return playerGame; 38 | } 39 | 40 | function getPlayerGame (playerName, id) { 41 | return playerGames[id + "_" + playerName]; 42 | } 43 | 44 | 45 | // exports 46 | 47 | module.exports = { 48 | join: joinGame, 49 | getPlayerGame: getPlayerGame 50 | }; -------------------------------------------------------------------------------- /Ch25_Sockets/TheCrypt/lib/place.js: -------------------------------------------------------------------------------- 1 | var Place = function (title, description) { 2 | var exits = {}; 3 | var items = []; 4 | var challenges = {}; 5 | 6 | this.addItem = function (item) { 7 | items.push(item); 8 | }; 9 | 10 | this.getLastItem = function () { 11 | return items.pop(); 12 | }; 13 | 14 | this.addExit = function (direction, exit) { 15 | exits[direction] = exit; 16 | }; 17 | 18 | this.getExit = function (direction) { 19 | return exits[direction]; 20 | }; 21 | 22 | this.addChallenge = function (direction, challenge) { 23 | challenges[direction] = challenge; 24 | }; 25 | 26 | this.getChallenge = function (direction) { 27 | return challenges[direction]; 28 | }; 29 | 30 | this.getData = function () { 31 | var data = { 32 | "title" : title, 33 | "description" : description, 34 | "items" : items.slice(), 35 | "exits" : Object.keys(exits) 36 | }; 37 | 38 | return data; 39 | }; 40 | }; 41 | 42 | module.exports = Place; -------------------------------------------------------------------------------- /Ch25_Sockets/TheCrypt/lib/player.js: -------------------------------------------------------------------------------- 1 | var Player = function (name, health) { 2 | var items = []; 3 | var place = null; 4 | 5 | this.addItem = function (item) { 6 | items.push(item); 7 | }; 8 | 9 | this.hasItem = function (item) { 10 | return items.indexOf(item) !== -1; 11 | }; 12 | 13 | this.removeItem = function (item) { 14 | var itemIndex = items.indexOf(item); 15 | if (itemIndex !== -1) { 16 | items.splice(itemIndex, 1); 17 | } 18 | }; 19 | 20 | this.setPlace = function (destination) { 21 | place = destination; 22 | }; 23 | 24 | this.getPlace = function () { 25 | return place; 26 | }; 27 | 28 | this.applyDamage = function (damage) { 29 | health = health - damage; 30 | }; 31 | 32 | this.getData = function () { 33 | var data = { 34 | "name" : name, 35 | "health" : health, 36 | "items" : items.slice() 37 | }; 38 | 39 | if (place !== null) { 40 | data.place = place.getData().title; 41 | } 42 | 43 | return data; 44 | }; 45 | }; 46 | 47 | module.exports = Player; -------------------------------------------------------------------------------- /Ch25_Sockets/TheCrypt/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jahvers-crypt-sockets", 3 | "version": "1.0.0", 4 | "description": "A text-based adventure game", 5 | "main": "gameServer.js", 6 | "dependencies": { 7 | "express": "^4.13.4", 8 | "socket.io": "^1.4.6" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Ch25_Sockets/TheCrypt/public/img/rock.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrlarsen/GetProgramming/9f89c8aaaaecd518c6fea61de94a4ecd129ab03a/Ch25_Sockets/TheCrypt/public/img/rock.jpg -------------------------------------------------------------------------------- /Ch25_Sockets/TheCrypt/public/img/sand.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrlarsen/GetProgramming/9f89c8aaaaecd518c6fea61de94a4ecd129ab03a/Ch25_Sockets/TheCrypt/public/img/sand.jpg -------------------------------------------------------------------------------- /Ch25_Sockets/TheCrypt/public/js/commands.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | function parseCommand (commandString) { 5 | var commandWords = commandString.split(" "); 6 | var command = { 7 | type: commandWords.shift() 8 | }; 9 | 10 | if (command.type === "go" || command.type === "use") { 11 | command.direction = commandWords.pop(); 12 | } 13 | 14 | command.item = commandWords.join(" "); 15 | 16 | return command; 17 | } 18 | 19 | function doAction () { 20 | var txtCommand = document.getElementById("txtCommand"); 21 | var commandString = txtCommand.value; 22 | var command = parseCommand(commandString); 23 | 24 | theCrypt.messageView.clear(); 25 | 26 | game.do(command); 27 | 28 | txtCommand.value = ""; 29 | txtCommand.focus(); 30 | } 31 | 32 | var commandButton = document.getElementById("btnCommand"); 33 | commandButton.addEventListener("click", doAction); 34 | 35 | })(); -------------------------------------------------------------------------------- /Ch25_Sockets/TheCrypt/public/js/dataLoader-socketio.js: -------------------------------------------------------------------------------- 1 | // dataLoader for use with socket.io 2 | 3 | (function () { 4 | "use strict"; 5 | 6 | var socket = io('http://localhost:1337'); 7 | 8 | function postAction (command) { 9 | var data = { 10 | gameID: theCrypt.gameID, 11 | playerName: theCrypt.playerName, 12 | command: command 13 | }; 14 | 15 | socket.emit(command.type, data); 16 | } 17 | 18 | function getStartData (callback) { 19 | var gameID = theCrypt.gameID; 20 | 21 | var data = { 22 | playerName: theCrypt.playerName 23 | }; 24 | 25 | if (gameID !== undefined && gameID !== "") { 26 | data.gameID = gameID; 27 | } 28 | 29 | socket.on('state', callback); 30 | 31 | socket.emit('start', data); 32 | } 33 | 34 | if (window.theCrypt === undefined) { 35 | window.theCrypt = {}; 36 | } 37 | 38 | theCrypt.data = { 39 | postAction: postAction, 40 | getStartData: getStartData 41 | }; 42 | 43 | })(); -------------------------------------------------------------------------------- /Ch25_Sockets/TheCrypt/public/js/gameController.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | function render (data) { 5 | theCrypt.mainView.render(); 6 | 7 | if (data.place) { 8 | theCrypt.placeView.render(data.place); 9 | } 10 | 11 | if (data.players) { 12 | theCrypt.playerView.render(data.players); 13 | } 14 | 15 | if (data.messages && data.messages.length) { 16 | theCrypt.messageView.render(data.messages.join('
    ')); 17 | } 18 | } 19 | 20 | function updateState (data) { 21 | theCrypt.gameID = data.gameID; 22 | render(data); 23 | } 24 | 25 | function init (playerName, gameID) { 26 | theCrypt.playerName = playerName; 27 | theCrypt.gameID = gameID; 28 | 29 | theCrypt.data.getStartData(updateState); 30 | } 31 | 32 | function doAction (command) { 33 | theCrypt.data.postAction(command, updateState); 34 | } 35 | 36 | // Assign the public interface 37 | window.game = { 38 | do: doAction, 39 | init: init 40 | }; 41 | 42 | })(); -------------------------------------------------------------------------------- /Ch25_Sockets/TheCrypt/public/js/mainView.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | var mainDiv = document.getElementById("main"); 5 | var startFormDiv = document.getElementById("startControls"); 6 | 7 | var userDetailsTemplate = document.getElementById("userDetailsTemplate").innerHTML; 8 | 9 | function showMain () { 10 | mainDiv.className = ""; 11 | } 12 | 13 | function renderUser () { 14 | startFormDiv.innerHTML = gpwj.templates.fill(userDetailsTemplate, { 15 | playerName: theCrypt.playerName, 16 | gameID: theCrypt.gameID 17 | }); 18 | } 19 | 20 | function render () { 21 | showMain(); 22 | renderUser(); 23 | } 24 | 25 | if (window.theCrypt === undefined) { 26 | window.theCrypt = {}; 27 | } 28 | 29 | theCrypt.mainView = { 30 | render: render 31 | }; 32 | 33 | })(); -------------------------------------------------------------------------------- /Ch25_Sockets/TheCrypt/public/js/messageView.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | var messageDiv = document.getElementById("messages"); 5 | var templateScript = document.getElementById("messageTemplate"); 6 | var template = templateScript.innerHTML; 7 | 8 | function render (message) { 9 | var data = { message: message }; 10 | messageDiv.innerHTML = gpwj.templates.fill(template, data); 11 | } 12 | 13 | function clear () { 14 | messageDiv.innerHTML = ""; 15 | } 16 | 17 | if (window.theCrypt === undefined) { 18 | window.theCrypt = {}; 19 | } 20 | 21 | theCrypt.messageView = { 22 | render: render, 23 | clear: clear 24 | }; 25 | 26 | })(); -------------------------------------------------------------------------------- /Ch25_Sockets/TheCrypt/public/js/startGame.js: -------------------------------------------------------------------------------- 1 | var btnStart = document.getElementById('btnStart'); 2 | 3 | btnStart.addEventListener('click', function () { 4 | var playerName = document.getElementById('txtPlayerName').value; 5 | var gameID = document.getElementById('txtGameID').value; 6 | 7 | game.init(playerName, gameID); 8 | }); -------------------------------------------------------------------------------- /Ch25_Sockets/TheCrypt/public/js/templates.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | function fill (template, data) { 5 | Object.keys(data).forEach(function (key) { 6 | var placeholder = "{{" + key + "}}"; 7 | var value = data[key]; 8 | 9 | while (template.indexOf(placeholder) !== -1) { 10 | template = template.replace(placeholder, value); 11 | } 12 | }); 13 | 14 | return template; 15 | } 16 | 17 | function fillList (template, dataArray) { 18 | var listString = ""; 19 | 20 | dataArray.forEach(function (data) { 21 | listString += fill(template, data); 22 | }); 23 | 24 | return listString; 25 | } 26 | 27 | if (window.gpwj === undefined) { 28 | window.gpwj = {}; 29 | } 30 | 31 | gpwj.templates = { 32 | fill: fill, 33 | fillList: fillList 34 | }; 35 | 36 | })(); -------------------------------------------------------------------------------- /js_next/listing2.10.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 2.10 3 | * Declaring and assigning a variable with let 4 | */ 5 | 6 | 7 | // declare the variable 8 | let score; 9 | 10 | // assign it a value 11 | score = 100; 12 | 13 | console.log(score); 14 | 15 | // assign a new value 16 | score = score + 50; 17 | 18 | console.log(score); 19 | 20 | 21 | 22 | /* Further Adventures 23 | * 24 | * 1) Assign a new value to the score variable. 25 | * 26 | * 2) Log the new value to the console. 27 | * 28 | * 3) Declare two more variables using let, 29 | * and assign them values. 30 | * 31 | */ -------------------------------------------------------------------------------- /js_next/listing2.11.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 2.11 3 | * Declaring and assigning a constant with const 4 | */ 5 | 6 | 7 | // declare a variable that may change 8 | let playerLocation = "The Dungeon"; 9 | 10 | // declare a variable that won't change 11 | const playerName = "Kandra"; 12 | 13 | console.log(playerName + " is in " + playerLocation); 14 | 15 | // assign a new value 16 | playerLocation = "The Old Library"; 17 | 18 | console.log(playerName + " is in " + playerLocation); 19 | 20 | 21 | 22 | /* Further Adventures 23 | * 24 | * 1) Try assigning a new value to playerName. 25 | * 26 | * Variables declared with const must be assigned 27 | * a value when they are declared. They cannot 28 | * have a new value assigned to them later. 29 | * 30 | * 2) Try separating the declaration of playerName 31 | * from its first assignment. 32 | * 33 | * const playerName; 34 | * playerName = "Kandra"; 35 | * 36 | */ -------------------------------------------------------------------------------- /js_next/listing2.12.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 2.12 3 | * Using template literals when logging variables 4 | */ 5 | 6 | 7 | let playerLocation = "The Dungeon"; 8 | const playerName = "Kandra"; 9 | 10 | // use backticks and placeholders to display values 11 | console.log(`${playerName} is in ${playerLocation}`); 12 | 13 | playerLocation = "The Old Library"; 14 | 15 | console.log(`${playerName} is in ${playerLocation}`); 16 | 17 | 18 | 19 | /* Further Adventures 20 | * 21 | * Place text between backticks to create a 22 | * template literal. 23 | * 24 | * 1) Change the location again and display the updated 25 | * player info. 26 | * 27 | * Variable values can be included in the template 28 | * by using a placeholder: 29 | * 30 | * `${variableName}` 31 | * 32 | * The value of the variable will replace the placeholder. 33 | * 34 | * 2) Create a new variable (using let or const). 35 | * 36 | * 3) Display the variable's value by using a template. 37 | * 38 | */ -------------------------------------------------------------------------------- /js_next/listing3.17.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.17 3 | * Using dot notation in templates 4 | */ 5 | 6 | 7 | const book = { 8 | title : "The Hobbit", 9 | author : "J. R. R. Tolkien", 10 | published : 1937 11 | }; 12 | 13 | console.log(`${book.title} by ${book.author}`); 14 | 15 | 16 | 17 | /* Further Adventures 18 | * 19 | * 1) Use a placeholder to include the published 20 | * property in the template string. 21 | * 22 | * 2) Add a second book. 23 | * 24 | * 3) Log its details to the console using a template. 25 | * 26 | * The book variable is declared as a constant. 27 | * 28 | * 4) Try to update one of the properties. 29 | * Does the program still work? 30 | * 31 | * book.published = 1938; 32 | * 33 | */ -------------------------------------------------------------------------------- /js_next/listing3.18.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.18 3 | * Assigning properties to variables 4 | */ 5 | 6 | 7 | const book = { 8 | title : "The Hobbit", 9 | author : "J. R. R. Tolkien", 10 | published : 1937 11 | }; 12 | 13 | // declare two variables whose names match 14 | // properties of the object. 15 | // assign the matching values to the variables 16 | 17 | const { title, author } = book; 18 | 19 | console.log(`${title} by ${author}`); 20 | 21 | 22 | 23 | /* Further Adventures 24 | * 25 | * Using curly braces on the left of an assignment, 26 | * 27 | * { name1, name2 } = myObject; 28 | * 29 | * assigns property values of the object on the right 30 | * to variables with matching names. 31 | * 32 | * The process is called object destructuring 33 | * 34 | * 1) Assign the published property to a matching variable. 35 | * 36 | * 2) Include the new variable in the template. 37 | * 38 | * The destructured variables are declared as constants. 39 | * 40 | * 4) Add a second book and try the destructuring 41 | * process again. 42 | * 43 | */ -------------------------------------------------------------------------------- /js_next/listing3.19.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.19 3 | * Assigning variables to matching properties 4 | */ 5 | 6 | const author = "Mark Twain"; 7 | const title = "The Adventures of Tom Sawyer"; 8 | 9 | const book = { 10 | author, 11 | title 12 | }; 13 | 14 | console.log(book); 15 | 16 | 17 | 18 | /* Further Adventures 19 | * 20 | * 1) Run the program. 21 | * 22 | * The book object is displayed on the console. 23 | * 24 | * When a variable name matches a property name 25 | * you want to assign, you can use the shorthand 26 | * shown in the listing above. 27 | * 28 | * 2) Change the program to use the longer syntax. 29 | * 30 | * e.g. for just the author property: 31 | * 32 | * const book = { 33 | * author: author 34 | * }; 35 | * 36 | * Does it still work? 37 | * 38 | * 3) Add a third variable and matching property 39 | * using the shorthand. 40 | * 41 | */ -------------------------------------------------------------------------------- /js_next/listing3.20.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 3.20 3 | * Updating objects assigned to constants 4 | */ 5 | 6 | const player1 = { 7 | name: "Max", 8 | attempted: 0, 9 | correct: 0 10 | }; 11 | 12 | player1.attempted = 1; 13 | player1.correct = 1; 14 | player1.score = 50; 15 | 16 | const playerInfo = ` 17 | * ${player1.name} 18 | * has score 19 | * ${player1.score} 20 | `; 21 | 22 | console.log(playerInfo); 23 | 24 | 25 | 26 | /* Further Adventures 27 | * 28 | * 1) Add more lines to the program to 29 | * update the name and score. 30 | * 31 | * 2) Log the updated player info to the console. 32 | * 33 | * You can only assign a value once to a variable 34 | * declared with const. However, if you assign an 35 | * object to the variable, you can update the 36 | * variable's properties. 37 | * 38 | * 3) At the end of the program, 39 | * try assigning a new object to player1: 40 | * 41 | * player1 = { name: "Kandra" }; 42 | * 43 | * 4) Play with the playerInfo template to make 44 | * the info logged more interesting. 45 | * 46 | * Template strings can span multiple lines. 47 | * 48 | */ -------------------------------------------------------------------------------- /js_next/listing4.15.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 4.15 3 | * Using fat arrow notation 4 | */ 5 | 6 | const sayHello = () => { 7 | console.log("Hello World!"); 8 | }; 9 | 10 | sayHello(); 11 | sayHello(); 12 | sayHello(); 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * 1) Change the message from the sayHello function. 19 | * 20 | * Enclose the message in backticks to spread it 21 | * across multiple lines. 22 | * 23 | * 2) Break the Hello World! message across two lines. 24 | * 25 | * 3) Create a function that prints the letters 26 | * of "Hello World!" one by one down the page. 27 | * 28 | */ -------------------------------------------------------------------------------- /js_next/listing4.16.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 4.16 3 | * Displaying a menu using a template string 4 | */ 5 | 6 | const displayMenu = () => { 7 | console.log(` 8 | Please choose an option: 9 | (1) Print log 10 | (2) Upload file 11 | (9) Quit 12 | ` ); 13 | }; 14 | 15 | displayMenu(); 16 | 17 | 18 | 19 | /* Further Adventures 20 | * 21 | * 1) Add two more options to the displayMenu 22 | * function and run the program. 23 | * 24 | * 2) Create your own displayMyMenu function. 25 | * 26 | * 3) Add a line to call your function as well. 27 | * Run the program 28 | * 29 | */ -------------------------------------------------------------------------------- /js_next/listing4.17.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 4.17 3 | * A function to display player information 4 | */ 5 | 6 | let player; 7 | 8 | const player1 = { 9 | name: "Kandra", 10 | place: "The Dungeon of Doom", 11 | health: 50 12 | }; 13 | 14 | const player2 = { 15 | name: "Dax", 16 | place: "The Old Library", 17 | health: 40 18 | }; 19 | 20 | const showPlayerInfo = () => { 21 | const { name, place, health } = player; 22 | console.log(` 23 | ${name} 24 | ------------------------------ 25 | ${name} is in ${place} 26 | ${name} has health ${health} 27 | ------------------------------ 28 | ` ); 29 | }; 30 | 31 | player = player1; 32 | showPlayerInfo(); 33 | 34 | player = player2; 35 | showPlayerInfo(); 36 | 37 | 38 | 39 | /* Further Adventures 40 | * 41 | * 1) Write a function that just shows 42 | * where the player is. 43 | * 44 | * 2) Write a function that just shows 45 | * the player's health. 46 | * 47 | * 3) Change the showPlayerInfo function 48 | * to use your two functions. 49 | * 50 | */ -------------------------------------------------------------------------------- /js_next/listing5.15.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 5.15 3 | * Calling the same function with different arguments 4 | */ 5 | 6 | const showMessage = message => console.log(`The message is: ${message}`); 7 | 8 | showMessage("It's full of stars!"); 9 | showMessage("Hello to Jason Isaacs"); 10 | showMessage("Hello to Jason Isaacs and Stephen Fry"); 11 | 12 | 13 | 14 | /* Further Adventures 15 | * 16 | * 1) Create a showMessage2 function to 17 | * display its prefixed text on a 18 | * separate line to the message. 19 | * 20 | * 2) Declare a myMessage variable and 21 | * assign it a string value. 22 | * 23 | * 3) Call the showMessage2 function with 24 | * myMessage as the argument. 25 | * 26 | */ -------------------------------------------------------------------------------- /js_next/listing5.16.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 5.16 3 | * Defining a function with a default argument 4 | */ 5 | 6 | const showMessage = (message = "Hello World!") => { 7 | console.log(`The message is: ${message}`); 8 | }; 9 | 10 | showMessage("It's full of stars!"); 11 | showMessage("Hello to Jason Isaacs"); 12 | showMessage(); 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * 1) Add a second parameter to the function 19 | * called prefix. 20 | * 21 | * 2) Change the template string to log the 22 | * prefix followed by the message. 23 | * 24 | * 3) Include a default value for the prefix. 25 | * 26 | */ -------------------------------------------------------------------------------- /js_next/listing5.17.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 5.17 3 | * Using the square function 4 | */ 5 | 6 | const square = numberToSquare => { 7 | const result = numberToSquare ** 2; 8 | console.log(`${numberToSquare} * ${numberToSquare} = ${result}`); 9 | }; 10 | 11 | square(10); 12 | square(-2); 13 | square(1111); 14 | square(0.5); 15 | 16 | 17 | 18 | /* Further Adventures 19 | * 20 | * 1) Define a cube function that cubes 21 | * any number passed in as an argument. 22 | * 23 | * 2) Test your cube function 24 | * four times with different arguments. 25 | * 26 | * Math.sqrt is a built-in function to find 27 | * the positive square root of a number. 28 | * e.g. Math.sqrt(9) finds the square root of 9. 29 | * 30 | * 3) Define and test a squareRoot function 31 | * to find square roots and display 32 | * them on the console. 33 | * e.g. The square root of 9 is 3. 34 | * 35 | */ -------------------------------------------------------------------------------- /js_next/listing5.18.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 5.18 3 | * A function with two arguments 4 | */ 5 | 6 | const showSum = (number1, number2) => { 7 | const total = number1 + number2; 8 | console.log(`The sum is ${total}`); 9 | }; 10 | 11 | showSum(30, 23); 12 | showSum(2.8, -5); 13 | 14 | 15 | 16 | /* Further Adventures 17 | * 18 | * 1) Use the showSum function to add 56 and 74. 19 | * 20 | * To multiply two numbers, use the * symbol. 21 | * e.g. 3 * 5 is 3 multiplied by 5. 22 | * 23 | * 2) Create a showProduct function to multiply two numbers. 24 | * 25 | * 3) Use your function to multiply three pairs of numbers. 26 | * 27 | * To divide one number by another, use /. 28 | * e.g. 10 / 2 is 10 divided by 2. 29 | * 30 | * 4) What about showDifference and showQuotient 31 | * for subtraction and division? 32 | * 33 | */ -------------------------------------------------------------------------------- /js_next/listing6.11.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 6.11 3 | * Returning a value from a function 4 | */ 5 | 6 | const getMessage = () => "I’m going on an adventure!"; 7 | 8 | const response = getMessage(); 9 | 10 | console.log(response); 11 | 12 | 13 | 14 | /* Further Adventures 15 | * 16 | * 1) Write a getMyMessage function 17 | * that returns a message of 18 | * your choosing. 19 | * 20 | */ -------------------------------------------------------------------------------- /js_next/listing6.12.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 6.12 3 | * Using the return value as an argument 4 | */ 5 | 6 | const getHelloTo = name => `Hello to ${name}`; 7 | 8 | console.log(getHelloTo("Kandra")); 9 | console.log(getHelloTo("Dax")); 10 | 11 | 12 | 13 | /* Further Adventures 14 | * 15 | * 1) Rewrite the function using curly braces 16 | * for the function body and an explicit 17 | * return statement. 18 | * 19 | * 2) Run the program to check the output 20 | * is unaffected by the change in form. 21 | * 22 | * Do you prefer the function with or without 23 | * the return statement? 24 | * 25 | */ -------------------------------------------------------------------------------- /js_next/listing6.13.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 6.13 3 | * Returning the sum of two numbers 4 | */ 5 | 6 | const add = (x, y) => x + y; 7 | 8 | const sum = add(50, 23); 9 | 10 | console.log(sum); 11 | 12 | 13 | 14 | /* Further Adventures 15 | * 16 | * 1) Find and display the sum of 17 | * a different pair of numbers 18 | * 19 | * 2) Change the call to console.log so that 20 | * the display on the console reads: 21 | * 'The sum of 50 and 23 is 73' 22 | * using the add function to generate the answer. 23 | * 24 | * 3) Can you use the add function as it is 25 | * to add more than two numbers? 26 | * Hint: You can nest calls to add. 27 | * 28 | * 4) Create a function to return the sum of 29 | * three numbers given as arguments. 30 | * 31 | */ -------------------------------------------------------------------------------- /js_next/listing7.12.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 7.12 3 | * Destructuring an object argument 4 | */ 5 | 6 | const planet1 = { 7 | name: "Jupiter", 8 | position: 5, 9 | type: "Gas Giant", 10 | radius: 69911, 11 | sizeRank: 1 12 | }; 13 | 14 | const getPlanetInfo = planet => { 15 | const { name, position } = planet; 16 | return `${name}: planet number ${position}`; 17 | }; 18 | 19 | console.log(getPlanetInfo(planet1)); 20 | 21 | 22 | 23 | /* Further Adventures 24 | * 25 | * 1) Create a second planet object. 26 | * 27 | * 2) Use getPlanetInfo to log details of 28 | * the second planet. 29 | * 30 | * 3) Update the getPlanetInfo function to 31 | * include more information about 32 | * each planet. 33 | * 34 | */ -------------------------------------------------------------------------------- /js_next/listing7.13.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 7.13 3 | * Shorthand properties and argument destructuring 4 | */ 5 | 6 | const buildPlanet = function (name, position, type, radius, rank) { 7 | return { 8 | name, 9 | position, 10 | type, 11 | radius, 12 | sizeRank: rank 13 | }; 14 | }; 15 | 16 | const getPlanetInfo = ({name, position}) => `${name.toUpperCase()}: planet ${position}`; 17 | 18 | const planet1 = buildPlanet("Jupiter", 5, "Gas Giant", 69911, 1); 19 | const planet2 = buildPlanet("Neptune", 8, "Ice Giant", 24622, 4); 20 | 21 | console.log(getPlanetInfo(planet1)); 22 | console.log(getPlanetInfo(planet2)); 23 | 24 | 25 | 26 | /* Further Adventures 27 | * 28 | * 1) Create a getPlanetInfo2 function that 29 | * uses destructuring to gather other planet 30 | * properties and returns a different string 31 | * of info. 32 | * 33 | */ -------------------------------------------------------------------------------- /js_next/listing7.14.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 7.14 3 | * Renaming properties when object destructuring 4 | */ 5 | 6 | const move = ({x, y}, {x: dx, y: dy}) => ({x: x + dx, y: y + dy}); 7 | 8 | const showPoint = ({x, y}) => console.log(`( ${x} , ${y} )`); 9 | 10 | const point1 = { x : 2, y : 5 }; 11 | 12 | const point2 = move(point1, { x : 4, y : -2 }); 13 | 14 | showPoint(point1); 15 | console.log("Move 4 across and 2 down"); 16 | showPoint(point2); 17 | 18 | 19 | 20 | /* Further Adventures 21 | * 22 | * 1) Change the amount by which the point is moved 23 | * by altering the x and y properties of 24 | * the object literal passed to the move function. 25 | * 26 | * 2) Write a reflectX function that reflects 27 | * a point in the x-axis, returning the new point. 28 | * 29 | * 3) How about a rotate90 function that rotates 30 | * the point by 90 degrees anticlockwise 31 | * around ( 0 , 0 )? 32 | * 33 | */ -------------------------------------------------------------------------------- /js_next/listing7.15.js: -------------------------------------------------------------------------------- 1 | /* Get Programming with JavaScript 2 | * Listing 7.15 3 | * Shorthand object methods and padding 4 | */ 5 | 6 | var spacer = { 7 | blank() { 8 | return ""; 9 | }, 10 | 11 | newLine() { 12 | return "\n"; 13 | }, 14 | 15 | line(length, character) { 16 | return ''.padStart(length, character); 17 | }, 18 | 19 | wrap(text, length, character) { 20 | return (character + " " + text).padEnd(length - 1) + character; 21 | }, 22 | 23 | box(text, length, character) { 24 | const border = spacer.line(length, character); 25 | const wrapText = spacer.wrap(text, length, character); 26 | 27 | return ` 28 | ${border} 29 | ${wrapText} 30 | ${border} 31 | `; 32 | } 33 | }; 34 | 35 | console.log(spacer.box("Mercury", 11, "=")); 36 | console.log(spacer.box("Mars", 11, "*")); 37 | 38 | 39 | 40 | /* Further Adventures 41 | * 42 | * 1) Change the Spacer.box function so that 43 | * the box is 5 lines high. 44 | * 45 | * Spacer.box("Earth"); 46 | * 47 | * > ========= 48 | * > = = 49 | * > = Earth = 50 | * > = = 51 | * > ========= 52 | * 53 | */ -------------------------------------------------------------------------------- /projects/theCrypt_Node/index.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | var path = require('path'); 4 | var apiRouter = require('./api'); 5 | 6 | app.use(express.static(path.resolve(__dirname, "public"))); 7 | app.use('/api', apiRouter); 8 | 9 | app.listen(1337); -------------------------------------------------------------------------------- /projects/theCrypt_Node/lib/game.js: -------------------------------------------------------------------------------- 1 | var Player = require('./player'); 2 | var gameCounter = 0; 3 | 4 | function getID () { 5 | gameCounter += 1; 6 | return gameCounter; 7 | } 8 | 9 | function Game (playerName, playerHealth, firstPlace) { 10 | this.id = getID(); 11 | this.messages = []; 12 | 13 | this.player = new Player(playerName, playerHealth); 14 | this.player.setPlace(firstPlace); 15 | 16 | this.inPlay = true; 17 | } 18 | 19 | Game.prototype = { 20 | getData: function () { 21 | var player = this.player; 22 | var place = player.getPlace(); 23 | 24 | return { 25 | gameID: this.id, 26 | player: player.getData(), 27 | place: place.getData(), 28 | messages: this.messages, 29 | inPlay: this.inPlay 30 | }; 31 | }, 32 | 33 | clearMessages: function () { 34 | this.messages = []; 35 | }, 36 | 37 | addMessage: function (message) { 38 | this.messages.push(message); 39 | } 40 | }; 41 | 42 | module.exports = Game; -------------------------------------------------------------------------------- /projects/theCrypt_Node/lib/gameCache.js: -------------------------------------------------------------------------------- 1 | var Game = require('./game'); 2 | var games = {}; 3 | 4 | var buildMap = require('./mapBuilder'); 5 | var mapData = require('../maps/TheDarkHouse.json'); 6 | 7 | function startGame (playerName, playerHealth) { 8 | var map = buildMap(mapData); 9 | var place = map.store[map.firstPlace]; 10 | 11 | var game = new Game(playerName, playerHealth, place); 12 | 13 | games[game.id] = game; 14 | return game; 15 | } 16 | 17 | function endGame (id) { 18 | delete games[id]; 19 | } 20 | 21 | function getGame (id) { 22 | return games[id]; 23 | } 24 | 25 | module.exports = { 26 | start: startGame, 27 | end: endGame, 28 | get: getGame 29 | }; -------------------------------------------------------------------------------- /projects/theCrypt_Node/lib/place.js: -------------------------------------------------------------------------------- 1 | var Place = function (title, description) { 2 | var exits = {}; 3 | var items = []; 4 | var challenges = {}; 5 | 6 | this.addItem = function (item) { 7 | items.push(item); 8 | }; 9 | 10 | this.getLastItem = function () { 11 | return items.pop(); 12 | }; 13 | 14 | this.addExit = function (direction, exit) { 15 | exits[direction] = exit; 16 | }; 17 | 18 | this.getExit = function (direction) { 19 | return exits[direction]; 20 | }; 21 | 22 | this.addChallenge = function (direction, challenge) { 23 | challenges[direction] = challenge; 24 | }; 25 | 26 | this.getChallenge = function (direction) { 27 | return challenges[direction]; 28 | }; 29 | 30 | this.getData = function () { 31 | var data = { 32 | "title" : title, 33 | "description" : description, 34 | "items" : items.slice(), 35 | "exits" : Object.keys(exits) 36 | }; 37 | 38 | return data; 39 | }; 40 | }; 41 | 42 | module.exports = Place; -------------------------------------------------------------------------------- /projects/theCrypt_Node/lib/player.js: -------------------------------------------------------------------------------- 1 | var Player = function (name, health) { 2 | var items = []; 3 | var place = null; 4 | 5 | this.addItem = function (item) { 6 | items.push(item); 7 | }; 8 | 9 | this.hasItem = function (item) { 10 | return items.indexOf(item) !== -1; 11 | }; 12 | 13 | this.removeItem = function (item) { 14 | var itemIndex = items.indexOf(item); 15 | if (itemIndex !== -1) { 16 | items.splice(itemIndex, 1); 17 | } 18 | }; 19 | 20 | this.setPlace = function (destination) { 21 | place = destination; 22 | }; 23 | 24 | this.getPlace = function () { 25 | return place; 26 | }; 27 | 28 | this.applyDamage = function (damage) { 29 | health = health - damage; 30 | }; 31 | 32 | this.getData = function () { 33 | var data = { 34 | "name" : name, 35 | "health" : health, 36 | "items" : items.slice() 37 | }; 38 | 39 | if (place !== null) { 40 | data.place = place.title; 41 | } 42 | 43 | return data; 44 | }; 45 | }; 46 | 47 | module.exports = Player; -------------------------------------------------------------------------------- /projects/theCrypt_Node/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "the-crypt-node", 3 | "version": "1.0.0", 4 | "private": true, 5 | "description": "A text-based adventure game", 6 | "main": "index.js", 7 | "scripts": { 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "author": "thecrypt@room51.co.uk", 11 | "dependencies": { 12 | "express": "^4.13.4" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /projects/theCrypt_Node/public/img/rock.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrlarsen/GetProgramming/9f89c8aaaaecd518c6fea61de94a4ecd129ab03a/projects/theCrypt_Node/public/img/rock.jpg -------------------------------------------------------------------------------- /projects/theCrypt_Node/public/img/sand.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jrlarsen/GetProgramming/9f89c8aaaaecd518c6fea61de94a4ecd129ab03a/projects/theCrypt_Node/public/img/sand.jpg -------------------------------------------------------------------------------- /projects/theCrypt_Node/public/js/commands.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | function parseCommand (commandString) { 5 | var commandWords = commandString.split(" "); 6 | var command = { 7 | type: commandWords.shift() 8 | }; 9 | 10 | if (command.type === "go" || command.type === "use") { 11 | command.direction = commandWords.pop(); 12 | } 13 | 14 | command.item = commandWords.join(" "); 15 | 16 | return command; 17 | } 18 | 19 | function doAction () { 20 | var txtCommand = document.getElementById("txtCommand"); 21 | var commandString = txtCommand.value; 22 | var command = parseCommand(commandString); 23 | 24 | theCrypt.messageView.clear(); 25 | 26 | game.do(command); 27 | 28 | txtCommand.value = ""; 29 | txtCommand.focus(); 30 | } 31 | 32 | var commandButton = document.getElementById("btnCommand"); 33 | commandButton.addEventListener("click", doAction); 34 | 35 | })(); -------------------------------------------------------------------------------- /projects/theCrypt_Node/public/js/gameController.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | function render (data) { 5 | theCrypt.placeView.render(data.place); 6 | theCrypt.playerView.render(data.player); 7 | if (data.messages !== undefined) { 8 | renderMessages(data.messages); 9 | } 10 | } 11 | 12 | function renderMessage (message) { 13 | theCrypt.messageView.render(message); 14 | } 15 | 16 | function renderMessages (messages) { 17 | messages.forEach(renderMessage); 18 | } 19 | 20 | function init () { 21 | gpwj.data.getStartData(function (data) { 22 | render(data); 23 | theCrypt.gameID = data.gameID; 24 | }); 25 | } 26 | 27 | function doAction (command) { 28 | gpwj.data.postAction(theCrypt.gameID, command, function (data) { 29 | render(data); 30 | }); 31 | } 32 | 33 | // Assign the public interface 34 | window.game = { 35 | do: doAction, 36 | init: init, 37 | message: renderMessage 38 | }; 39 | 40 | })(); -------------------------------------------------------------------------------- /projects/theCrypt_Node/public/js/messageView.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | var messageDiv = document.getElementById("messages"); 5 | var templateScript = document.getElementById("messageTemplate"); 6 | var template = templateScript.innerHTML; 7 | 8 | function render (message) { 9 | var data = { message: message }; 10 | messageDiv.innerHTML = gpwj.templates.fill(template, data); 11 | } 12 | 13 | function clear () { 14 | messageDiv.innerHTML = ""; 15 | } 16 | 17 | if (window.theCrypt === undefined) { 18 | window.theCrypt = {}; 19 | } 20 | 21 | theCrypt.messageView = { 22 | render: render, 23 | clear: clear 24 | }; 25 | 26 | })(); -------------------------------------------------------------------------------- /projects/theCrypt_Node/public/js/playerView.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | var playerDiv = document.getElementById("player"); 5 | var playerScript = document.getElementById("playerTemplate"); 6 | var itemScript = document.getElementById("itemTemplate"); 7 | 8 | var playerTemplate = playerScript.innerHTML; 9 | var itemTemplate = itemScript.innerHTML; 10 | 11 | function render (data) { 12 | var itemsDiv; 13 | 14 | var items = data.items.map(function (itemName) { 15 | return { item : itemName }; 16 | }); 17 | 18 | playerDiv.innerHTML = gpwj.templates.fill(playerTemplate, data); 19 | 20 | itemsDiv = document.getElementById("playerItems"); 21 | itemsDiv.innerHTML = gpwj.templates.fillList(itemTemplate, items); 22 | } 23 | 24 | if (window.theCrypt === undefined) { 25 | window.theCrypt = {}; 26 | } 27 | 28 | theCrypt.playerView = { 29 | render: render 30 | }; 31 | 32 | })(); -------------------------------------------------------------------------------- /projects/theCrypt_Node/public/js/templates.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | "use strict"; 3 | 4 | function fill (template, data) { 5 | Object.keys(data).forEach(function (key) { 6 | var placeholder = "{{" + key + "}}"; 7 | var value = data[key]; 8 | 9 | while (template.indexOf(placeholder) !== -1) { 10 | template = template.replace(placeholder, value); 11 | } 12 | }); 13 | 14 | return template; 15 | } 16 | 17 | function fillList (template, dataArray) { 18 | var listString = ""; 19 | 20 | dataArray.forEach(function (data) { 21 | listString += fill(template, data); 22 | }); 23 | 24 | return listString; 25 | } 26 | 27 | if (window.gpwj === undefined) { 28 | window.gpwj = {}; 29 | } 30 | 31 | gpwj.templates = { 32 | fill: fill, 33 | fillList: fillList 34 | }; 35 | 36 | })(); --------------------------------------------------------------------------------