Sunday, December 22, 2013

JavaScript Tutorial 8 - Guess The Number

Now we will put some of our skills to the test by creating a simple app that will give the user 5 chances for the user to guess the number it generated. To start of we nee to first be able to generate a random number from 1 - 100. Just like we did in my previous tutorial...


var random = (Math.random());
var multiply = random * 100;
var round = Math.round(multiply) ;
var number = round;

So now the variable "number" will be a random number between 1 - 100. Next we need to write a code that will give the user only 5 chances to guess the number, I think a for loop will work perfectly for this...

for(var c = 0; c < 4; c ++)

Ok, so now it will only let the user have 5 guesses, next we need to create a prompt that will let the user enter in their guess, for this all we do is use a prompt statement like this...

var guess = prompt("Guess what number i'm thinking off, 1 - 100");

Now we can grab the guess from the user, now we need to create a if else statement to tell the user if their guess is higher or lower then the number that the code generated, but what happens if the user guesses it right because if else statements can only handle 2 options? Well thats when else if statements come in, they allow you to add in another condition, so in our case that will be if the user guesses it correctly...


if(guess < number)
{
    alert("higher. " + c);
}

else if (guess > number)
{
    alert("lower. " + c);
}
else
{
    alert("correct the number was " + number);
 }

Using the "<" and ">" we were able to determine if the guess was higher or lower then the number and if it wasn't or higher or lower then we knew that it must be the number.So when its all put together it looks like this...


var random = (Math.random());
var multiply = random * 100;
var round = Math.round(multiply) ;
var number = round;
for(var c = 0; c < 5; c ++)
{
var guess = prompt("Guess what number i'm thinking off, 1 - 100");
if(guess < number)
{
    alert("higher. " + c);
}

else if (guess > number)
{
    alert("lower. " + c);
}
else
{
    alert("correct the number was " + number);
}
}

This is what a simple guess my number game looks like in JavaScript.


No comments:

Post a Comment