HTML and CSS Reference

In-Depth Information

// Keep asking the user to guess until he gets the number.

while(guess != randomNumber) {

guess = prompt('What is your guess?');

}

// Let the user know that he guessed correctly.

alert('Congratulations! You guessed correctly. The number

was ' +

randomNumber + '.');

}

3.
Save the
example10-8.js
file.

4.
Create a new file called
example10-8.html
.

5.
Copy the following code into this new file:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>While Loops</title>

</head>

<body>

<h1>The Guessing Game</h1>

<p>

Guess a number between 0 and 10.

</p>

<script src="example10-8.js"></script>

</body>

</html>

6.
Save the
example10-8.html
file.

Open this example in your browser and give the game a go.

This code is a little more complex than earlier JavaScript you looked at, so I will take you through each part. Lines

that begin with
//
are comments.

The objective of this game is for the user to guess a random number that is generated by the program. This number

will be between 0 and 10.

First you need to generate the random number. To do this, you initialize a new variable
randomNumber
. You use

JavaScript's built-in
Math
library to help generate the number. Let's take a closer look at this segment.

Math.floor(Math.random()*10)

Here you first use the Math library's
random
function to generate a decimal number between 0 and 1. Your program

needs a number between 0 and 10, though, so you multiply this random number by 10 to make it larger. Finally, you

only want that random number as an integer so you can use the
floor
function to round your decimal number to

the closest integer. The example below shows how the random number is calculated:

Math.random() = 0.4382

Math.random()*10 = 4.382

Math.floor(Math.random()*10) = 4