-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumber-guessing-game.js
44 lines (36 loc) · 1.04 KB
/
number-guessing-game.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const readline = require('readline');
// Generate a random number between 1 and 100
const secretNumber = Math.floor(Math.random() * 100) + 1;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function startGame() {
console.log('Welcome to the Number Guessing Game!');
console.log('I have selected a number between 1 and 100. Your task is to guess the correct number.');
askForGuess();
}
function askForGuess() {
rl.question('Enter your guess: ', (userInput) => {
const userGuess = parseInt(userInput);
if (isNaN(userGuess)) {
console.log('Please enter a valid number.');
} else {
checkGuess(userGuess);
}
});
}
function checkGuess(guess) {
if (guess === secretNumber) {
console.log(`Congratulations! You guessed the correct number (${secretNumber}).`);
rl.close();
} else if (guess < secretNumber) {
console.log('Too low! Try again.');
askForGuess();
} else {
console.log('Too high! Try again.');
askForGuess();
}
}
// Start the game
startGame();