-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
55 lines (45 loc) · 949 Bytes
/
cli.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
const readline = require('readline'),
Engine = require('./src/engine');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: '2048> '
});
function newGame() {
const engine = new Engine();
engine.fillRandomTiles();
return engine;
}
function clear() {
console.log('\033[2J');
}
clear();
let engine = newGame();
engine.print();
rl.on('line', (input) => {
if (input === 'new') {
clear();
engine = newGame();
engine.print();
} else if (input === 'quit') {
process.exit(0);
}
rl.clearLine();
});
process.stdin.on('keypress',function(sequence, {name}){
if (engine.isEnded) return;
if ([
'up',
'down',
'left',
'right'
].indexOf(name) === -1) return;
clear();
try {
engine.move(name, true);
engine.print();
} catch (e) {
console.log('THE END. Type "new" to play another one, and "quit" to quit');
rl.prompt(true);
}
});