You are here

Fun with Random Numbers Tutorial

In this tutorial we show how to generate random numbers using JavaScript, and include some useful and entertaining tricks that you can do with random numbers.

We can use JavaScript to generate random numbers, that is, numbers that are different each time the script is run. This allows us to do all sorts of fun stuff, such as:

  • Show a random image or piece of text on the page
  • Make a link that links to a random page
  • Create games that people can play in their browser

First, let's look at how we can create a random number in JavaScript.

Generating a random number

We can get JavaScript to give us a random fractional number between 0 and 1, as follows:

alert ( Math.random ( ) );

Try this out by clicking on the link below:

Give me a random number!

Generating a useful random number

Of course, we often want to work with whole random numbers between 1 and a certain value. Let's write a simple function to generate such a number:

function rand ( n )
{
  return ( Math.floor ( Math.random ( ) * n + 1 ) );
}

This function takes a whole number argument, n, and returns a random number between 1 and n. It multiplies the Math.random() value by n, adds 1 to the value (so that we get a number between 1 and n), then uses the Math.floor() method to remove the fractional part of the number, leaving us with a whole (integer) number.

We can now use our function to return us a random number between, say, 1 and 100:

alert ( rand ( 100 ) );

Click on the link below to see this in action!

Give me a random number between 1 and 100!

That's the basics of random numbers covered. Let's look at some fun things we can do with them!

Displaying a random image

Let's display a random image that changes each time the visitor reloads the page. To do this, we first create an array of image URLs, then use a function to set the image's source to point to a randomly-selected URL when the page loads:

// Store some random image URLs

var random_images = new Array ( );
random_images[0] = "boats.jpg";
random_images[1] = "cat.jpg";
random_images[2] = "chairs.jpg";
random_images[3] = "daisy.jpg";
random_images[4] = "escalator.jpg";
random_images[5] = "koala.jpg";
random_images[6] = "planks.jpg";
random_images[7] = "sunset.jpg";
random_images[8] = "swans.jpg";
random_images[9] = "waterfall.jpg";

// Pick a random image from the list,
// and set the image source to that image

function pick_image ( )
{
  document.getElementById("random-image").src = random_images[rand(10)-1];
}

The pick_image() function sets the source of the image with ID random-image to one of the images in the array. (Note that, because arrays in JavaScript start from element number zero, we need to subtract one from the random number to get a number between 0 and 9.)

We're going to call the pick_image() function using the onload event handler in the page's body tag:

<body onload="pick_image()">

And finally, here's the HTML for the image itself:

<img id="random-image" border="0" alt="Random Image" />

So when the page loads, the image with ID random-image will be set to a random image.

Take a look at this script in action. Click your browser's Refresh/Reload button to see a different image appear!

Feel free to use the above code on your own site to display random images. It's also useful for rotating ad banners! Don't forget to include the rand() function that we made earlier, as it's needed by this script.

Displaying random text

We can use a similar technique to display a random piece of text when the user clicks a link. The JavaScript below will display a random quotation from Shakespeare:

// Store some random quotations

var random_quotes = new Array ( );
random_quotes[0] = "If music be the food of love, play on";
random_quotes[1] = "When shall we three meet again...?";
random_quotes[2] = "What a piece of work is man!";
random_quotes[3] = "There's daggers in men's smiles";
random_quotes[4] = "Alas, poor Yorick! I knew him, Horatio";
random_quotes[5] = "Time shall unfold what plaited cunning hides";
random_quotes[6] = "Goodnight, goodnight! Parting is such sweet sorrow";
random_quotes[7] = "Friends, Romans, countrymen, lend me your ears";
random_quotes[8] = "I am dying, Egypt, dying";
random_quotes[9] = "Get thee to a nunn'ry";

// Pick a random quote from the list,
// and set the 'random-quote' paragraph content to that quote

function pick_quote ( )
{
  document.getElementById("random-quote").innerHTML = random_quotes[rand(10)-1];
}

If we create a paragraph in our page with the ID random-quote, as follows:

<p id="random-quote"> </p>

then we can call our pick_quote() function above to set that paragraph's content to one of the random quotes. (We do this by setting the paragraph's innerHTML property.) For example, we can call the function from within a link:

<a href="javascript:pick_quote()">Feed me some Shakespeare!</a>

Here's the random quote generator in action. Click the link below to get another quote!

 

Feed me some Shakespeare!

Random links

Let's make a link that, when clicked on, takes you to a random Web site. First we build our list of URLs, then write a simple function to redirect the browser to a random URL from the list:

// Store some random URLs

var random_urls = new Array ( );
random_urls[0] = "http://www.empireonline.co.uk/";
random_urls[1] = "http://www.theonion.com/";
random_urls[2] = "http://slashdot.org/";
random_urls[3] = "http://www.theregister.co.uk/";
random_urls[4] = "http://news.bbc.co.uk/";
random_urls[5] = "http://www.w3.org/";
random_urls[6] = "http://www.nme.com/";
random_urls[7] = "http://www.altoids.com/";
random_urls[8] = "http://www.pythonline.com/";
random_urls[9] = "http://www.dilbert.com/";

// Jump to a random URL from the list

function jump_to_url ( )
{
  document.location.href = random_urls[rand(10)-1];
}

We can then make our random link by calling the jump_to_url() function, as follows:

<a href="javascript:jump_to_url()">Take me somewhere fun!</a>

Try clicking on the random link below to see how it works. (Use your browser's Back button to return to this tutorial.)

Take me somewhere fun!

A number guessing game

To round off this tutorial, let's write a simple number guessing game. The computer will think of a number between 1 and 100, and we have to guess what it is!

Here's the JavaScript for the game:

// Store the random number that the user has to guess

var my_number = rand ( 100 );

// Start a new game

function new_game ( )
{
  // Clear the guess form field
  document.getElementById("user-guess").value = "";

  // Generate a new random number
  my_number = rand ( 100 );

  // Tell the user that we're ready for them to guess
  alert ( "OK, I'm thinking of another number..." );
}

// Process the user's guess

function make_guess ( )
{
  // Get the user's guessed number
  var user_guess = document.getElementById("user-guess").value;

  // Warn if they haven't entered a number between 1 and 100

  if ( isNaN ( user_guess ) || user_guess < 1 || user_guess > 100 )
  {
    alert ( "Please enter a guess between 1 and 100" );
    return;
  }

  // Compare the guessed number against the computer's number,
  // and respond accordingly

  if ( user_guess > my_number )
  {
    alert ( "Too high - try again!" );
  }
  else if ( user_guess < my_number )
  {
    alert ( "Too low - guess a higher number!" );
  }
  else
  {
    alert ( "You got it! My number was " + my_number );
    new_game ( );
  }
}

The first thing the above code does is create a variable, my_number, to store the random number for the user to guess. Then we've written 2 functions to handle the game itself.

new_game() clears the form field containing the user's guess (in case it contained a previous guess), creates a new number to guess, then prompts the user to start guessing.

make_guess() is called when the user clicks the Guess button. This function retrieves the user's guessed number from the text field with ID user-guess, then validates the number to make sure it is indeed a number between 1 and 100. If the number is valid, we then compare it against the random number and return an appropriate response. If the user has guessed correctly, the new_game() function is then called to reset the random number and start again.

In order to play the game, we also need to create the user-guess form field where the user can enter their guess:

<input id="user-guess" type="text" size="2" value="" />

...and a button that the user can click to check their guess:

<input type="button" value="Guess" onclick="make_guess()" />

Try the game out for yourself! Enter a number between 1 and 100 in the box below, and press the Guess button:

Hours of fun! :)

This tutorial has introduced you to JavaScript's Math.random() method for generating random numbers, and provided a handy wrapper function, rand(), to generate random whole numbers between 1 and a given value. We've also shown you how to write some fun scripts using random numbers. Feel free to use any of these scripts in your own pages, but remember to include the rand() function in the same page, because all these scripts use this function to generate their random numbers!

 

 

Source :- tutorialized.com

Forums: