Created
February 7, 2014 20:43
-
-
Save krab7191/8871453 to your computer and use it in GitHub Desktop.
guess.js
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 JS guessing game that picks a random, secret number between 1 and 100, lets the user take up to 5 guesses, and states if the secret number is equal to, higher, lower than a guess. Read input from stdin and print to stdout.*/ | |
var correct = Math.floor(Math.random()*100)+1; | |
//console.log(correct); | |
var MAX_TRIES = 5; | |
var readline = require('readline'); | |
var rl = readline.createInterface(process.stdin, process.stdout); | |
var guesses = 0; | |
rl.setPrompt('Guess a number between 1 and 100.'); | |
rl.prompt(); | |
rl.on('line', function(line) { | |
//console.log(line); | |
line = Number(line); | |
if (line === correct) { | |
console.log("You got it!"); | |
rl.close(); | |
return; | |
} else if(line > correct){ | |
console.log('Too high.'); | |
} else if (line < correct){ | |
console.log('Too low.'); | |
} else { | |
console.log('Umm...Try again.'); | |
} | |
if (++guesses >= MAX_TRIES) { | |
console.log('You lose'); | |
rl.close(); | |
return; | |
} | |
}).on('close', function(){ | |
console.log("bye!"); | |
//process.exit(0); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment