Last active
December 1, 2015 21:43
-
-
Save itsanna/62c719550e08642669e5 to your computer and use it in GitHub Desktop.
Number guessing game
This file contains 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
// Write a function that is a number guessing game. It should determine a random number from 1-100, and let the user guess the number. | |
// It should report back whether their guess is correct, too high, or too low. Important: if the user guesses a number they've already | |
// guessed, it should tell them they have previously guessed this number. Until they guess the correct number, it should continue to prompt | |
// them. Once they've guessed the correct number, it should congratulate them and tell them how many guesses they took to solve the problem | |
// (minus any duplicate guesses). | |
function game() { | |
var guess = [] // store user's guesses | |
var randNum = Math.floor(Math.random() * (100)) + 1 | |
function numberGuesser(num) { | |
if (guess.indexOf(num) !== -1) { // if current guess is found in our storage of guesses | |
return 'You already guessed this number' | |
} | |
if (typeof num !== "number") { // if argument isn't a number | |
return 'Argument must be a number!' | |
} | |
guess.push(num) | |
if (num < randNum) { // if guess is lower | |
return 'Your guess is too low' | |
} | |
if (num > randNum) { // if guess is higher | |
return 'Your guess is too high' | |
} | |
else { | |
return 'Congrats! You got it!! IT ONLY TOOK YOU ' + guess.length + ' TRIES' | |
} | |
} | |
return check // return a function to be called later | |
} | |
var check = game() // invoke 'game', which returns a function. Give it a name, 'check' | |
check(44) // invoke 'check' with a number guess | |
check(44) // invoke again with the same number, get a message: 'You already guessed this number' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment