Created
October 23, 2014 07:44
-
-
Save ryanorsinger/f5788103d0bb79a7b56a to your computer and use it in GitHub Desktop.
High Low Game with small functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Generate a random integer between 1 and 100 each time the function is called. | |
function getRandom() { | |
return Math.floor(Math.random() * 101); | |
} | |
// Prompt the user for their guess and validate it. | |
function getNewGuess() { | |
var userGuess = parseInt(prompt('Input a number between 1 and 100')); | |
return validateOrRetryInput(userGuess); | |
} | |
// Prompts users to enter a new guess if validation fails. | |
function validateOrRetryInput(userGuess) { | |
if (Number.isInteger(userGuess) && (userGuess < 100 || userGuess > 1 )) { | |
return userGuess; | |
} else { | |
alert('Dear Player, your guess must be an integer less than 100 and greater than 1. Please try again.'); | |
return getNewGuess(); | |
} | |
} | |
var randomNumber = getRandom(); | |
console.log('The randomly generated number is ' + randomNumber); | |
do { | |
var guessedNumber = getNewGuess(); | |
if (guessedNumber < randomNumber) { | |
alert('You guessed too low!'); | |
} | |
if (guessedNumber > randomNumber) { | |
alert('You guessed too high!'); | |
} | |
} while (guessedNumber != randomNumber); | |
alert('Congratulations! You\'ve earned victory in the High-Low Game!'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment