bigbadbrain logo
bbb Home
  Lesson 8 - Randomly Move Target

SUMMARY

In this lesson you will learn how to use the Math object to move the target to a random location.  In later lessons we will add a timer so that the target moves periodically.   

DISCUSSION

There are many objects in JavaScript.  These objects have functions that do special tasks.  For your information, object functions are generally called  methods.  

The Math object has methods that do mathematical tasks.  For example, the random method creates a random number between 0 and 1.  Referring to the example below, the function ranNumber() contains three statements on lines  5 to 7.  On line 5, the Math.random() method is called.  This function returns a number between 0 and 1.  The number is then displayed in an alert.  On line 6, Math.random() returns a number between 0 and 1.  This number is multiplied by 200 and the result is displayed on the face of the button.  When you run the program, you will notice that the result is a number between 0 and 200.  On line 7, the button is positioned so that its left side is located between 0 and 300 pixels from the left side of the screen.

On line 14, the function ranNumber() is called when the user clicks the button.

EXAMPLE - Math.random()

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

PRACTICE

In  the example above:

  1. Modify line 5 so that a random number between 0 and 150 is displayed in the alert.
  2. Modify line 6 so that the top of the button is set to a random number between 0 and 400.
  3. Visit a reference and review the other Math methods. Add code to demonstrate three of these other methods.

GAME DEVELOPMENT

Modify your game page (game.htm) as follows:

  1. Add a function called moveTarget().
  2. In the function moveTarget(), set the position of the target to a random location. You must set both the top and left of the target to a random number that the target appears at a random location.
  3. Call the moveTarget() function in the startGame() function so that the target moves to a random location when the user clicks the start button.  Later we will add code so that the moveTarget function is called periodically.
 
 
©dfx interactive, inc. Contact us at bigbadbrain@bigbadbrain.com