-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
executable file
·227 lines (208 loc) · 5.99 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
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
222
223
224
225
226
227
#!/usr/bin/env node
'use strict';
const readline = require('readline');
const clear = require('clear');
const Nsweeper = require('./nsweeper');
const commander = require('commander');
const chalk = require('chalk');
const unselectedChar = '▆';
const mineChar = 'X';
const flagChar = '⚑';
const helpText = `
Select coordination with a list of numbers separated by a non number character.
Example: "1 2" will pick top row, one to the right on a grid.
Additional dimensions require additional numbers, for example this would be a
valid coordinate set for a 4 dimensional board: "1 2 3 4".
You can flag/unflag coordinates by preceeding them with the letter f.
`;
const program = new commander.Command();
program.version('1.0.0');
function optParseInt(value) {
return parseInt(value);
}
function optParsePercent(value) {
return parseFloat(value);
}
function optParseBool(value) {
if (value === 'f' || value === 'false' || value === 'no' || value === '0') {
return false;
}
return !!value;
}
program
.option('-s, --size <number>', 'size of board along each dimension', optParseInt, 10)
.option('-d, --dimension <number>', 'number of dimensions', optParseInt, 2)
.option(
'-x, --difficulty <float>',
'difficulty, a float between 0 and 1 that reflects mine density',
optParsePercent,
0.2
)
.option('-w, --easywin <boolean>', 'do not require flagging all mines', optParseBool, false)
.option('-t, --test <boolean>', 'for testing, build board and exit with duration', optParseBool, false)
.parse(process.argv);
async function main() {
const startDatetime = new Date();
let game;
try {
game = new Nsweeper({
dim: program.dimension,
size: program.size,
density: program.difficulty,
autoWin: program.easywin,
});
} catch (err) {
console.log('Could not initialize game, see error below.');
console.log(err);
process.exit(1);
}
if (program.test) {
console.log(`Test: board build duration ${new Date() - startDatetime} ms.`);
process.exit(0);
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const prompt = 'Pick coordinates, exit, moves, or help: ';
clear();
console.log(
`=> Initialized nsweeper board with ${game.dim} dimensions, ${
game.size
} length per dimension, containing ${Math.floor(game.density * 100)}% mines. Easy win is ${
game.autoWin ? 'on' : 'off'
}.
`
);
printGame(game);
process.stdout.write(prompt);
for await (const line of rl) {
clear();
if (line === 'quit' || line === 'exit') {
console.log('=> Exiting...');
rl.close();
continue;
}
if (line === 'help' || line === 'h') {
console.log('=> Displaying help...\n');
printGame(game);
console.log(helpText);
process.stdout.write(prompt);
continue;
}
if (line === 'moves' || line === 'move') {
console.log('=> Displaying moves...\n');
printGame(game);
console.log(game.moves);
process.stdout.write(prompt);
continue;
}
if (line.startsWith('f')) {
console.log('=> Toggling flag...\n');
const indexes = parseSelection(line);
game.toggleFlag(indexes);
} else {
const indexes = parseSelection(line);
const resp = game.select(indexes);
if (resp.err) {
console.log(`=> ${resp.err}\n`);
} else {
console.log(`=> Revealed ${resp.val}\n`);
}
}
if (game.mineSelected) {
printGame(game, true);
console.log('You hit a mine! Game over.');
rl.close();
} else if (game.checkWin()) {
printGame(game, true);
console.log('You WON!');
rl.close();
} else {
printGame(game);
process.stdout.write(prompt);
}
}
}
function printGame(game, fullBoard = false) {
function condition() {
return true;
}
function effect({ arr, indices, i }) {
let visibile = false;
const curIndexString = JSON.stringify([...indices, i]);
const row = indices[indices.length - 1] || 0;
const val = arr[i];
const transition = i + 1 === game.size;
const horizontalHeaderNeeded = row === 0 && i === 0;
const thirdDimesionHeader = indices.length > 1 ? indices[indices.length - 2] + 1 : null;
for (let i = 0; i < game.moves.length; i++) {
if (game.moves[i] === curIndexString) {
visibile = true;
break;
}
}
// Column headers
if (horizontalHeaderNeeded) {
printHeaderIndexes(game.size, thirdDimesionHeader);
}
// Top left corner 3D+ indicator
if (i === 0) {
if (indices.length > 0) {
writeCell(row + 1, chalk.inverse);
} else {
writeCell(' ');
}
}
if (game.flags.indexOf(curIndexString) !== -1) {
writeCell(flagChar);
} else if (visibile || fullBoard) {
writeCell(val);
} else {
writeCell(unselectedChar);
}
if (transition) {
writeNewline();
}
}
Nsweeper.nestedArrayIterator({ originalArr: game.board, arr: game.board, indices: [], condition, effect });
writeNewline();
}
function parseSelection(line) {
const strings = line.split(/[^0-9]+/);
const indexes = strings.reduce((acc, cur) => {
if (cur !== null && cur !== undefined && cur !== '') {
acc.push(parseInt(cur) - 1);
}
return acc;
}, []);
return indexes;
}
function writeNewline() {
process.stdout.write('\n');
}
function padCell(input, rightPad = false, padTo = 4) {
let s = input.toString();
while (s.length < padTo) {
s = rightPad ? s + ' ' : ' ' + s;
}
return s;
}
function writeCell(input, modifier = x => x) {
if (input === Nsweeper.MINE) {
input = mineChar;
}
const stringPaddedInput = padCell(input);
process.stdout.write(modifier(stringPaddedInput));
}
function printHeaderIndexes(size, header = null) {
writeNewline();
if (header) {
process.stdout.write(chalk.inverse(padCell(header, true)));
} else {
writeCell(' ', chalk.inverse);
}
Array.from({ length: size }, (_, x) => writeCell(x + 1, chalk.inverse));
writeNewline();
}
main();