Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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)
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;
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.on('line', function(line) {
line = Number(line);
if (line === correct){
console.log('You won!');
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.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment