web coding with javascript handout - gigalearnit.com...javascript, we’ll need to open a text...

11
Web Coding with JavaScript Getting Started From Teaching Coding through Game Creation by Sarah Kepple © 2018 1 We’ll start by working directly in the JavaScript console, which can carry out entered JavaScript expressions. Open a browser such as Chrome or Firefox. (Windows) CTRL, SHIFT, and J or (), OPTION, and J (Windows) COMMAND, OPTION, and K or (), OPTION, and K Step 1 Variables Define and Call a Variable Create a variable called myScore and assign it the value of zero: var myScore = 0 Click enter to store the value Call the value of myScore: myScore Reassign Variables Change myScore’s content to a string: myScore = “awesome” Call the reassigned variable: myScore Reassign it back to a number: myScore = 0 Change Variable Values Increment the value of myScore: ++myScore Increment again to add one to the new value: ++myScore Now decrement a few times: --myScore ++ increment or increase the value of a variable by one -- decrement or decrease the value of a varaiable by one

Upload: others

Post on 23-Jul-2020

13 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Web Coding with JavaScript Handout - gigalearnit.com...JavaScript, we’ll need to open a text editor. Open Komodo Edit & Create a New File Create a basic HTML page (the JavaScript

Web Coding with JavaScript Getting Started

From Teaching Coding through Game Creation by Sarah Kepple © 2018

1

We’ll start by working directly in the JavaScript console, which can carry out entered JavaScript expressions. Open a browser such as Chrome or Firefox.

(Windows) CTRL, SHIFT, and J or ()⌘, OPTION, and J

(Windows) COMMAND, OPTION, and K or ()⌘, OPTION, and K

Step 1 Variables Define and Call a Variable

Create a variable called myScore and assign it the value of zero: var myScore = 0 Click enter to store the value Call the value of myScore: myScore

Reassign Variables Change myScore’s content to a string: myScore = “awesome” Call the reassigned variable: myScore Reassign it back to a number: myScore = 0

Change Variable Values Increment the value of myScore: ++myScore Increment again to add one to the new value: ++myScore Now decrement a few times: --myScore

++ increment or increase the value of a variable by one -- decrement or decrease the value of a varaiable by one

Page 2: Web Coding with JavaScript Handout - gigalearnit.com...JavaScript, we’ll need to open a text editor. Open Komodo Edit & Create a New File Create a basic HTML page (the JavaScript

Web Coding with JavaScript Getting Started

From Teaching Coding through Game Creation by Sarah Kepple © 2018

2

Change the value by more than one by using the += and -= operators: myScore += 4

Variable Equals Variable

Use a variable to reassign its own value: myScore=myScore+3

Step 2 Arrays an array is a variable that can store multiple, indexed values

Create an array to store the names of the Lost Boys: var lostBoysArray = [“Tootles”, “Nibs”, “Slightly”, “Curly”, “The Twins” ] Call an element: lostBoysArray[1]

*Note that the indexing is zero based (Nibs is assigned the value of 1 rather than Tootles)

Page 3: Web Coding with JavaScript Handout - gigalearnit.com...JavaScript, we’ll need to open a text editor. Open Komodo Edit & Create a New File Create a basic HTML page (the JavaScript

Web Coding with JavaScript The Name of the Queen

From Teaching Coding through Game Creation by Sarah Kepple © 2018

3

This game is based on the classic fairytale “Rumpelstiltskin” in which the miller brags erroneously to the king that his daughter can spin straw into gold. Read the short story here: https://tinyurl.com/GrimmRumpel Interestingly, although the story’s plot revolves around guessing Rumpelstiltskin’s name, he is the only character whose name the reader ever learns. The girl is referred to only as the miller’s daughter or the queen. In our game, we’ll turn the tables, and ask players to guess her name.

Step 1 Create the File Structure We’ve been working directly in the console, but to create a program using JavaScript, we’ll need to open a text editor. Open Komodo Edit & Create a New File Create a basic HTML page (the JavaScript code will live inside of it) Save as TheNameOfTheQueen.html inside a new folder called JSfiles Place the rumple.png image in the JSfiles folder also

Step 2 HTML Elements The JavaScript controls how a page functions, but HTML provides the content. Let’s add that content.

ID Attribute Add four paragraph lines in the body Add an id attribute inside each opening <p> tag Insert a <br> to bump “Choose a letter” onto it’s own line: <p id="line1"> The Queen guessed my name, but can you guess hers? <br> Choose a letter. </p> <p id="letterBlanks"> </p> <p id="line2"> </p> <p id="line3"> </p> Save and Open in Browser

id attribute specifies a unique name for an html element

Page 4: Web Coding with JavaScript Handout - gigalearnit.com...JavaScript, we’ll need to open a text editor. Open Komodo Edit & Create a New File Create a basic HTML page (the JavaScript

Web Coding with JavaScript The Name of the Queen

From Teaching Coding through Game Creation by Sarah Kepple © 2018

4

Input Create a text box for player to enter guess: <input id ="guess" type="text" value=""/> Create button to submit guess: <input type="button" value="Submit" onclick="letterGuess();"/> Add the rumpel.png image: <p><img src="rumpel.png"/></p>

input element specifies a field in which the user can enter data

id attribute allows JavaScript to pull the data entered type attribute specifies the input object to be created value attribute defines the default content to display onclick attribute launches the designated sequence when the button is activated

Save and Refresh Browser to Test The results should appear similar to the image below, however, the button will not actually trigger anything yet because we haven’t created the script to run yet. We’ll start working with JavaScript next…

Page 5: Web Coding with JavaScript Handout - gigalearnit.com...JavaScript, we’ll need to open a text editor. Open Komodo Edit & Create a New File Create a basic HTML page (the JavaScript

Web Coding with JavaScript The Name of the Queen

From Teaching Coding through Game Creation by Sarah Kepple © 2018

5

Step 3 Set-up The JavaScript code will live within the HTML tags for it <script></script>. Add the script tags & Create an array of possible Queen names: <script> var names = ["liesl", "gretl", "marta", "brigitta", "louisa"] </script>

Math Methods Create a variable called secretName Assign it to the randomly selected name from the array: var secretName = names[Math.floor(Math.random() * names.length)]

Math.random() method returns a non-predictable floating-point (decimal) number between 0 and 1

Math.floor()method rounds a number down to the nearest integer

Answer Array

We’ll give players a hint by displaying a blank for each letter in the name, filling them in with each correct guess.

Create a variable to store a blank array: var answerArray = [] Create a for loop with a variable “n” If “n” is less than the number of letters in the random name, increment “n” until it isn’t: for (var n=0; n<secretName.length;n++){ answerArray[n]="_" }

length property returns the number of entries in an array, but when used with a string it returns the number of characters in the string

Page 6: Web Coding with JavaScript Handout - gigalearnit.com...JavaScript, we’ll need to open a text editor. Open Komodo Edit & Create a New File Create a basic HTML page (the JavaScript

Web Coding with JavaScript The Name of the Queen

From Teaching Coding through Game Creation by Sarah Kepple © 2018

6

Get Element by ID Use the getElementById() method to

call and print the number of blanks on the screen: document.getElementById("letterBlanks").innerHTML = (answerArray.join(" "))

getElementById() method returns the assigned HTML element innerHTML property sets or returns the HTML content of the element

Save and Refresh Browser to Test Blank lines representing each letter of one of the words in the array should display. The quantity of blanks will vary each time the page is refreshed.

Step 4 Check and Report Create a custom function to check if the letter guessed is in the secretName, and if so, return the letter in place of the appropriate blank

Define the Function: function letterGuess(){ }

a function is a block of code intended to perform a particular task

Retrieve Guess: function letterGuess(){ var playerGuess = document.getElementById(“guess”) }

Test and Update Loop Using a for loop, create a variable(L) and set it to increment until it matches the value of the number of letters in secretName: for (var L = 0; L<secretName.length; L++){ }

Page 7: Web Coding with JavaScript Handout - gigalearnit.com...JavaScript, we’ll need to open a text editor. Open Komodo Edit & Create a New File Create a basic HTML page (the JavaScript

Web Coding with JavaScript The Name of the Queen

From Teaching Coding through Game Creation by Sarah Kepple © 2018

7

Add an if statement to check and see if L character of secretName is equal to the value of the playerGuess. So if the secretName is “gretl” and the playerGuess is “e”, then the if statement will be true the third time that the loop runs: for (var L = 0; L<secretName.length; L++){ if (secretName[L] === playerGuess.value) { answerArray[L] = playerGuess.value } }

Report Correct Letter Copy and paste the same getElementById line that we used prior to starting the letter Guess() function: for (var L = 0; L<secretName.length; L++){ if (secretName[L] === playerGuess.value) { answerArray[L] = playerGuess.value } } document.getElementById("letterBlanks").innerHTML = (answerArray.join(" ")) }

Save and Refresh Browser to Test After a correct letter is guessed, it should appear in place of the appropriate blank or blanks. Remember that the for loop continues to run after the first match, so if a player guesses a letter that appears more than once in the same word, all instances will fill in.

Page 8: Web Coding with JavaScript Handout - gigalearnit.com...JavaScript, we’ll need to open a text editor. Open Komodo Edit & Create a New File Create a basic HTML page (the JavaScript

Web Coding with JavaScript The Name of the Queen

From Teaching Coding through Game Creation by Sarah Kepple © 2018

8

Step 5 Respond if Correct Create a variable called LetterDashes to store the number of initial blanks and

place it abouve the function letterGuess(): var LetterDashes = secretName.length

* use two minus signs (- -), rather than a long dash(—)

Decrement LetterDashes for each correct letter guessed by adding a line to the if statement in cunction letterGuess(): if (secretName[L] === playerGuess.value) { answerArray[L] = playerGuess.value LetterDashes-- }

Add a second if statement inside of the first to check to see if LetterDashes is less than 1, and if so, it will congratulate the player by updating the text in the HTML paragraph element identified as “line 3”: LetterDashes-- if (LetterDashes<1) { document.getElementById("line3").innerHTML = "Good job!\ It was "+secretName }

Page 9: Web Coding with JavaScript Handout - gigalearnit.com...JavaScript, we’ll need to open a text editor. Open Komodo Edit & Create a New File Create a basic HTML page (the JavaScript

Web Coding with JavaScript The Name of the Queen

From Teaching Coding through Game Creation by Sarah Kepple © 2018

9

Save and Refresh Browser to Test When all letters have been correctly guessed, the player should see the congratulatory message. Notice that if a player accidentally submits a correct letter that has previously been submitted, it throws things off. For instance, if the secretName is gretl, and the player guesses g,r,e,t, and

then t again, the congrats message appears, even though the name hasn’t been solved with the final letter l. This is because the if statement that decrements LetterDashes still evaluates to true if t is guessed twice, since t is in secretName. To solve this, we need to add another condition to the if statement to check that the letter is not already in the answerArray.

&& (And) != (Not Equal)

Update the first if statement in the function letterGuess() from this: if (secretName[L] === playerGuess.value) { to this: if ((secretName[L] === playerGuess.value) && (playerGuess.value != answerArray[L])) {

Save and Refresh Browser to Test

Now, if a player guesses a previously guessed letter, the if statement will evaluate to false, so that LetterDashes remains at the same value and will only decrement when the player guesses a new correct letter. The only remaining issue is that players have an unlimited number of guesses…

Step 6 Limit Guesses and End Game Set Variable Guess Number

Add varaible guessesLeft above the letterGuess() function. Give it the value of the number of letters in the secretName plus additional attempts (3 for example): var guessesLeft = secretName.length + 3 Add a line to decrement guessesLeft after each guess. Place it inside the function letterGuess() before the for loop: guessesLeft—

Page 10: Web Coding with JavaScript Handout - gigalearnit.com...JavaScript, we’ll need to open a text editor. Open Komodo Edit & Create a New File Create a basic HTML page (the JavaScript

Web Coding with JavaScript The Name of the Queen

From Teaching Coding through Game Creation by Sarah Kepple © 2018

10

Place For Loop Inside of If Each time the letter Guess() function runs, we want to test if there are guesses remaining. If so, we want to execute the for loop, and if not, we want to display game over. To do this, we need to add an if statement and an else statement. Add the following if statement before the for loop in function letterGuess(): if ((guessesLeft>-1)&&(LetterDashes > 0)){ Copy and paste the for loop into the if statement. For clarity, indent the if statements inside of the for loop:

Add an end bracket to close the new if statement

Update User Feedback Add a statement to show the player how many guesses remain: document.getElementById("guessNumber").innerHTML = "guesses remaining: " + guessesLeft

Make sure to return to the top of the file and create a corresponding paragraph element id: <p id ="guessNumber"></p>

Save and Refresh Browser to Test The number of guesses remaining should appear and decrease after each guess, and the letter insertion should end when guessesLeft < zero.

Else End Game Add an else statement to display a game over message when guessesLeft<0: else{ document.getElementById("line2").innerHTML = "Out of Guesses" document.getElementById("line3").innerHTML = "The Queen's Name was " + secretName }

Page 11: Web Coding with JavaScript Handout - gigalearnit.com...JavaScript, we’ll need to open a text editor. Open Komodo Edit & Create a New File Create a basic HTML page (the JavaScript

Web Coding with JavaScript The Name of the Queen

From Teaching Coding through Game Creation by Sarah Kepple © 2018

11

Save and Refresh Browser to Test If the player guesses all letters within the limit the congrats message should display, if not, the Out of Guesses message should display. That’s it! Good job!