-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
339 lines (296 loc) · 10.4 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const argv = Object.fromEntries(
process.argv
.slice(2)
.map((pair) => pair.split('='))
.filter((pair) => pair.length == 2)
.map(([key, value]) => [key.slice(2).replace(/-(\w)/g, (_, $1) => $1.toUpperCase()), value])
);
const firstPlayer = argv.firstPlayer || 'cpu';
if (!['cpu', 'player'].includes(firstPlayer)) {
console.log(`Invalid value for 'first-player': ${firstPlayer}. Must be one of: cpu, player`);
process.exit(1);
}
const numberMode = argv.numberMode || 'numpad';
if (!['numpad', 'natural'].includes(numberMode)) {
console.log(`Invalid value for 'number-mode': ${numberMode}. Must be one of: numpad, natural`);
process.exit(1);
}
const guideVisibility = argv.guideVisibility || 'visible';
if (!['visible', 'hidden'].includes(guideVisibility)) {
console.log(`Invalid value for 'guide-visibility': ${guideVisibility}. Must be one of: visible, hidden`);
process.exit(1);
}
const _ = 0; // Empty
const P = 1; // Player
const C = 2; // CPU
const $ = 3; // Any non-empty
const charset = { [_]: '', [C]: '◯', [P]: '✖' };
const color = { [charset[_]]: 30, [charset[C]]: 33, [charset[P]]: 32 };
const boardIndices = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
// prettier-ignore
const [ /* ___L, ___M, ___R */
/* Top_ */ TopL, TopM, TopR,
/* Mid_ */ MidL, MidM, MidR,
/* Bot_ */ BotL, BotM, BotR,
] = boardIndices;
const Rows = { Top: [TopL, TopM, TopR], Mid: [MidL, MidM, MidR], Bot: [BotL, BotM, BotR] };
const Cols = { L: [TopL, MidL, BotL], M: [TopM, MidM, BotM], R: [TopR, MidR, BotR] };
const Diag = { Pri: [TopL, MidM, BotR], Sec: [TopR, MidM, BotL] };
const board = [_, _, _, _, _, _, _, _, _];
let winner = null;
let hasError = false;
const main = () => {
if (firstPlayer == 'cpu') {
const cpuCell = computeNextMove();
if (cpuCell != null) board[cpuCell] = C;
}
loop();
};
const random = (values) => values[(Math.random() * values.length) | 0];
const match = (positions, match) => {
return positions
.map((pos) => board[pos])
.every((cell, i) => {
if (match[i] == $) return cell != _;
return match[i] == cell;
});
};
const all = (v) => Array(9).fill(v);
const computeNextMove = () => {
// If the CPU can win in this turn, win
// Horizontal pair
if (match(Rows.Top, [_, C, C])) return TopL;
if (match(Rows.Mid, [_, C, C])) return MidL;
if (match(Rows.Bot, [_, C, C])) return BotL;
if (match(Rows.Top, [C, _, C])) return TopM;
if (match(Rows.Mid, [C, _, C])) return MidM;
if (match(Rows.Bot, [C, _, C])) return BotM;
if (match(Rows.Top, [C, C, _])) return TopR;
if (match(Rows.Mid, [C, C, _])) return MidR;
if (match(Rows.Bot, [C, C, _])) return BotR;
// Vertical pair
if (match(Cols.L, [_, C, C])) return TopL;
if (match(Cols.M, [_, C, C])) return TopM;
if (match(Cols.R, [_, C, C])) return TopR;
if (match(Cols.L, [C, _, C])) return BotL;
if (match(Cols.M, [C, _, C])) return MidM;
if (match(Cols.R, [C, _, C])) return MidR;
if (match(Cols.L, [C, C, _])) return BotL;
if (match(Cols.M, [C, C, _])) return BotM;
if (match(Cols.R, [C, C, _])) return BotR;
// Diagonal pair
if (match(Diag.Pri, [_, C, C])) return TopL;
if (match(Diag.Pri, [C, _, C])) return MidM;
if (match(Diag.Pri, [C, C, _])) return BotR;
if (match(Diag.Sec, [_, C, C])) return TopR;
if (match(Diag.Sec, [C, _, C])) return MidM;
if (match(Diag.Sec, [C, C, _])) return BotL;
// If the player could win in the next turn, prevent it
// Horizontal pair
if (match(Rows.Top, [_, P, P])) return TopL;
if (match(Rows.Mid, [_, P, P])) return MidL;
if (match(Rows.Bot, [_, P, P])) return BotL;
if (match(Rows.Top, [P, _, P])) return TopM;
if (match(Rows.Mid, [P, _, P])) return MidM;
if (match(Rows.Bot, [P, _, P])) return BotM;
if (match(Rows.Top, [P, P, _])) return TopR;
if (match(Rows.Mid, [P, P, _])) return MidR;
if (match(Rows.Bot, [P, P, _])) return BotR;
// Vertical pair
if (match(Cols.L, [_, P, P])) return TopL;
if (match(Cols.M, [_, P, P])) return TopM;
if (match(Cols.R, [_, P, P])) return TopR;
if (match(Cols.L, [P, _, P])) return BotL;
if (match(Cols.M, [P, _, P])) return MidM;
if (match(Cols.R, [P, _, P])) return MidR;
if (match(Cols.L, [P, P, _])) return BotL;
if (match(Cols.M, [P, P, _])) return BotM;
if (match(Cols.R, [P, P, _])) return BotR;
// Diagonal pair
if (match(Diag.Pri, [_, P, P])) return TopL;
if (match(Diag.Pri, [P, _, P])) return MidM;
if (match(Diag.Pri, [P, P, _])) return BotR;
if (match(Diag.Sec, [_, P, P])) return TopR;
if (match(Diag.Sec, [P, _, P])) return MidM;
if (match(Diag.Sec, [P, P, _])) return BotL;
// Given that the CPU cannot win in this turn
// and the player cannot win in the next,
// prepare for reaching a win condition
// If no corner is used, occupy one
if (match([TopL, TopR, BotL, BotR], all(_))) return random([TopL, TopR, BotL, BotR]);
// Occupy the corner opposite to one already owned by the CPU
if (match([TopL, BotR], [_, C])) return TopL;
if (match([TopR, BotL], [_, C])) return TopR;
if (match([TopL, BotR], [C, _])) return BotR;
if (match([TopR, BotL], [C, _])) return BotL;
// Occupy the corner opposite to the player
if (match([TopL, BotR], [_, P])) return TopL;
if (match([TopR, BotL], [_, P])) return TopR;
if (match([TopL, BotR], [P, _])) return BotR;
if (match([TopR, BotL], [P, _])) return BotL;
// Occupy the corner adjacent to one already owned by the CPU
if (match([TopL, TopR], [_, C])) return TopL;
if (match([TopL, TopR], [C, _])) return TopR;
if (match([BotL, BotR], [_, C])) return BotL;
if (match([BotL, BotR], [C, _])) return BotR;
if (match([TopL, BotL], [_, C])) return TopL;
if (match([TopL, BotL], [C, _])) return BotL;
if (match([TopR, BotR], [C, _])) return BotR;
if (match([TopR, BotR], [_, C])) return TopR;
// If there are any spots left, the board is
// probably symmetric so we can choose any spot
const emptySpots = getEmptySpots();
if (emptySpots.length > 0) return random(emptySpots);
// No move found!
hasError = true;
return null;
};
const cpuWinSentences = [
'Are you even trying?',
'That was easy.',
'Zzz...',
'QED.',
'As always.',
'Yay!',
'You stand no chance!',
'Wanna try again? Are you sure?',
"You're wasting time.",
'In other news, water is wet.',
'What a news!',
'Is that surprising?',
'Of course.',
"You can't beat me.",
'Stop trying.',
'Why bother?',
];
const loop = async () => {
header();
drawBoard();
if (hasError) {
console.log(`Submit this to the developer: ${board.join('')}#${+firstPlayer == 'cpu'}_${+numberMode == 'numpad'}\n`);
process.exit(1);
}
if (winner == C) console.log(`You lost! ${random(cpuWinSentences)}\n`);
if (winner == P) console.log('No way! You won!\n');
if (winner == $) console.log('Draw!\n');
if (winner != null) process.exit(0);
let playerCell = await queryInput();
if (isValid(playerCell)) {
playerCell = mapIndex(+playerCell);
board[playerCell - 1] = P;
if (!isBoardFilled()) {
const cpuCell = computeNextMove();
if (cpuCell != null) board[cpuCell] = C;
}
}
if (win()) winner = C;
else if (lose()) winner = P;
else if (isBoardFilled()) winner = $;
loop();
};
const header = () => {
console.clear();
console.log('\x1b[34m<\x1b[36m<\x1b[35m Unbeatable Tic-Tac-Toe AI \x1b[36m>\x1b[34m>\x1b[0m');
console.log();
console.log(`\x1b[${color[charset[P]]}m${charset[P]}\x1b[0m = Player, \x1b[${color[charset[C]]}m${charset[C]}\x1b[0m = CPU`);
if (firstPlayer == 'cpu') console.log(`CPU goes first.`);
else console.log(`Player goes first.`);
console.log();
};
const mapIndex = (value) => {
if (numberMode == 'natural') return value;
if ([1, 2, 3].includes(value)) return value + 6;
if ([7, 8, 9].includes(value)) return value - 6;
return value;
};
const drawBoard = () => {
const c = (i) => {
const char = charset[board[i]];
return `\x1b[${color[char]}m${char || (guideVisibility == 'visible' ? mapIndex(i + 1) : ' ')}\x1b[0m`;
};
console.log(` ${c(0)} │ ${c(1)} │ ${c(2)}`);
console.log('───┼───┼───');
console.log(` ${c(3)} │ ${c(4)} │ ${c(5)} ${hasError ? '\x1b[31mUnable to find move!\x1b[0m' : ''}`);
console.log('───┼───┼───');
console.log(` ${c(6)} │ ${c(7)} │ ${c(8)}`);
console.log();
};
const isValid = (value) => {
value = mapIndex(+value);
if (isNaN(value)) return false;
if (value != Math.trunc(value)) return false;
if (value < 1 || value > 9) return false;
if (board[value - 1] != _) return false;
return true;
};
const queryInput = () => new Promise((resolve) => rl.question('Choose your cell: ', (answer) => resolve(answer)));
const isBoardEmpty = () => match(boardIndices, all(_));
const isBoardFilled = () => match(boardIndices, all($));
const getEmptySpots = () => {
return board
.map((v, i) => [v, i])
.filter(([v]) => v == _)
.map(([_, i]) => i);
};
const win = () => {
return (
match(Rows.Top, all(C)) ||
match(Rows.Mid, all(C)) ||
match(Rows.Bot, all(C)) ||
match(Rows.Top, all(C)) ||
match(Rows.Mid, all(C)) ||
match(Rows.Bot, all(C)) ||
match(Rows.Top, all(C)) ||
match(Rows.Mid, all(C)) ||
match(Rows.Bot, all(C)) ||
match(Cols.L, all(C)) ||
match(Cols.M, all(C)) ||
match(Cols.R, all(C)) ||
match(Cols.L, all(C)) ||
match(Cols.M, all(C)) ||
match(Cols.R, all(C)) ||
match(Cols.L, all(C)) ||
match(Cols.M, all(C)) ||
match(Cols.R, all(C)) ||
match(Diag.Pri, all(C)) ||
match(Diag.Pri, all(C)) ||
match(Diag.Pri, all(C)) ||
match(Diag.Sec, all(C)) ||
match(Diag.Sec, all(C)) ||
match(Diag.Sec, all(C))
);
};
const lose = () => {
return (
match(Rows.Top, all(P)) ||
match(Rows.Mid, all(P)) ||
match(Rows.Bot, all(P)) ||
match(Rows.Top, all(P)) ||
match(Rows.Mid, all(P)) ||
match(Rows.Bot, all(P)) ||
match(Rows.Top, all(P)) ||
match(Rows.Mid, all(P)) ||
match(Rows.Bot, all(P)) ||
match(Cols.L, all(P)) ||
match(Cols.M, all(P)) ||
match(Cols.R, all(P)) ||
match(Cols.L, all(P)) ||
match(Cols.M, all(P)) ||
match(Cols.R, all(P)) ||
match(Cols.L, all(P)) ||
match(Cols.M, all(P)) ||
match(Cols.R, all(P)) ||
match(Diag.Pri, all(P)) ||
match(Diag.Pri, all(P)) ||
match(Diag.Pri, all(P)) ||
match(Diag.Sec, all(P)) ||
match(Diag.Sec, all(P)) ||
match(Diag.Sec, all(P))
);
};
main();