-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
45 lines (36 loc) · 1.06 KB
/
index.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
const express = require('express')
const app = express()
const port = 3000
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
const randomNumber = Math.floor(Math.random() * 100) + 1
console.log(`The random number is: ${randomNumber}`)
let attempts = 0 // Declare and initialize the attempts variable
console.log('Welcome to the Number Guessing Game!')
console.log(
'I have selected a random number between 1 and 100. Can you guess it?'
)
const askQuestion = () => {
rl.question('Enter your guess: ', (answer) => {
const guess = parseInt(answer, 10)
attempts += 1
if (isNaN(guess)) {
console.log('Please enter a valid number.')
} else if (guess < randomNumber) {
console.log('Too low! Try again.')
} else if (guess > randomNumber) {
console.log('Too high! Try again.')
} else {
console.log(
`Congratulations! You guessed the number in ${attempts} attempt(s).`
)
rl.close()
return
}
askQuestion()
})
}
askQuestion()