Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·221 lines (190 loc) · 6.03 KB
/
Copy pathindex.js
File metadata and controls
executable file
·221 lines (190 loc) · 6.03 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#!/usr/bin/env node
const fs = require(`fs`);
const ArgumentParser = require(`argparse`).ArgumentParser;
const ansi = require(`./ansi`);
const npmPackage = JSON.parse(fs.readFileSync(`${__dirname}/package.json`));
const argParser = new ArgumentParser({
version: npmPackage.version,
description: `The famous Matrix rain effect of falling green characters as a cli command`,
});
[
{
flags: [ `-d`, `--direction` ],
opts: {
choices: [`h`, `v`],
defaultValue: `v`,
help: `Change direction of rain. h=horizontal, v=vertical.`,
},
},
{
flags: [ `-c`, `--color` ],
opts: {
choices: [`green`, `red`, `blue`, `yellow`, `magenta`, `cyan`, `white`],
defaultValue: `green`,
dest: `color`,
help: `Rain color. NOTE: droplet start is always white.`,
},
},
{
flags: [ `-k`, `--char-range` ],
opts: {
choices: [`ascii`, `binary`, `braille`, `emoji`, `kanji`],
defaultValue: `ascii`,
dest: `charRange`,
help: `Use rain characters from char-range.`,
},
},
{
flags: [ `-f`, `--file-path` ],
opts: {
dest: `filePath`,
help: `Read characters from a file instead of random characters from char-range.`,
},
},
].forEach(({flags, opts}) => argParser.addArgument(flags, opts));
// Simple string stream buffer + stdout flush at once
let outBuffer = [];
function write(chars) {
return outBuffer.push(chars);
}
function flush() {
process.stdout.write(outBuffer.join(``));
return outBuffer = [];
}
function rand(start, end) {
return start + Math.floor(Math.random() * (end - start));
}
class MatrixRain {
constructor(opts) {
this.transpose = opts.direction === `h`;
this.color = opts.color;
this.charRange = opts.charRange;
this.maxSpeed = 20;
this.colDroplets = [];
this.numCols = 0;
this.numRows = 0;
// handle reading from file
if (opts.filePath) {
if (!fs.existsSync(opts.filePath)) {
throw new Error(`${opts.filePath} doesn't exist`);
}
this.fileChars = fs.readFileSync(opts.filePath, `utf-8`).trim().split(``);
this.filePos = 0;
this.charRange = `file`;
}
}
generateChars(len, charRange) {
// by default charRange == ascii
let chars = new Array(len);
if (charRange === `ascii`) {
for (let i = 0; i < len; i++) {
chars[i] = String.fromCharCode(rand(0x21, 0x7E));
}
} else if (charRange === `braille`) {
for (let i = 0; i < len; i++) {
chars[i] = String.fromCharCode(rand(0x2840, 0x28ff));
}
} else if (charRange === `kanji`) {
for (let i = 0; i < len; i++) {
chars[i] = String.fromCharCode(rand(0x30a0, 0x30ff));
}
} else if (charRange === `emoji`) {
// emojis are two character widths, so use a prefix
const emojiPrefix = String.fromCharCode(0xd83d);
for (let i = 0; i < len; i++) {
chars[i] = emojiPrefix + String.fromCharCode(rand(0xde01, 0xde4a));
}
} else if (charRange === `file`) {
for (let i = 0; i < len; i++, this.filePos++) {
this.filePos = this.filePos < this.fileChars.length ? this.filePos : 0;
chars[i] = this.fileChars[this.filePos];
}
}
return chars;
}
makeDroplet(col) {
return {
col,
alive: 0,
curRow: rand(0, this.numRows),
height: rand(this.numRows / 2, this.numRows),
speed: rand(1, this.maxSpeed),
chars: this.generateChars(this.numRows, this.charRange),
};
}
resizeDroplets() {
[this.numCols, this.numRows] = process.stdout.getWindowSize();
// transpose for direction
if (this.transpose) {
[this.numCols, this.numRows] = [this.numRows, this.numCols];
}
// Create droplets per column
// add/remove droplets to match column size
if (this.numCols > this.colDroplets.length) {
for (let col = this.colDroplets.length; col < this.numCols; ++col) {
// make two droplets per row that start in random positions
this.colDroplets.push([this.makeDroplet(col), this.makeDroplet(col)]);
}
} else {
this.colDroplets.splice(this.numCols, this.colDroplets.length - this.numCols);
}
}
writeAt(row, col, str, color) {
// Only output if in viewport
if (row >=0 && row < this.numRows && col >=0 && col < this.numCols) {
const pos = this.transpose ? ansi.cursorPos(col, row) : ansi.cursorPos(row, col);
write(`${pos}${color || ``}${str || ``}`);
}
}
renderFrame() {
const ansiColor = ansi.colors[`fg${this.color.charAt(0).toUpperCase()}${this.color.substr(1)}`]();
for (const droplets of this.colDroplets) {
for (const droplet of droplets) {
const {curRow, col: curCol, height} = droplet;
droplet.alive++;
if (droplet.alive % droplet.speed === 0) {
this.writeAt(curRow - 1, curCol, droplet.chars[curRow - 1], ansiColor);
this.writeAt(curRow, curCol, droplet.chars[curRow], ansi.colors.fgWhite());
this.writeAt(curRow - height, curCol, ` `);
droplet.curRow++;
}
if (curRow - height > this.numRows) {
// reset droplet
Object.assign(droplet, this.makeDroplet(droplet.col), {curRow: 0});
}
}
}
flush();
}
}
//// main ////
const args = argParser.parseArgs();
const matrixRain = new MatrixRain(args);
function start() {
if (!process.stdout.isTTY) {
console.error(`Error: Output is not a text terminal`);
process.exit(1);
}
// clear terminal and use alt buffer
process.stdin.setRawMode(true);
write(ansi.useAltBuffer());
write(ansi.cursorInvisible());
write(ansi.colors.bgBlack());
write(ansi.colors.fgBlack());
write(ansi.clearScreen());
flush();
matrixRain.resizeDroplets();
}
function stop() {
write(ansi.cursorVisible());
write(ansi.clearScreen());
write(ansi.cursorHome());
write(ansi.useNormalBuffer());
flush();
process.exit();
}
process.on(`SIGINT`, () => stop());
process.stdin.on(`data`, () => stop());
process.stdout.on(`resize`, () => matrixRain.resizeDroplets());
setInterval(() => matrixRain.renderFrame(), 16); // 60FPS
start();