bigbadbrain logo
bbb Home
  Lesson 3 - Start Game
 

SUMMARY

In this lesson we will add code to make the game start when the user presses any key other than the left or right arrow key.  

DISCUSSION

In previous lessons, you learned to write an if...else statement to check if a certain condition is true or not.  Sometimes we want to check if a condition is one of multiple possibilities.  For example, we might want to check if the user clicks the "a" key, or the "b" key, or the "c" key, or any other key.  We can use an if...else if...else if...else statement.  These  statements are written as follows:

if(condition){
  code
}
else if(
condition){ //More than 1 else if OK
  code
}
else{
  code
}

The example illustrates these concepts.
 

EXAMPLE - if...else if...else

 Font Size: 10pt 12pt   View Large Version
 Ctrl-C to Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

PRACTICE

1.  Write code that prompts the user for a number.  Store this number in a variable. Then use an if...else if...else statement to display a message if the number is negative, positive, or 0. Remember to use code similar to  var num = parseInt(prompt("Enter a number"))
to get the number.
 
2.  Write code that calls a function when the user presses a key.  The function should:
  1. Display an alert with one message if the left arrow key is pressed
  2. Display another alert if the right arrow key is pressed
  3. Display another alert if any other key is pressed.

GAME DEVELOPMENT

1. Ensure that the message in the <div> on your Pong page is similar to the message shown in the figure on the Home page.  The message should be similar to: "Click any key to start. Press the arrow keys to control the paddle". 

2.  Modify your game page so that the game starts when the user presses any key besides the left or right arrow keys.  At the moment, nothing much will happen when the game starts except that the message on the screen will change to display "Score: 0".  In future lessons we will make the ball move.  You should: 
  • Create a function called startGame().  This function should set the message in the message <div> to "Score: 0 ".  Later we will add additional code to the startGame() function to make the ball move.. 
  • Modify the movePaddle() function (created in Lesson 2) to check if the keypress is anything other then the left or right arrow key using an if...else if...else statement.  If any key is pressed other than the arrow keys, the startGame() function should be called.

 

©dfx interactive, inc. Contact us at bigbadbrain@bigbadbrain.com