-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathguess.js
61 lines (52 loc) · 1.39 KB
/
guess.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const express = require("express");
const app = express();
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let secretNumber;
let attempts = 3;
function startGame() {
secretNumber = Math.floor(Math.random() * 10) + 1;
attempts = 3;
console.log('Guess the secret number (between 1 and 10). You have 3 attempts.\n');
askQuestion();
}
function askQuestion() {
rl.question('Enter your guess: ', (guess) => {
const number = parseInt(guess);
if (isNaN(number)) {
console.log('Invalid input. Please enter a number.\n');
askQuestion();
} else {
checkGuess(number);
}
});
}
function checkGuess(number) {
if (number === secretNumber) {
console.log('Congratulations! You guessed the secret number.\n');
playAgain();
} else {
attempts--;
if (attempts === 0) {
console.log(`Wrong guess. You ran out of attempts. The secret number was ${secretNumber}.\n`);
playAgain();
} else {
console.log(`Wrong guess. Try again. You have ${attempts} attempt(s) remaining.\n`);
askQuestion();
}
}
}
function playAgain() {
rl.question('Do you want to play again? (yes/no): ', (answer) => {
if (answer.toLowerCase() === 'yes') {
startGame();
} else {
console.log('Thank you for playing! Goodbye.');
rl.close();
}
});
}
startGame();