Gameeee
by wooozy
HTML
<h2>Guessing Game</h2>
<h3>Let the computer guess for you :D </h3>
<input type="button" value="Click me :)" onClick="guessAway();" />
<p>Choose a number from 1-1000->
<input style="width:50px;" type="textbox" id="targetValue"/>
</p>
<div id="output"></div>
JavaScript
var array = new Array(1000);
for (var n = 0; i < array.length; n++) {
array[n] = n + 1;}
function guessAway(){
var targetValue = parseInt(document.getElementById("targetValue").value);
var guess;
var count = 0;
var min = 0;
var max = array.length;
if (targetValue > array.length || targetValue < 1){ document.getElementById("output").innerHTML += ("Sorry, Choose a number from 1-1000<br>");
}else{
while (min <= max){
guess = Math.floor((min + max) / 2);
if (guess === targetValue){
count++; document.getElementById("output").innerHTML += ("Your Guess " + guess + " : Congrats you got it in " + count + " attempts!<br>");
return guess;
}else if (guess > targetValue){
count++;
max = guess - 1; document.getElementById("output").innerHTML += ("Your Guess " + guess + " - High, try again!<br>");
}else{
count++;
min = guess + 1; document.getElementById("output").innerHTML += ("Your Guess " + guess + " - Low, try again.<br>");
}}}}