Java Script Programming

Page 15

One of Java Script's many built-in functions is one called random(). The function random() is part of the Math object of Java Script. The function is used like so:

Math.random();

What this function does in this case is creates a random number between 0 and 1. We can also tweak this function to return a number within a specified range. For instance:

Math.random() * 100 Creates a random number between 0 and 100
(Math.random() * 100) + 1 Creates a random number between 1 and 101
Math.random()  * 1000 Creates a random number between 0 and 1000

This is just simple arithmetic. Because the random function of the Math class (object) of Java Script returns a number between 0 and 1, the number is a decimal. If we say var number = Math.random() * 1000, suppose the random function of the Math class returns .84342. When this number is multiplied by 1000 we get:

.84342 * 1000 = 843.42

Let's put this function to use.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
56
57
58
59
<html>
<head>
<title>Number Guesser</title>
<Script Language = "JavaScript">
<!--

-->
</script>
</head>

<body>

<p>
<h1>Guess the number</h1>

<form name = "frmGuess">

Choose number range:

<input type = "radio" name = "optRange" checked onClick = "Generate();">1-100
<input type = "radio" name = "optRange" onClick = "Generate();">1-1000
<input type = "radio" name = "optRange" onClick = "Generate();">1-10000

<p></p>

<b>Guess:</b>

<input type = "text" name = "txtGuess" size = "5">
<input type = "button" value = "Guess" onClick = "Guess();">

<p></p>

<input type = "text" size = "25" name = "txtHint" value = "Enter your Guess." onFocus = "this.blur();">

</form>

</p>
</body>
</html>
 

 

 

Lines 20-22 create option button forms. Because the buttons are named the same (optRange), they are indexed 0-2. Each button calls the function Generate() when it is clicked. This function is created later to generate the random number that the user tries to guess.

 

Line 29 calls a function Guess when the button is clicked. This function compares the user's entry to the number.

 

Line 33 uses a text box which is later used to tell the user to guess higher or lower. This textbox cannot be edited by the user because it is prevented by the onFocus event. The object's focus is taken away with the this.blur() command seen in the tag.

Line 1: Set variable number to a random integer between 1 and 100.

Because the Math.random() function generates a number between 0 and 1, multiplying that number by 100 sets the range from 0 to 99. We then add 1 to it in order to also generate the number 100. Suppose the function Math.random() returns .99. .99 * 100 equals 99. 99 + 1 equals 100. Therefore, the number range for this command is 1 to 100.

Line 2: Check the option button optRange[0]. When the page is reloaded, we need to set a command to reset the option buttons. This option button is the button initially checked.

Line 1: Declare function Guess().
Line 3: Set variable guess to the user's entry, which is the value of text box txtHint
Line 4: Increment variable tries, which tracks how many guesses the user has made.
Line 5: Set the browser's status bar to Tries: and the amount of tries the user has made
Line 7: Test if the user's guess is less than the random number. When it is, display No, guess higher in the text box txtHint.
Line 8: Test if the user's guess is greater than the random number. When it is, display No, guess lower in the text box txtHint.
Line 10: Test if the user guessed the number correctly. In which case, execute lines 12-14
Line 12: Display CORRECT! Good Guess! in the text box txtHint.
Line 13: Display alert to tell the user how many times it took to guess the number.
Line 14: Reload the web page.

You may notice on the form are option buttons which set the range of values. Because the user can change the range at any time, we need to define a function to generate random numbers according to the option the user chooses.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
var index = 0; // keep track of the selected option button
var tries = 0;
var number = 0;

function Generate()
{
    var answer = confirm("Changing the value range resets guesses to 0.\n
    Are you sure you want to do this?");

    if (answer == true)
    {
        // 1 to 100
        if (document.frmGuess.optRange[0].checked == true)
        {
            number = Math.floor(Math.random() * 100) + 1;
            index = 0;
        }

        // 1 to 1000
        if (document.frmGuess.optRange[1].checked == true)
        {
            number = Math.floor(Math.random() * 1000) + 1;
            index = 1;
        }

        // 1 to 10000
        if (document.frmGuess.optRange[2].checked == true)
        {
            number = Math.floor(Math.random() * 10000) + 1;
            index = 2;
        }

        tries = 0;
        window.status = "Tries: " + tries;

    } else { // user say no

        document.frmGuess.optRange[index].checked = true;
    }
}
Lines 1 through 3: Declare variables for our script. Index: Sets to the index of the selected option button, which are indexed 0 to 2. Tries: The number of times the user guessed. Number: The number generated at random with the Math.random() function

Line 5: Create function Generate(), which creates our random number when the user selects an option button.
Line 7: Display a confirm dialog to ask user if they want to change the random number range and reset their guesses to zero. The confirm dialog displays the buttons OK and Cancel. Clicking OK returns true and clicking Cancel returns false.
Line 10: Test for the button the user clicked.
Line 13: Test if the option button optRange[0] is selected. When it is, execute lines 15 and 16.
Line 15: Generate an integer number between 1 and 100. When we use the Math.floor function like this, the number is rounded as an integer (no decimals). The Math.random function generates a decimal between 0 and 1, then multiplies it by 100. Because the number 100 cannot be generated by multiplying it by the decimals between 0 and 1, we then add 1 to it, which potentially returns 100 if 99 is the resulting random number.
Line 16: Set variable index to 0 to tell us that the first option button is checked (first option button is indexed as 0).
Line 20: Test if the option button optRange[1] is selected. When it is, execute lines 22 and 23.
Line 22: Generates an integer number between 1 and 1000. This works the same way as on line 15 except the resulting value of the Math.random() function is multiplied by 1000 instead of 100 as on line 15.
Line 23: Set variable index to 1 to tell us that the second option button is selected
Line 27: Test if the option button optRange[2] is selected. When it is, execute lines 29 and 30.
Line 29: Generates an integer number between 1 and 10000.
Line 30: Set variable index to 2 to tell us that the third option button is selected.
Line 33: Reset variable tries to 0. Because this function is called when the user selects and option button, we want to reset the user's guessing cycle to 0.
Line 34: Reset the browser window's status bar to display variable tries.

Line 38: When the user selects No in the confirm dialog (as tested by line 36), recheck the option button that is selected initially. So this basically does nothing. Nothing is reset. The option button needs to be set back to where it was though in order to keep track of it correctly if the user decides to reset it again.

Line 1: Generate random integer number between 1 and 100 and store in variable number.
Line 2: Check the option button optRange indexed at 0.

These commands initialize the page. We use these commands outside the function so that a number is generated when the user loads the page. This also resets the page if it is reloaded when the user clicks the browser's reload button.

I hope everything works well for you. This concludes our lesson in random numbers. However, the next page puts this function to use in a more complex script. Proceed to Page 16 when you like.

Page 1 | Page 2 | Page 3 | Page 4 | Page 5 | Page 6 | Page 7 | Page 8 | Page 9 | Page 10 | Page 11 | Page 12 | Page 13 | Page 14 | Page 15 | Page 16 | Page 17 | Page 18 | Page 19 | Page 20 | Page 21 | Page 22 | Page 23 | Page 24 | Page 25

Return Home