Created
February 7, 2014 20:45
-
-
Save andycandrea/8871489 to your computer and use it in GitHub Desktop.
Basic JS Guessing Game created for use with TotT (Tools of the Trade - a series of lectures at UNC intended to supplement the CS curriculum)
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
/* | |
JS guessing game that picks a random number between 1 and 100 and prompts the user for up to five guesses. | |
The program then prints if the correct number is less than, greater than or equal to the guess. If five | |
guesses are completed without getting the right number, a loss message is output. | |
*/ | |
var correct = Math.floor(Math.random()*100)+1; | |
console.log(correct); | |
var readLine = require('readline'), rl = readLine.createInterface(process.stdin, process.stdout); | |
var MAX_TRIES = 5; | |
var count = 0; | |
rl.setPrompt('Guess a number between 1 and 100\n'); | |
rl.prompt(); | |
rl.on('line', function(line) { | |
line = Number(line); | |
if (line === correct){ | |
console.log('You won!'); | |
return; | |
} | |
else if (line > correct) { | |
console.log('Too high.'); | |
} | |
else if (line < correct) { | |
console.log('Too low.'); | |
} | |
else { | |
console.log('Please input a number.'); | |
} | |
if (++guesses >= MAX_TRIES) { | |
console.log("You lose."); | |
rl.close(); | |
return; | |
} | |
rl.prompt(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment