Get Programming with JavaScript - Listings 13.07 and 13.08
Listings 13.07 and 13.08 - Using spacer and between in the guessing game
JS Bin
HTML:
<!-- number generator -->
<script src="http://output.jsbin.com/qezoce.js"></script>
<!-- spacer -->
<script src="http://output.jsbin.com/juneqo.js"></script>
JS:
var getGuesser = function (lowest, highest) {
var secret = between(lowest, highest);
return function (userNumber) {
if (userNumber === secret) {
return spacer.box("Well done!", 14, "=");
} else if (userNumber > secret) {
return spacer.box("Too high!", 13, "+");
} else {
return spacer.box("Too low!", 12, "-");
}
};
};
var guess = getGuesser(5, 10);
Further Adventures
Listings 13.07 and 13.08 - Using spacer and between in the guessing game - Task 1
- Report the number of guesses taken at each stage.
var getGuesser = function (lowest, highest) {
var secret = between(lowest, highest);
var numGuesses = 0;
return function (userNumber) {
var msg;
numGuesses += 1;
if (userNumber === secret) {
msg = "Well done! (" + numGuesses + " guesses)";
return spacer.box(msg, msg.length + 4, "=");
} else if (userNumber > secret) {
msg = "Too high! (" + numGuesses + " guesses)";
return spacer.box(msg, msg.length + 4, "+");
} else {
msg = "Too low! (" + numGuesses + " guesses)";
return spacer.box(msg, msg.length + 4, "-");
}
};
};
var guess = getGuesser(5, 10);
Listings 13.07 and 13.08 - Using spacer and between in the guessing game - Task 2
- End the game after a certain number of guesses.
var getGuesser = function (lowest, highest) {
var secret = between(lowest, highest);
var numGuesses = 0;
var maxGuesses = 3;
var inPlay = true;
return function (userNumber) {
var msg;
if (inPlay) {
numGuesses += 1;
if (numGuesses === maxGuesses) {
inPlay = false;
}
if (userNumber === secret) {
msg = "Well done! (" + numGuesses + " guesses)";
return spacer.box(msg, msg.length + 4, "=");
} else if (userNumber > secret) {
msg = "Too high! (" + numGuesses + " guesses)";
return spacer.box(msg, msg.length + 4, "+");
} else {
msg = "Too low! (" + numGuesses + " guesses)";
return spacer.box(msg, msg.length + 4, "-");
}
} else {
return spacer.box("Out Of Guesses", 18, "!");
}
};
};
var guess = getGuesser(5, 10);