Guess the number game
Thursday, February 5th, 2009Enter
this in the <BODY> section
<script language=”JavaScript”>
<!– begin
// global variables - number to guess, attempts counter
var my_no,count;
function load() {
// first set window property
window.defaultStatus=”JavaScript Guess-a-Number Game”;
// show help mesage
document.game.help.value=”Please set range of numbers and press the Start button.”;
// focus cursor
document.game.from.focus(); }
// random number function, returns number from 0 to scale-1
function rnd(scale) {
var dd=new Date();
return((Math.round(Math.abs(Math.sin(dd.getTime()))*8.71*scale)%scale)); }
function range() {
var to=1+1*document.game.to.value;
// clear attempts counter
count=0;
// computer thinks number my_no generated here:
my_no=rnd(to);
while(my_no<document.game.from.value) {
my_no=rnd(to); }
// show help message
document.game.help.value=”Now please guess a number by typing it and pressign the Guess button.”; }
function guess()
{
var no=document.game.number.value;
// increase attempts counter
count++;
// your number is less than my_no
if(no<my_no) document.game.help.value=”My number is greater than “+no+”.”;
// your number is greater than my_no
else if(no>my_no) document.game.help.value=”My number is less than “+no+”.”;
// your number is approaching my_no :-)
else alert(”It takes you “+count+” attempts to guess this number”); }
// end –>
</script>
<body bgcolor=”white” text=”#000000″ onload=”load()” onunload=”window.defaultStatus=””>
<center>
<form name=game>
<table border=3>
<tr><td align=center colspan=2>Range of numbers</td>
<td align=center rowspan=2><input type=button value=” Start ” onclick=”range()”></td></tr>
<tr><td align=center>From:<br><input type=text name=from size=10></td>
<td align=center>To:<br><input type=text name=to size=10></td></tr>
<tr><td></td></tr>
<tr><td align=center colspan=3><input type=text name=help size=70></td></tr>
<tr><td></td></tr>
<tr><td align=right colspan=3><input type=text name=number size=10><input type=button value=” Guess ” onclick=”guess()”></td></tr>
</table>
</form>
