Number Guesser

[Total: 0    Average: 0/5]

This script will guess any number between the range given.

Init Code:

checkMinMax(document.f1);computeGuesses(document.f1);takeGuess(document.f1);

Body Code:

Script desgined by <a href="http://www.js-x.com/">JS-X.com</a>
<BR>
This is an temporary version that is for demonstration purpose only.
<BR>
<form name=f1>
<input type=button value="Start Over" onclick="setUp(this.form);">
<HR>
Min: <input type="text" name="min" value="1"    onblur="setUp(this.form);">
Max: <input type="text" name="max" value="1000" onblur="setUp(this.form);">
<BR>
I will guess your number with in this many guesses: <input type="text" name="guesses" value="">
<HR>
Guesses Made: <input type="text" name="qAsked" value="0" readonly onfucus="blur()">
<BR>
My Guess:<input type=text name="myGuess" value="" readonly onfocus="blur()">
<BR>
Press "&lt;" or "&gt;" to let me know if I was under or over your number.
<BR>
(repeat until I have guessed your number)
<BR>
<input type=button value="&lt;" onclick="badGuess(this.form,0);takeGuess(this.form)">
<input type=button value="&gt;" onclick="badGuess(this.form,1);takeGuess(this.form)">
</form>

<script>
/*
 * These define the boundries of this game.
 */
var MIN=1;
var MAX=1024;

function setUp(_f)
{
  checkMinMax(_f);
  computeGuesses(_f);
  _f.myGuess.value="";
  _f.qAsked.value="0";
  takeGuess(_f);
}

function takeGuess(_f)
{
  var _pg=_f.myGuess.value;
  var _m=_f.min.value;
  var _M=_f.max.value;
  var _d=_M-_m;
  var _g=parseInt(_d/2)+parseInt(_m);

  _f.myGuess.value=_g;
  
  if(_pg != _f.myGuess.value)
    _f.qAsked.value=parseInt(_f.qAsked.value)+1;
  else
    alert("I must have guessed your number!");
}

function badGuess(_f,_a)
{
  var _g=parseInt(_f.myGuess.value);
  if(_a)
    _f.min.value=_g;
  else
    _f.max.value=_g;
}

function checkForm(_f)
{
  /* do not submit this form */
  return false;
}


function checkMinMax(_f)
{
  var _m=parseInt(_f.min.value);if(_m!=parseInt(_m))_m=MIN;
  var _M=parseInt(_f.max.value);if(_M!=parseInt(_M))_M=MAX;
  if(_m<MIN){alert("You can not choose a min lower than "+MIN+"!");_m=MIN};
  if(_M>MAX){alert("You can not choose a max over "+MAX+"!");_M=MAX};
  if(_m>_M||_M<_m){var _t=_m;_m=_M;_M=_t;}
  _f.min.value=_m;
  _f.max.value=_M;
}

function computeGuesses(_f)
{
  var _m=_f.min.value;
  var _M=_f.max.value;
  var _delta=_M-_m;
  var _g=0;
  while(_delta>0)
  {
    _g++;
	_delta=parseInt(_delta/2);
  }
  _f.guesses.value=_g;
}
</script>

Times Viewed: 7

Leave a Reply

Your email address will not be published. Required fields are marked *