Skip to content

Instantly share code, notes, and snippets.

@TheSaviourEking
Last active September 4, 2023 03:48
Show Gist options
  • Save TheSaviourEking/89c64ab0cf2561f0db70597347d9721c to your computer and use it in GitHub Desktop.
Save TheSaviourEking/89c64ab0cf2561f0db70597347d9721c to your computer and use it in GitHub Desktop.
Number Guessing Game A simple number guessing game implemented in JavaScript. The game prompts the user to specify the range of numbers and the number of attempts they want to make. Then, it generates a random number within the specified range, and the user tries to guess the secret number within the given number of attempts. The game provides f…
// Require the 'readline' module to handle user input.
readline = require('node:readline');
/**
* Create an interface for reading user input from the console.
* @type {readline.Interface}
*/
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout // Use process.stdout for output
});
/************************************************************* */
/**
* The secret number for the guessing game.
* @type {number}
*/
let secretNumber = 0;
/**
* The number of attempts for the guessing game.
* @type {number}
*/
let numAttempts = 5;
/**
* Check if a value is a valid numeric value (not NaN and of type 'number').
*
* @param {*} value - The value to be checked.
* @returns {boolean} - True if the value is a valid number, false otherwise.
*/
function isValidValue(value) {
return typeof value === 'number' && !isNaN(value);
}
/**
* Check if the user's guess is correct.
*
* @param {number} guess - The user's guess to be checked
* @returns {boolean} - True if the guess is correct, false otherwise
*/
let checkGuess = (guess) => {
if (isValidValue(guess)) {
if (guess > secretNumber) {
console.log(`Too High, Attempts Left: ${numAttempts}`);
return false;
} else if (guess < secretNumber) {
console.log(`Too Low, Attempts Left: ${numAttempts}`);
return false;
} else {
console.log('Correct');
return true;
}
} else {
console.log('Invalid input. Please enter a valid number.');
return false;
}
}
/**
* Ask the user for their guess in recurse until they get it right.
*/
const askGuess = () => {
--numAttempts;
console.log('Guess Must be a number');
rl.question('Enter a guess: ', (answer) => {
// Convert the user's input to a number and check if it's correct.
if (numAttempts > 0) {
if (!checkGuess(Number(answer))) {
askGuess()
} else {
console.log('You win!')
rl.close(); // Close the input interface when the guess is correct.
}
} else {
console.log('You Lose');
rl.close();
}
});
}
/**
* Generates a random integer within a specified range, inclusive.
*
* @param {number} minNumber - The minimum value in the range.
* @param {number} maxNumber - The maximum value in the range.
* @returns {number} - A random integer between minNumber and maxNumber (inclusive).
*/
const randomInRange = (minNumber, maxNumber) => {
minNumber = Math.ceil(minNumber);
maxNumber = Math.floor(maxNumber);
return Math.floor(Math.random() * (maxNumber - minNumber + 1) + minNumber); // The maxNumber and minNumber inclusive;
}
/**
* Prompt the user to enter a range (min and max numbers) for the random number.
* Once the range is entered, generate a random number within that range and start the guessing game.
*/
const askRange = () => {
rl.question('Enter a max number: ', (max) => {
rl.question('Enter a min number: ', (min) => {
if (isValidValue(Number(max)) && isValidValue(Number(min))) {
if (min >= max || min + 1 === max) {
console.log("The first number should be at least 2 digits smaller than the second number. Try again.")
askRange();
} else {
// Generate a random number within the specified range.
console.log(`I'm thinking of a number between ${min} and ${max}...`);
secretNumber = randomInRange(Number(min), Number(max));
// Start the guessing game.
askGuess();
}
} else {
console.log('Invalid input. Please enter valid numbers for max and min.');
// You may choose to ask for input again or handle this case as appropriate.
askRange()
}
})
})
}
/**
* Prompt the user to specify the number of attempts they want to make in the guessing game.
* If the user provides a valid numeric input, the game is started with the specified number of attempts.
* If the input is not a valid number, an error message is displayed, and the program exits.
*/
const asklimit = () => {
rl.question('How many attempts do you want to make? ', (answer) => {
if (isValidValue(Number(answer))) {
numAttempts = Number(answer);
askRange();
} else {
console.log('Attempts must be a number');
rl.close();
}
});
}
// Start Game
asklimit()
// https://my.appacademy.io/lessons/user-input/0e404b7c/practices/guessing-game-project/d236f9b6
// https://gist.github.com/TheSaviourEking/89c64ab0cf2561f0db70597347d9721c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment