Guess That Number


Writing a guess-that-number script in javascript is notorious in low-level javascript classes. I can’t tell you how many times someone has approached me on IRC asking about, “how to make a guess that number script?”. Since I wrote it so many times, I figured I would post it here for the world to access.

Isn’t sharing fun?

?View Code JAVASCRIPT
var guess_num = 0, guess_range, guess_tries = 0;
 
/**
* @desc Think of a number from 1 to x
* @param number range to guess within
**/
function GuessNum( num )
{
	if ( isNaN(num) )
		throw "Invalid Number Provided For GuessNum()";
 
	guess_tries = 0;
	guess_range = num;
	guess_num = Math.floor(Math.random() * num) + 1;
}
 
function Guess( frm )
{
	var g = parseInt(frm.guess1.value);
 
	if ( isNaN(g) )
	{
		alert("Please insert a numerical value.");
		return;
	} else if ( g < 1 || g > guess_range ) {
		alert("You must select a number between 1 and "+ guess_range);
		return;
	}
 
	guess_tries += 1;
	status = "Tries: "+ guess_tries;
 
	if ( g == guess_num )
	{
		if ( guess_tries == 1 )
			alert("Correct!  You guessed it in 1 try!  Wow, good job!!");
		else
			alert("Correct!  You guessed it in "+ guess_tries +" tries!");
 
		GuessOver();
	} else if ( guess_tries >= 10 ) {
 
		alert("Sorry, time's up. The number was: "+ guess_num);
		GuessOver();
	} else if ( g < guess_num )
		frm.hint.value = "No, guess higher.";
	else if ( g > guess_num )
 
		frm.hint.value = "No, guess lower.";
}
 
/**
* @desc Prompt to start the guessing game over
**/
function GuessOver()
{
	if ( !confirm('Would you like to play again?') )
	{
		alert("Thanks for playing!  :)");
		location.reload();
	} else {
		GuessNum( 100 );
		document.forms.form1.hint.value = "Enter your Guess.";
	}
}
 
// initialize the guessing game
GuessNum( 100 );

View: Open Source Copy


Guess That Number

I'm thinking of a number between 1 and 100. Try to guess it in less than 10 tries.



Guess:


VN:F [1.9.22_1171]
Rating: 7.3/10 (3 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)
Guess That Number, 7.3 out of 10 based on 3 ratings
Share/Save

,

  1. No comments yet.
(will not be published)