-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathguess.js
More file actions
25 lines (22 loc) · 746 Bytes
/
guess.js
File metadata and controls
25 lines (22 loc) · 746 Bytes
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
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const rand = () => Math.floor(Math.random() * 100) + 1;
function play() {
const secret = rand();
let tries = 0;
const ask = () =>
rl.question('Guess (1-100): ', (ans) => {
const n = parseInt(ans, 10);
if (Number.isNaN(n)) return ask();
tries++;
if (n > secret) return console.log('Too high'), ask();
if (n < secret) return console.log('Too low'), ask();
console.log(`Correct! Attempts: ${tries}`);
rl.question('Play again? (y/n): ', (r) => {
if (r.trim().toLowerCase().startsWith('y')) return play();
rl.close();
});
});
ask();
}
play();