Que Logo

Chapter 16

Script Example 2: Random Chatter



In This Chapter

When Is Random Not Random?


Computers are "linear" machines, very logical and precise. Humans have no problem picking a number between 1 and 10, but computers don't have the capability to randomly select things. And yet, card games, dice games-just about any game you can think of-involves some sort of random selection… and we do love to play games on computers. So how, then, do computers take a "shot in the dark"? By using a formula that's dependent on something that is always changing: the time of day.
Using military time (where hours are numbered from 0 to 23 instead of "a.m." and "p.m."), you can create a pseudo-random number, or a number that seems random because it changes every second. Simply speaking, take the hour of the day, the minute of the hour, and the second of the minute and multiply them together. Depending on the hour, minute, and second you pick, you'll have a number somewhere between 0 and 80,063 (the 59th second of the 59th minute of the 23rd hour of the day… or the second just before midnight). And, through the Date object in JavaScript, you can get the current time of day easily.
Random numbers are used commonly in computer programs, especially games. Lottery-style games, gambling games, and so forth tend to be common beginners' programs. Perhaps, if you were designing an online "store" for your wares, you might offer customers a chance at a discount via a lottery or slot-machine style game. Using the Date object, it's just a hop, skip, and a jump to implementing a random-number generator into your JavaScript programs.

Random Numbers with the Date Object


With the Date object, you can find out the current hour, minute, and second. The Date object contains a large number of methods that can be used to extract various portions of the current date and time, or set them.
First, though, you need to create a new Date object that contains the current date and time settings. This is simple:

now = new Date()

Here, now would be the name of your Date object, although you could use any legal variable name. Thus, you have an object now that contains all of the date methods. Some of the more useful ones include:

getDay()
getDate()
getHours()
getMinutes()
getMonth()
getSeconds()
getTime()
getYear()

There are also more methods for setting the various aspects of the date and other date-related tasks. For more references on these, check out the Appendix of this book, "JavaScript: The Complete Overview."
You use these methods in typical fashion; for example, let's say you'd like to know the current date. Having already created the object now, you can simply use an expression such as

today = now.getDate()

Or perhaps you might write the current day into a document message:

document.write ("<H2>Welcome, today is the " + now.getDate() + "th</H2>")

To generate a random number, you use the hour, minute, and second of the current date. All you need to do then is multiply them together and you'll have a different number for every second each day, such as with the statement

rannum = now.getHours() * now.getMinutes() * now.getSeconds()


Modulus Math?

Normally, when you divide one number by another, you get some decimal result (unless the numbers divide evenly). Modulus math is interested in the remainder, or what's left after you've evenly divided as much as you can. For example, dividing 10 by 3 gives you 3 with a remainder of 1 (3 times 3 is 9, plus 1 for 10). In JavaScript, modulus math is represented by the percent sign (%) and, when used in place of the division sign operator, returns the remainder of the division. This value will always be a number from 0 (perfectly divisible) to one less than the dividend (in our 10 % 3 example, the range of the modulus is from 0 to 2).
However, under normal circumstances, this is too wide a range to deal with. Usually, when you want a random number, it needs to fall within certain bounds. For example, there are only 52 cards in a deck, unless you count the jokers, so a card game must not choose random numbers outside the range of 1 to 52. You need to be able to limit the range of numbers, and this is easily accomplished with a little modulus math.
So, you can write a JavaScript function that returns a "random" number within a particular range as follows:

function random(maxValue)
{
   day = new Date();
   hour = day.getHours();
   min = day.getMinutes();
   sec = day.getSeconds();
   return (((hour + 1) * (min + 1) * sec) % maxValue) + 1;
}

As you can see, you get the hour, minute, and second from the Date object, then multiply them together. Finally, you modulus this number by the maxValue parameter to get a number somewhere between 1 and (maxValue - 1). Add 1 to this result (you'll see why in
a moment) and return the final value. This is a handy little function to keep in your toolkit, because most uses of random-number generation will require a range limit. You can then plop it into any JavaScript program where you require a random-number generator, or save it in a separate file and include it in your HTML documents with the SRC= attribute of the <SCRIPT> tag. In the case of your card game, you would pass the value 52 to random(), which would then be the maxValue.
You may be asking, "Why is 1 added to the hour and minute before you multiply them together?" Well, if you happen to be a late-night surfer and are trying this page out between midnight and 1:00 a.m., you'd discover that without this step you'd always get the value of 1. Remember, the hour, minute, and second are values between 0 and 59 or 23, so for the first hour of the day, the hour is 0. This would make the entire equation return a zero for one whole hour (as an experiment, try changing the function above and experimenting with the page after midnight).
Now that you can randomly generate a number within a particular range, you need to have a selection of things to randomly pick from-and that's next.

The Random Chatter Example


Create a simple example that randomly picks a phrase from an array of sentences. An "array" is simply an object, and each "array element" is one property. Every time the user clicks on the button, something new appears on the screen. Here's the JavaScript page:

<HTML>
<TITLE>Random Chatter</TITLE>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!- Hide from non-JavaScript browsers
function random(maxValue)
{
 day = new Date();
 hour = day.getHours();
 min = day.getMinutes();
 sec = day.getSeconds();
 return (((hour + 1) * (min + 1) * sec) % maxValue) + 1;
}

function MakeArray(size)
{
 this.length = size;
 for(var i = 1; i <= size; i++)
 {
 this[i] = 0;
 }

 return this;
}

function showRandom(field)
{
 textArray = new MakeArray(10);
 textArray[1] = "JavaScript is Fun!";
 textArray[2] = "Let's Browse the Web in Style!";
 textArray[3] = "We're now JavaScript-powered!";
 textArray[4] = "Click again, I don't like this choice.";
 textArray[5] = "And now ... something completely different.";
 textArray[6] = "So far ... so good.";
 textArray[7] = "Ok ... now what?";
 textArray[8] = "A nice choice, if I do say so myself.";
 textArray[9] = "Only one more to go ...";
 textArray[10] = "That's it!";

 field.value = textArray[random(10)];
}

//->
</SCRIPT>
</HEAD>
<BODY>
<H1>Random Chatter</H1>
<HR>
JavaScript can be quite a talker, and can even randomly pick things
to say.
<P>
<FORM>
<HR>
Click on the button, I'll think of something to say
<INPUT TYPE="button" VALUE="Take a chance!" ONCLICK="showRandom(this.form.randomOut)">
<CENTER><INPUT TYPE=text NAME="randomOut" size="60"></CENTER>
</FORM>
</BODY>
</HTML>

There's your random-number function. In this case, it's returning a number between 1 and 10. Notice that you pass the parameter 10 (your maxValue) to random() in the function call in the final statement of showRandom(). The value it returns is used by the showRandom() function to pick a text line from textArray. The selected text is then loaded into the value property of the field that is passed to showRandom(). In the BODY of the page, you'll find the "Take a chance!" button that fires showRandom() whenever you click it, and the randomOut field that receives the text selected by showRandom().
One other thing you should see is the MakeArray() function in the <SCRIPT> tag. This is another handy little function to have around. Remember that creating an array is as simple as using new and defining the size (or number of indexes). MakeArray() provides a clean way of initializing any type of array to any size, setting all indexes in the array to 0 (or an empty text string). In essence, this is an automated object and property creator; recall that an array is another name for a JavaScript object. MakeArray() simply creates an object and uses a loop to create some number of properties (array elements). This is done to create the skeleton of the array, for the same reason you created skeletons of an object back in Chapter 9.

Color Me Random


As another mini-example of random numbers, you can add another button to your page that causes the background color to change each time the button is clicked. To do this:
For a list of 138 of the most common colors, their RGB values, and their hexadecimal triplets, see "JavaScript: The Complete Reference" at the end of this book. For quick reference, here are the hexadecimal triplets for some basic colors:





Color

Hexadecimal Triplet

black

000000

blue

0000FF

brown

A52A2A

cyan

00FFFF

gold

FFD700

gray

808080

green

008000

lime

00FF00

magenta

FF00FF

maroon

800000

orange

FFA500

pink

FFC0CB

purple

800080

red

FF0000

silver

C0C0C0

white

FFFFFF

yellow

FFFF00


Here's your function to pick a background color:

function SetBkgndColor()
{
 colorArray = new MakeArray(7);
 colorArray[1] = "#FF0000";
 colorArray[2] = "#00FF00";
 colorArray[3] = "#FFFF00";
 colorArray[4] = "#0000FF";
 colorArray[5] = "#FF00FF";
 colorArray[6] = "#00FFFF";
 colorArray[7] = "#FFFFFF";

 document.bgColor = colorArray[random(7)];
}

Notice that all you need to do to cause the background color to change is set document.bgColor. Remember that document is a predefined JavaScript object that gives you direct access to the current document and how it's being displayed (see Chapter 13 for more information on the document object).
Putting it all together, here's your new random chatter page:

<HTML>
<TITLE>Random Chatter</TITLE>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!- Hide from non-JavaScript browsers
function random(maxValue)
{
 day = new Date();
 hour = day.getHours();
 min = day.getMinutes();
 sec = day.getSeconds();
 return (((hour + 1) * (min + 1) * sec) % maxValue) + 1;
}

function MakeArray(size)
{
 this.length = size;
 for(var i = 1; i <= size; i++)
 {
 this[i] = 0;
 }

 return this;
}

function showRandom(field)
{
 textArray = new MakeArray(10);
 textArray[1] = "JavaScript is Fun!";
 textArray[2] = "Let's Browse the Web in Style!";
 textArray[3] = "We're now JavaScript-powered!";
 textArray[4] = "Click again, I don't like this choice.";
 textArray[5] = "And now ... something completely different.";
 textArray[6] = "So far ... so good.";
 textArray[7] = "Ok ... now what?";
 textArray[8] = "A nice choice, if I do say so myself.";
 textArray[9] = "Only one more to go ...";
 textArray[10] = "That's it!";

 field.value = textArray[random(10)];
}

function SetBkgndColor()
{
 colorArray = new MakeArray(7);
 colorArray[1] = "#FF0000";
 colorArray[2] = "#00FF00";
 colorArray[3] = "#FFFF00";
 colorArray[4] = "#0000FF";
 colorArray[5] = "#FF00FF";
 colorArray[6] = "#00FFFF";
 colorArray[7] = "#FFFFFF";

 document.bgColor = colorArray[random(7)];
}

//->
</SCRIPT>
</HEAD>
<BODY>
<H1>Random Chatter</H1>
<HR>
JavaScript can be quite a talker, and can even randomly pick things
to say.
<P>
<FORM>
<HR>
Click on the button, I'll think of something to say
<INPUT TYPE="button" VALUE="Take a chance!" 
ONCLICK="showRandom(this.form.randomOut)">
<CENTER><INPUT TYPE=text NAME="randomOut" size="60"></CENTER>
<HR>
Or ... click here and I'll change color! 
<INPUT TYPE="button" VALUE="Color Me!" ONCLICK="SetBkgndColor()">
</FORM>
</BODY>
</HTML>

And, here's what it looks like once it's running:

Randomly selecting text and changing document properties.

The Least You Need To Know


In this chapter's example, you learned how to:

Previous Chapter

Next Chapter


Beginning of ChapterTable of ContentsBook Home PageQue Home Page


For comments or technical support for our books and software, select Talk to Us.
To order books, call us at 800-716-0044 or 317-228-4366.

© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon & Schuster Company.