bigbadbrain logo
bbb Home
  Lesson 2 - Make Paddle Move When Press Keys
 

SUMMARY

In this lesson we will add code to make the paddle move when the user presses the left and right arrow keys.  In order to complete this lesson, you should have created the game page in Lesson 1 and added a link to your home page to open the game page in a new window 500 wide by 400 high. 

DISCUSSION

When the user presses a key an event is fired: onkeyDown.  Generally when we want to use the onkeydown event, we want to know which key is pressed.  The following statement indicates what key is pressed:

window.event.keyCode

In previous lessons, you learned to write an if statement to check if a certain condition is true. Often we want a statement that does one thing if something is true and something else, if  the condition is false. These if...else statements are written as follows:

if(condition){
  code
}
else{

  code
}

The example illustrates these concepts.
 

EXAMPLE - KeyPress and 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

PRACTICE

1.  Write code that prompts the user for a number.  Store this number in a variable. Your line of code should look like:
var num = parseInt(prompt("Enter a number"))
Then write an if...else statement to determine if the number is greater then 0, or less then or equal to 0. If the number is greater then 0, display an alert with the message "> 0".  If the number is less then or equal to 0, display an alert with the message "<= 0 ".
 
2.  Write code that calls a function when the user presses a key.  The function should display an alert with one message if the key pressed is the left arrow key; else the function should display an alert with another message.

GAME DEVELOPMENT

1.  Modify your game page so that the paddle moves left when the user presses the left arrow key and right when the user presses the right arrow key. You should: 
  • Create a global variable called gPx to keep track of the left side of the paddle. 
  • Initialize gPx to equal the same value as the left style property of the paddle.
  • Create a function  called movePaddle(). This function will contain the code to move the paddle when the user presses the keys.
  • Add the onkeyDown event to the body and call the movePaddle() function when this event is fired
  • Add code to the movePaddle() function to move the paddle to the left when the user clicks the left arrow key and move the paddle to the right when the user clicks the right arrow key.   You will need to check what key is pressed, update gPx, and then set the left style property of the paddle to gPx.

 

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