bbb Home |
Lesson 11 - End Game |
SUMMARY
In this lesson you will learn how to use an if statement in order to end the game after the target hs been moved a certain number of times. DISCUSSION
Conditional statements are used to execute certain code if a condition is true.
There are several different types of conditional statements including if,
if...else, and if...else if...else if...else. In
this lesson we will focus on if statements. The syntax for an if
statement is as follows:
if(condition){ statements } In the statement above, the condition must evaluate to true or false. If the condition is true, then the statements are executed. If there is only one statement, then the brackets {} are not needed and the if statement can be written as: if(condition) statement Conditions are generally formed using conditional operators:
Examples of conditional statements are illustrated below. On line 3, a global variable called gNumClicks is defined and set to 0. On line 19, gNumClicks is incremented when the user clicks on the page and the function checkValue() is called. Lines 4 to 14 define checkValue(). On line 5, gNumClicks is compared to 1. If gNumClicks is equal to 1, then an alert is displayed. Notice that because only one thing happens if gNumClicks is equal to 1, no brackets are needed around the alert statement. The if statement on line 6 checks if gNumClicks is less then or equal to 5. If so, line 7 is executed and the contents of <div> d1 are updated by displaying the value of gNumClicks. Line 9 checks if gNumClicks is greater then 5. If so, lines 10 to 12 are executed. These lines display a message in an alert, set the contents of d1 to "Back to 0", and then set gNumClicks to 0. Lines 15 to 17 define a function called checkName(). This function checks if the contents of the textbox t1 do NOT equal "bob". If the contents of the textbox do not equal "bob", then an alert is displayed. The function checkName() is called on line 23 when the user clicks on the button. EXAMPLE - Conditional Statements
PRACTICE1. Modify the function checkValue() so that it checks if gNumClicks equals 4. If gNumClicks equals 4, then an alert should appear with the message that gNumClicks equals 4. 2. Modify the function checkName() so that it checks for a name other than "bob" and displays the appropriate message in the alert. 3. Open CodeTester and create a page that meets the following requirements:
GAME DEVELOPMENTFinish your game page (game.htm) so that the timer is stopped after the target is displayed 10 times and an alert appears with a message that the game is over. Recall that gNumTries keeps track of the number of times that the target is displayed. |
References |
©dfx interactive, inc. Contact us at bigbadbrain@bigbadbrain.com |