Created
May 20, 2016 11:33
-
-
Save lesleh/c99fd036e4ae6cb9952abf27bcb97e53 to your computer and use it in GitHub Desktop.
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
"use strict"; | |
let readline = require('readline'); | |
class GuessTheNumber { | |
randomBetween(min, max) { | |
return Math.floor(Math.random() * (max - min + 1) + min); | |
} | |
guessAnswer(guess) { | |
if(guess < this.answer) { | |
return -1; | |
} else if(guess > this.answer) { | |
return 1; | |
} else { | |
return 0; | |
} | |
} | |
answerMessage(answerCode) { | |
if(answerCode < 0) { | |
return "Too low"; | |
} | |
if(answerCode > 0) { | |
return "Too high"; | |
} | |
return "Correct"; | |
} | |
constructor() { | |
this.min = 1; | |
this.max = 1000; | |
this.answer = this.randomBetween(this.min, this.max); | |
} | |
} | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}); | |
function readGuess() { | |
rl.question('Enter your guess: ', (answer) => { | |
var result = game.guessAnswer(parseInt(answer)); | |
var message = game.answerMessage(result); | |
console.log(message); | |
if(result != 0) { | |
readGuess(); // Ask again | |
} else { | |
rl.close(); | |
} | |
}); | |
} | |
let game = new GuessTheNumber(); | |
console.log(`Guess the number! Between ${game.min} and ${game.max}`); | |
readGuess(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment