Skip to content

Instantly share code, notes, and snippets.

@parente
Created February 7, 2014 20:41
Show Gist options
  • Select an option

  • Save parente/8871408 to your computer and use it in GitHub Desktop.

Select an option

Save parente/8871408 to your computer and use it in GitHub Desktop.
Guessing game for TotT
/*
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);
// console.log(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('Uh. Try again.');
}
guesses += 1;
if(guesses >= MAX_TRIES) {
console.log('You lose!');
rl.close();
return;
}
rl.prompt();
}).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