It's been long enough that you've probably done it by now anyway, so I guess it's OK for me to show off:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Number Guesser</title>
<script type="text/javascript">
var Functional = {
Operator: {
add: function(a, b) {
return a + b;
}
},
reduce: function(f, a, initial) {
var t = initial || 0;
for(var i = 0; i < a.length; ++i)
t = f(t, a[i]);
return t;
}
};
Math.mean = function() {
return Functional.reduce(Functional.Operator.add, arguments) / arguments.length;
};
function GuessGame(upperBound, lowerBound, maxGuesses) {
this.ub = upperBound || 1001;
this.lb = lowerBound || 1;
this.mg = maxGuesses || 1000;
this.breakPlay = false;
}
GuessGame.HIGHER = 1;
GuessGame.LOWER = 2;
GuessGame.CORRECT = 3;
GuessGame.prototype = {
playBlocking: function() {
var d;
for(var i = 0; i < this.mg; ++i)
if(!this.breakPlay && (d = this.tryGuessBlocking()))
this.updateBounds(this.getGuess(), d);
else break;
if(this.breakPlay && this.ub !== this.lb)
this.fail();
},
getGuess: function() {
return Math.floor(Math.mean(this.ub, this.lb));
},
updateBounds: function(num, direction) {
if(direction === GuessGame.HIGHER)
if(num < this.ub)
return (this.ub = num) ? true : true;
else {
alert(num + " < " + this.ub);
return false;
}
else if(direction === GuessGame.LOWER)
if(num > this.lb)
return (this.lb = num) ? true : true;
else return false;
else if(direction === GuessGame.CORRECT) {
this.succeed(num);
return (this.ub = this.lb = num) ? true : true;
}
},
tryGuessBlocking: function() {
var h;
do
h = (h = prompt("I guess " + this.getGuess() + ". Is this [h]igher, [l]ower, or [c]orrect?")) ? h.charAt(0).toLowerCase() : h;
while(h !== null && (h.length !== 1 || "hlc".indexOf(h) === -1));
if(h === null)
return null;
else return ({h: GuessGame.HIGHER,
l: GuessGame.LOWER,
c: GuessGame.CORRECT})[h];
},
succeed: function(n) {
this.breakPlay = true;
alert("The answer is " + n);
},
fail: function() {
this.breakPlay = true;
alert("I failed to find your answer.");
}
};
</script>
</head>
<body>
<div>
<input type="button" onclick="(new GuessGame()).playBlocking();" value="Play">
</div>
</body>
</html>
Bookmarks