Lesson 8 Challenge 3
by nathanesa
JavaScript
// Introduce the game.
alert('Think of a number between 1 and 20.');
alert("Don't tell me!");
// Set the bounds for later calculations.
var lowerLimit = 1;
var upperLimit = 20;
var response = '';
while (response != 'y') {
// Our guess is the average or middle of the two bounds.
var guess = (lowerLimit + upperLimit) / 2;
// Round it down to a whole number using the floor command.
guess = Math.floor(guess);
// Get feedback from player and adjust a bound for next time.
response = prompt("Is it " + guess + "? Enter 'h' for higher, 'l' for lower, or 'y' to finish:");
if (response == 'h') {
lowerLimit = guess + 1;
}
if (response == 'l') {
upperLimit = guess - 1;
}
}
// Game is over.
alert('Yay! That was fun.');