Random text
From Spheriki
This tutorial is about choosing one random line of text from a bunch of them.
Math.random()
Wild-tiger bugged me about making random text, dispite me saying its easy and posting lines of code how to do this.
Math.random() is what you need. Math.random() generates a random number between 0 and 1, e.g. 0.400213564545, yeah not very helpful huh?
Well, actually it is. Say you want a random whole number, between 0 and 5 inclusive.
var a = Math.random(); var b = Math.floor(a * 6); // b is either 0, 1, 2, 3, 4 or 5
So we Math.floor()'ed a * 6. 6 was the highest number we wanted (5) plus 1 (5 + 1). Math.floor(number) returns the lowest possible number, equal to or less than the 'number' passed in as a paramter.
So now, if we simplify this, we get:
var r = Math.floor(Math.random() * 6);
Picking a random line of text
Say you have some text to get one of them, randomly. This is the bit where you can do it the stupid way, or the intelligent way.
var MaxRandomChoice = 4; // we have 0 to 3 text items...
var RandomNumber = Math.floor(Math.random() * MaxRandomChoice);
var RandomText = ""; // nothing there yet...
switch (RandomNumber)
/* this is the same as alot of if else statements */
{
case 0: RandomText = "Random Text 1"; break;
case 1: RandomText = "Random Text 2"; break;
case 2: RandomText = "Random Text 3"; break;
case 3: RandomText = "Random Text 4"; break;
}
Now at this point, if you have 60 "Random Text x" items, you'd faint at the amount of scripting that it took by doing it that way.
Although, there is an easier way.
Arrays of random text lines
This is done by using an array of the random text items.
var RandomTextArray = [
"Random Text 1",
"Random Text 3",
"Random Text 2",
"Random Text 4" ];
var RandomText = RandomTextArray[Math.floor(Math.random() * RandomTextArray.length)];
And so you have two lines of code that does the same as the code example before.
If it is still confusing, there is only one more thing I can suggest:
// Get Random Text, from any of the paramters.
function GetRandomText()
{
me = GetRandomText.arguments;
return me[Math.floor(Math.random() * me.length)];
}
var RandomText = GetRandomText(
"Random Text 4",
"Random Text 3",
"Random Text 2",
"Random Text 1" );
// RandomText now holds a random line from the above.
There's no limit or minimum of parameters that could be thrown into this function.
By Flikky (from the Sphere CHM, adapted and updated for the wiki.)

