-
Notifications
You must be signed in to change notification settings - Fork 30
/
guess.js
59 lines (48 loc) · 1.26 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
//
// guess.js - guessing game in javascript
//
// This is written to demonstrate this language versus the same program
// written in other languages.
//
// RUN:
// nodejs guess.js
//
// 01-Sep-2018 Scott Emmons Created.
//
var readline = require('readline');
var fs = require('fs');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
var main=(function *() {
const answer = Math.floor(Math.random()*100)+1;
const scorefile = 'highscores_js';
var guess = -1;
var num = 0;
console.log('guess.js - Guess a number between 1 and 100\n');
// Play game
while (guess != answer) {
num+=1;
console.log('Enter guess ' + num + ':');
guess = yield;
if (guess < answer) {
console.log('Higher...');
} else if (guess > answer) {
console.log('Lower...');
}
}
console.log('Correct! That took ' + num + ' guesses.\n');
// Save high score
console.log('Please enter your name:');
name = yield;
fs.writeFileSync(scorefile, name + " " + num + "\n", {'flag': 'a'});
// Print high scores
console.log('\nPrevious high scores:');
var input = fs.readFileSync(scorefile);
console.log(input.toString());
rl.close();
})();
main.next();
rl.on('line', input=>main.next(input))