Skip to content

Instantly share code, notes, and snippets.

@krab7191
Created Feb 7, 2014
Embed
What would you like to do?
guess.js
/*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