-
Notifications
You must be signed in to change notification settings - Fork 271
/
go.js
1564 lines (1508 loc) · 79.3 KB
/
go.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**Author:
* Discord:
* - Sphyxis
*
* Additional Contributers:
* Discord:
* - Stoneware
* - gmcew
* - eithel
* - Insight (alainbryden)
*/
import { getConfiguration, instanceCount, log, getErrorInfo, getActiveSourceFiles, getNsDataThroughFile, tail } from "./helpers";
const argsSchema = [
['cheats', true], // (Now true by default - but still an option for backwards compatibility) This is only possible if you have BN14.2
['disable-cheats', false], // Set to true if you want to *not* use cheats for some reason.
['cheat-chance-threshold', 0.9], // Don't cheat if our success chance is less than this
['logtime', false], // Logs time time it takes for each player to take their move
['runOnce', false], // Will only play one game if enabled
['silent', false], // (Obsolete) This script used to automatically tail. Now if you want to do this, call with --tail like normal.
];
export function autocomplete(data, args) {
data.flags(argsSchema);
return [];
}
/** Main script entrypoint.
* Note that to protect against "shared global memory", the entire script is wrapped in the body of the main function.
* @param {NS} ns */
export async function main(ns) {
let cheats = false;
let cheatChanceThreshold = 1.0;
let logtime = false;
let runOnce = true;
let silent = false;
let currentValidMovesTurn = 0; //The turn count that the currentValidMoves is valid for
let turn = 0;
let START = performance.now();
// Global variables initialized in this way get strong typing throughout
let board = (/**@returns{string[]}*/() => undefined)(); // The current board state
let currentValidMoves = (/**@returns{number[][]}*/() => undefined)(); //All valid moves for this turn
let currentValidContestedMoves = (/**@returns{number[][]}*/() => undefined)(); //All valid moves that occupy a contested space
let contested = (/**@returns{string[]}*/() => undefined)();
let validMove = (/**@returns{boolean[][]}*/() => undefined)();
let validLibMoves = (/**@returns{number[][]}*/() => undefined)();
let chains = (/**@returns{number[][]}*/() => undefined)();
let testBoard = (/**@returns{string[]}*/() => [])();
//X,O = Me, You x, o = Anything but the other person or a blocking, "W" space is off the board, ? is anything goes
//B is blocking(Wall or you, not empty or enemy), b is blocking but could be enemy, A is All but . (Wall, Me, You, Blank)
//* is move here next if you can - no safeties
const disrupt4 = [
["??b?", "?b.b", "b.*b", "?bb?"], //Pattern# Sphyxis - buy a turn #GREAT
["?bb?", "b..b", "b*Xb", "?bb?"], //Pattern# Sphyxis - buy a turn #GREAT
["?bb?", "b..b", "b.*b", "?bb?"], //Pattern# Sphyxis - buy a turn #GREAT
["??b?", "?b.b", "?b*b", "??O?"], //Pattern# Sphyxis - Sacrifice to kill an eye
["?bbb", "bb.b", "W.*b", "?oO?"], //Pattern# Sphyxis - 2x2 nook breatk
["?bbb", "bb.b", "W.*b", "?Oo?"], //Pattern# Sphyxis - 2x2 nook break
[".bbb", "o*.b", ".bbb", "????"], //Pattern# Sphyxis - Dangling 2 break
];
const disrupt5 = [
["?bbb?", "b.*.b", "?bbb?", "?????", "?????"], //Pattern# Sphyxis - Convert to 1 eye
["??OO?", "?b*.b", "?b..b", "??bb?", "?????"], //Pattern# Sphyxis - Buy time
["?????", "??bb?", "?b*Xb", "?boob", "??bb?"], //Pattern# Sphyxis - Buy time
["WWW??", "WWob?", "Wo*b?", "WWW??", "?????"], //Pattern# Sphyxis - 2x2 attack corner if possible
["??b??", "?b.b?", "?b*b?", "?b.A?", "??b??"], //Pattern# Sphyxis - Break two eyes into 1, buy a turn
["??b??", "?b.b?", "??*.b", "?b?b?", "?????"], //Pattern# Sphyxis - Break eyes, buy time
["?WWW?", "WoOoW", "WOO*W", "W???W", "?????"], //Block 3x3 corner
["?WWW?", "Wo*oW", "WOOOW", "W???W", "?????"], //Block 3x3 corner
];
const def5 = [
["?WW??", "WW.X?", "W.XX?", "WWW??", "?????"], //Pattern# Sphyxis - Eyes in a nook
["WWW??", "WW.X?", "W.*X?", "WWW??", "?????"], //Pattern# Sphyxis - 2x2 corner contain #GREAT
["BBB??", "BB.X?", "B..X?", "BBB??", "?????"], //Pattern# Sphyxis - 2x2 corner contain #GREAT
["?WWW?", "W.*.W", "WXXXW", "?????", "?????"], //Take the 3x3 back corner
];
// Testing
//const opponent = ["Slum Snakes", "Tetrads", "Daedalus", "Illuminati"]
//const opponent2 = ["????????????"]
// Original
const opponent = ["Netburners", "Slum Snakes", "The Black Hand", "Tetrads", "Daedalus", "Illuminati"];
const opponent2 = ["Netburners", "Slum Snakes", "The Black Hand", "Tetrads", "Daedalus", "Illuminati", "????????????"];
await start();
/** @param {NS} ns */
async function start() {
const runOptions = getConfiguration(ns, argsSchema);
if (!runOptions || (await instanceCount(ns)) > 1) return; // Prevent multiple instances of this script from being started, even with different args.
logtime = runOptions.logtime;
runOnce = runOptions.runOnce;
const sourceFiles = await getActiveSourceFiles(ns, true);
// Enable cheats if we have SF14.2 or higher (unless the user disabled cheats).
cheats = !runOptions['disable-cheats'] && (sourceFiles[14] ?? 0) >= 2;
cheatChanceThreshold = runOptions['cheat-chance-threshold'];
ns.disableLog("go.makeMove")
let ranToCompletion = false;
while (!ranToCompletion) {
try {
await playGo(ns);
ranToCompletion = true;
}
catch (err) {
log(ns, `WARNING: go.js Caught (and suppressed) an unexpected error:\n${getErrorInfo(err)}`, false, 'warning');
log(ns, `INFO: Will sleep for 10 seconds than try playing again.`, false);
await ns.sleep(10 * 1000);
}
}
}
// Ram-dodging helpers (Allows the script to only require as much RAM as its most expensive function)
/** @param {NS} ns @returns {Promise<string[]>} */
async function go_getBoardState(ns) {
return await getNsDataThroughFile(ns, `ns.go.getBoardState()`);
}
/** @param {NS} ns @returns {Promise<string[]>} */
async function go_analysis_getControlledEmptyNodes(ns) {
return await getNsDataThroughFile(ns, `ns.go.analysis.getControlledEmptyNodes()`);
}
/** @param {NS} ns @returns {Promise<boolean[][]>} */
async function go_analysis_getValidMoves(ns) {
return await getNsDataThroughFile(ns, `ns.go.analysis.getValidMoves()`);
}
/** @param {NS} ns @returns {Promise<number[][]>} */
async function go_analysis_getLiberties(ns) {
return await getNsDataThroughFile(ns, `ns.go.analysis.getLiberties()`);
}
/** @param {NS} ns @returns {Promise<number[][]>} */
async function go_analysis_getChains(ns) {
return await getNsDataThroughFile(ns, `ns.go.analysis.getChains()`);
}
/** @param {NS} ns @returns {Promise<number>} */
async function go_cheat_getCheatSuccessChance(ns) {
return await getNsDataThroughFile(ns, `ns.go.cheat.getCheatSuccessChance()`);
}
/** @param {NS} ns @param {number} x1 @param {number} y1 @param {number} x2 @param {number} y2
* @returns {Promise<{type: "move" | "pass" | "gameOver";x: number;y: number;}>} */
async function go_cheat_playTwoMoves(ns, x1, y1, x2, y2) {
return await getNsDataThroughFile(ns, `await ns.go.cheat.playTwoMoves(...ns.args)`, null, [x1, y1, x2, y2]);
}
/** @param {NS} ns @param {number} x1 @param {number} y1 @param {number} x2 @param {number} y2
* @returns {Promise<{type: "move" | "pass" | "gameOver";x: number;y: number;}>} */
async function go_makeMove(ns, x, y) {
return await ns.go.makeMove(x, y);
//return await getNsDataThroughFile(ns, `await ns.go.makeMove(...ns.args)`, null, [x, y]);
}
/** @param {NS} ns */
async function playGo(ns) {
const startBoard = await go_getBoardState(ns)
let inProgress = false
turn = 0
START = performance.now()
//If we have already moved, jump the turn to 3 to get out of Opening Moves
for (let x = 0; x < startBoard[0].length; x++) {
for (let y = 0; y < startBoard[0].length; y++) {
if (startBoard[x][y] === "X") {
inProgress = true
turn = 3
break
}
}
if (inProgress) break
}
const currentGame = await ns.go.opponentNextTurn(false)
checkNewGame(ns, currentGame)
const playStyle = getStyle(ns);
while (true) {
turn++
board = await go_getBoardState(ns);
contested = await go_analysis_getControlledEmptyNodes(ns);
validMove = await go_analysis_getValidMoves(ns);
validLibMoves = await go_analysis_getLiberties(ns);
chains = await go_analysis_getChains(ns);
const size = board[0].length
//Build a test board with walls
let testWall = "W".repeat(size + 2);
testBoard = [];
testBoard.push(testWall);
for (const b of board)
testBoard.push("W" + b + "W");
testBoard.push(testWall);
//We have our test board
let results;
if (turn < 3)
results = await movePiece(ns, getOpeningMove(ns))
if (turn >= 3) {
switch (playStyle) {
case 0: //Netburners
if (results = await movePiece(ns, getRandomCounterLib())) break
if (results = await movePiece(ns, getRandomLibAttack(88))) break
if (results = await movePiece(ns, getRandomLibDefend())) break
if (results = await moveSnakeEyes(ns, getSnakeEyes(6))) break
if (results = await movePiece(ns, getAggroAttack(2, 2, 2))) break
if (results = await movePiece(ns, disruptEyes())) break
if (results = await movePiece(ns, getDefPattern())) break
if (results = await movePiece(ns, getAggroAttack(3, 3, 3, 1, 6))) break
if (results = await movePiece(ns, getRandomBolster(2, 1))) break
if (results = await movePiece(ns, getAggroAttack(4, 7, 3, 1, 6))) break
if (results = await movePiece(ns, attackGrowDragon(1))) break
if (results = await movePiece(ns, getDefAttack(8, 20, 2))) break
if (results = await movePiece(ns, getRandomExpand())) break
if (results = await movePiece(ns, getRandomBolster(2, 1, false, 1))) break
if (results = await movePiece(ns, getRandomLibAttack())) break
if (results = await movePiece(ns, getRandomStrat())) break
ns.print("Turn Passed")
results = await ns.go.passTurn()
break
case 1: //The Black Hand
if (results = await movePiece(ns, getRandomCounterLib())) break
if (results = await movePiece(ns, getRandomLibAttack(88))) break
if (results = await movePiece(ns, getRandomLibDefend())) break
if (results = await moveSnakeEyes(ns, getSnakeEyes(6))) break
if (results = await movePiece(ns, getAggroAttack(2, 2, 2))) break
if (results = await movePiece(ns, disruptEyes())) break
if (results = await movePiece(ns, getDefPattern())) break
if (results = await movePiece(ns, getAggroAttack(3, 3, 3, 1, 6))) break
if (results = await movePiece(ns, getRandomBolster(2, 1))) break
if (results = await movePiece(ns, getAggroAttack(4, 7, 3, 1, 6))) break
if (results = await movePiece(ns, attackGrowDragon(1))) break
if (results = await movePiece(ns, getRandomExpand())) break
if (results = await movePiece(ns, getRandomBolster(2, 1, false, 1))) break
if (results = await movePiece(ns, getRandomLibAttack())) break
if (results = await movePiece(ns, getRandomStrat())) break
ns.print("Turn Passed")
results = await ns.go.passTurn()
break
case 2: //Mr. Mustacio - Slum Snakes
if (results = await movePiece(ns, getRandomCounterLib())) break
if (results = await movePiece(ns, getRandomLibAttack(88))) break
if (results = await movePiece(ns, getRandomLibDefend())) break
if (results = await moveSnakeEyes(ns, getSnakeEyes(6))) break
if (results = await movePiece(ns, getAggroAttack(2, 2, 2))) break
if (results = await movePiece(ns, disruptEyes())) break
if (results = await movePiece(ns, getDefPattern())) break
if (results = await movePiece(ns, getAggroAttack(3, 3, 3, 1, 6))) break
if (results = await movePiece(ns, getRandomBolster(2, 1))) break
if (results = await movePiece(ns, getDefAttack(4, 7, 3, 1, 6))) break
if (results = await movePiece(ns, attackGrowDragon(1))) break
if (results = await movePiece(ns, getRandomExpand())) break
if (results = await movePiece(ns, getRandomBolster(2, 1, false, 1))) break
if (results = await movePiece(ns, getRandomLibAttack())) break
if (results = await movePiece(ns, getRandomStrat())) break
ns.print("Turn Passed")
results = await ns.go.passTurn()
break
case 3: //Daedalus
if (results = await movePiece(ns, getRandomCounterLib())) break
if (results = await movePiece(ns, getRandomLibAttack(88))) break
if (results = await movePiece(ns, getRandomLibDefend())) break
if (results = await moveSnakeEyes(ns, getSnakeEyes(6))) break
if (results = await movePiece(ns, getAggroAttack(2, 2, 2))) break
if (results = await movePiece(ns, disruptEyes())) break
if (results = await movePiece(ns, getDefPattern())) break
if (results = await movePiece(ns, getAggroAttack(3, 4, 3, 1, 6))) break
if (results = await movePiece(ns, getRandomBolster(2, 1))) break
if (results = await movePiece(ns, getDefAttack(5, 7, 3, 2, 6))) break
if (results = await movePiece(ns, attackGrowDragon(1))) break
if (results = await movePiece(ns, getRandomExpand())) break
if (results = await movePiece(ns, getRandomBolster(2, 1, false, 1))) break
if (results = await movePiece(ns, getRandomLibAttack())) break
if (results = await movePiece(ns, getRandomStrat())) break
ns.print("Turn Passed")
results = await ns.go.passTurn()
break
case 4: //Tetrads
if (results = await movePiece(ns, getRandomCounterLib())) break
if (results = await movePiece(ns, getRandomLibAttack(88))) break
if (results = await movePiece(ns, getRandomLibDefend())) break
if (results = await moveSnakeEyes(ns, getSnakeEyes(6))) break
if (results = await movePiece(ns, getAggroAttack(2, 2, 2))) break
if (results = await movePiece(ns, disruptEyes())) break
if (results = await movePiece(ns, getDefPattern())) break
if (results = await movePiece(ns, getAggroAttack(3, 4, 3))) break
if (results = await movePiece(ns, getRandomBolster(2, 1))) break
if (results = await movePiece(ns, getAggroAttack(5, 7, 3))) break
if (results = await movePiece(ns, attackGrowDragon(1))) break
if (results = await movePiece(ns, getRandomExpand())) break
if (results = await movePiece(ns, getRandomBolster(2, 1, false))) break
if (results = await movePiece(ns, getRandomLibAttack())) break
if (results = await movePiece(ns, getRandomStrat(),)) break
ns.print("Turn Passed")
results = await ns.go.passTurn()
break
case 5: //Illum
if (results = await movePiece(ns, getRandomCounterLib())) break
if (results = await movePiece(ns, getRandomLibAttack(88))) break
if (results = await movePiece(ns, getRandomLibDefend())) break
if (results = await moveSnakeEyes(ns, getSnakeEyes(6))) break
if (results = await movePiece(ns, getAggroAttack(2, 2, 2))) break
if (results = await movePiece(ns, disruptEyes())) break
if (results = await movePiece(ns, getDefPattern())) break
if (results = await movePiece(ns, getAggroAttack(3, 4, 3))) break
if (results = await movePiece(ns, getRandomBolster(2, 1))) break
if (results = await movePiece(ns, attackGrowDragon(1))) break
if (results = await movePiece(ns, getRandomExpand())) break
if (results = await movePiece(ns, getRandomBolster(2, 1, false))) break
if (results = await movePiece(ns, getRandomLibAttack())) break
if (results = await movePiece(ns, getRandomStrat())) break
ns.print("Turn Passed")
results = await ns.go.passTurn()
break
case 6: //??????
if (results = await movePiece(ns, getRandomCounterLib())) break
if (results = await movePiece(ns, getRandomLibAttack(88))) break
if (results = await movePiece(ns, getRandomLibDefend())) break
if (results = await moveSnakeEyes(ns, getSnakeEyes(6))) break
if (results = await movePiece(ns, getAggroAttack(2, 2, 2))) break
if (results = await movePiece(ns, disruptEyes())) break
if (results = await movePiece(ns, getDefPattern())) break
if (results = await movePiece(ns, getAggroAttack(3, 4, 3))) break
if (results = await movePiece(ns, getRandomBolster(2, 1))) break
if (results = await movePiece(ns, getDefAttack(5, 7, 3))) break
if (results = await movePiece(ns, attackGrowDragon(1))) break
if (results = await movePiece(ns, getRandomExpand())) break
if (results = await movePiece(ns, getRandomBolster(2, 1, false))) break
if (results = await movePiece(ns, getRandomLibAttack())) break
if (results = await movePiece(ns, getRandomStrat())) break
ns.print("Turn Passed")
results = await ns.go.passTurn()
break
} //End of style switch
} // end of turn >= 3
checkNewGame(ns, results)
}
}
/** @param {NS} ns */
function getStyle(ns) {
switch (ns.go.getOpponent()) {
case "Netburners": return 0;
case "The Black Hand": return 1;
case "Slum Snakes": return 2;
case "Daedalus": return 3;
case "Tetrads": return 4;
case "Illuminati": return 5;
default: return 6;
}
}
/** @param {NS} ns
* @param {{ type:"move"|"pass"|"gameOver"; x:number; y:number;}} gameInfo
*/
function checkNewGame(ns, gameInfo) {
if (gameInfo.type === "gameOver") {
if (runOnce) ns.exit()
try { ns.go.resetBoardState(opponent2[Math.floor(Math.random() * opponent2.length)], 13) }
catch { ns.go.resetBoardState(opponent[Math.floor(Math.random() * opponent.length)], 13) }
turn = 0
ns.clearLog()
}
}
/** @param {NS} ns
* @param {number} x
* @param {number} y
* @param {string[]} pattern
* @returns {boolean}
*/
function isPattern(x, y, pattern) {
//Move the pattern around with x/y loops, check if pattern matches IF a move is placed
//We can assume that x and y are valid moves
const size = testBoard[0].length
const patterns = getAllPatterns(pattern)
const patternSize = pattern.length
for (const patternCheck of patterns) {
//cx and cy - the spots of the pattern we are checking against the test board
//For, say a 3x3 pattern, we do a grid of 0,0 -> 2, 2
for (let cx = ((patternSize - 1) * -1); cx <= 0; cx++) { // We've added a wall around everything, so 0 is a wall
if (cx + x + 1 < 0 || cx + x + 1 > size - 1) continue
for (let cy = ((patternSize - 1) * -1); cy <= 0 - 1; cy++) {
//We now have a cycle that will check each section of the grid against the pattern
//Safety checks: We know 0,0 is safe, we were sent it, but each other section could be bad
if (cy + y + 1 < 0 || cy + y + 1 > size - 1) continue
let count = 0
let abort = false
for (let px = 0; px < patternSize && !abort; px++) {
if (x + cx + px + 1 < 0 || x + cx + px + 1 >= size) { //Don't go off grid
abort = true
break
}
for (let py = 0; py < patternSize && !abort; py++) {
if (y + cy + py + 1 < 0 || y + cy + py + 1 >= size) { //Are we off the map?
abort = true
break
}
if (cx + px === 0 && cy + py === 0 && !["X", "*"].includes(patternCheck[px][py])) {
abort = true
break
}
if (cx + px === 0 && cy + py === 0 && ["X"].includes(contested[x][y]) && patternCheck[px][py] !== "*") {
abort = true
break
}
//We now have a cycles for each spot in the pattern
//0,0 -> 2,2 for a 3x3
switch (patternCheck[px][py]) {
case "X":
if (testBoard[cx + x + 1 + px][cy + y + 1 + py] === "X" || (cx + px === 0 && cy + py === 0 && testBoard[cx + x + 1 + px][cy + y + 1 + py] === ".")) {
count++
}
else if (cx + px === 0 && cy + py === 0) {
count++ // Our placement piece
}
else abort = true
break
case "*": // Special case. We move here next or break the test
if (testBoard[cx + x + 1 + px][cy + y + 1 + py] === "." && cx + px === 0 && cy + py === 0) {
count++
}
else abort = true
break
case "O":
if (testBoard[cx + x + 1 + px][cy + y + 1 + py] === "O")
count++
else abort = true
break
case "x":
if (["X", "."].includes(testBoard[cx + x + 1 + px][cy + y + 1 + py]))
count++
else abort = true
break
case "o":
if (["O", "."].includes(testBoard[cx + x + 1 + px][cy + y + 1 + py]))
count++
else abort = true
break
case "?":
count++
break
case ".":
if (testBoard[cx + x + 1 + px][cy + y + 1 + py] === ".")
count++
else abort = true
break
case "W":
if (["W", "#"].includes(testBoard[cx + x + 1 + px][cy + y + 1 + py]))
count++
else abort = true
break
case "B":
if (["W", "#", "X"].includes(testBoard[cx + x + 1 + px][cy + y + 1 + py]))
count++
else abort = true
break
case "b":
if (["W", "#", "O"].includes(testBoard[cx + x + 1 + px][cy + y + 1 + py]))
count++
else abort = true
break
case "A":
if (["W", "#", "X", "O"].includes(testBoard[cx + x + 1 + px][cy + y + 1 + py]))
count++
else abort = true
break
}
if (count === patternSize * patternSize) return true
}
}
}
}
}
return false
}
/** @param {NS} ns
* @param {string[]} pattern
* @returns {string[][]} */
function getAllPatterns(pattern) {
const rotations = [
pattern,
rotate90Degrees(pattern),
rotate90Degrees(rotate90Degrees(pattern)),
rotate90Degrees(rotate90Degrees(rotate90Degrees(pattern))),
]
return [...rotations, ...rotations.map(verticalMirror)]
}
//Special thanks to @gmcew for the next 2 functions!
/** @param {NS} ns
* @param {string[]} pattern
* @returns {string[]} */
function rotate90Degrees(pattern) {
return pattern.map((val, index) => pattern.map(row => row[index]).reverse().join(""))
}
/** @param {NS} ns
* @param {string[]} pattern
* @returns {string[]} */
function verticalMirror(pattern) {
return pattern.toReversed();
}
/** @param {NS} ns
* @returns {{coords: number[]; msg: string;}} */
function getSnakeEyes(minKilled = 5) {
if (!cheats) return []
const moveOptions = []
const size = board[0].length
let highValue = 1
const checked = new Set
for (let x = 0; x < size - 1; x++)
for (let y = 0; y < size - 1; y++) {
if (contested[x][y] === "X" || board[x][y] !== "O" || validLibMoves[x][y] !== 2 || checked.has(JSON.stringify([x, y]))) continue
//Is it the enemy, with 2 libs (we can kill) and we have not checked this spot and the chain is large enough
const chain = getChainValue(x, y, "O")
if (chain < minKilled) continue
//We have a winner! Check all it's spots and find the 2 killing blows. Add the checked spots to the checked list so we don't recheck
checked.add(JSON.stringify([x, y]))
const enemySearch = new Set
const move1 = []
const move2 = []
enemySearch.add(JSON.stringify([x, y]))
for (const explore of enemySearch) {
const [fx, fy] = JSON.parse(explore)
//Find your eyes
if (board[fx][fy] === ".") {
move1.length ? move2.push([fx, fy]) : move1.push([fx, fy])
checked.add(JSON.stringify([fx, fy]))
continue
}
//Find more of yourself to search...
if (fx < size - 1 && ["O", "."].includes(board[fx + 1][fy])) {
enemySearch.add(JSON.stringify([fx + 1, fy]))
checked.add(JSON.stringify([fx, fy]))
}
if (fx > 0 && ["O", "."].includes(board[fx - 1][fy])) {
enemySearch.add(JSON.stringify([fx - 1, fy]))
checked.add(JSON.stringify([fx, fy]))
}
if (fy > 0 && ["O", "."].includes(board[fx][fy - 1])) {
enemySearch.add(JSON.stringify([fx, fy - 1]))
checked.add(JSON.stringify([fx, fy]))
}
if (fy < size - 1 && ["O", "."].includes(board[fx][fy + 1])) {
enemySearch.add(JSON.stringify([fx, fy + 1]))
checked.add(JSON.stringify([fx, fy]))
}
} // End of searching the enemy
if (chain > highValue) {
highValue = chain
moveOptions.length = 0
const mv1 = move1.pop()
const mv2 = move2.pop()
moveOptions.push([mv1[0], mv1[1], mv2[0], mv2[1]])
}
else if (chain === highValue) {
const mv1 = move1.pop()
const mv2 = move2.pop()
moveOptions.push([mv1[0], mv1[1], mv2[0], mv2[1]])
}
} // Search whole board
// Choose one of the found moves at random
const randomIndex = Math.floor(Math.random() * moveOptions.length)
return moveOptions[randomIndex] ? {
coords: moveOptions[randomIndex],
msg: "SnakeEyes Cheat"
} : []
}
/** @param {NS} ns
* @returns {{coords: number[]; msg: string;}} */
function getRandomLibAttack(minKilled = 1) {
const moveOptions = []
const size = board[0].length
let highValue = 1
// Look through all the points on the board
const moves = getAllValidMoves(true)
for (const [x, y] of moves) {
if (contested[x][y] === "X" || validLibMoves[x][y] !== -1) continue
let count = 0
let chains = 0
//We are only checking up, down, left and right
if (x > 0 && board[x - 1][y] === "O" && validLibMoves[x - 1][y] === 1) {
count++
chains += getChainValue(x - 1, y, "O")
}
if (x < size - 1 && board[x + 1][y] === "O" && validLibMoves[x + 1][y] === 1) {
count++
chains += getChainValue(x + 1, y, "O")
}
if (y > 0 && board[x][y - 1] === "O" && validLibMoves[x][y - 1] === 1) {
count++
chains += getChainValue(x, y - 1, "O")
}
if (y < size - 1 && board[x][y + 1] === "O" && validLibMoves[x][y + 1] === 1) {
count++
chains += getChainValue(x, y + 1, "O")
}
const enemyLibs = getSurroundLibs(x, y, "O")
if (count === 0 || (chains < minKilled && enemyLibs <= 1)) continue
const result = count * chains
if (result > highValue) {
moveOptions.length = 0
moveOptions.push([x, y])
highValue = result
}
else if (result === highValue) moveOptions.push([x, y]);
}
// Choose one of the found moves at random
const randomIndex = Math.floor(Math.random() * moveOptions.length)
return moveOptions[randomIndex] ? {
coords: moveOptions[randomIndex],
msg: "Lib Attack"
} : []
}
/** @param {NS} ns
* @returns {{coords: number[]; msg: string;}} */
function getRandomLibDefend(savedMin = 1) {
const moveOptions = []
const size = board[0].length
let highValue = 0
// Look through all the points on the board
const moves = getAllValidMoves()
for (const [x, y] of moves) {
const surround = getSurroundLibs(x, y, "X")
const myEyes = getEyeValue(x, y, "X")
if (surround + myEyes < 2) continue //Abort. Let it go, let it go...
if (validLibMoves[x][y] === -1) {
let count = 0
//We are only checking up, down, left and right
if (x > 0 && validLibMoves[x - 1][y] === 1 && board[x - 1][y] === "X") count += getChainValue(x - 1, y, "X")
if (x < size - 1 && validLibMoves[x + 1][y] === 1 && board[x + 1][y] === "X") count += getChainValue(x + 1, y, "X")
if (y > 0 && validLibMoves[x][y - 1] === 1 && board[x][y - 1] === "X") count += getChainValue(x, y - 1, "X")
if (y < size - 1 && validLibMoves[x][y + 1] === 1 && board[x][y + 1] === "X") count += getChainValue(x, y + 1, "X")
if (count === 0 || count < savedMin) continue
//Just HOW effective will this move be? Counter attack if we can.
count *= surround
if (count > highValue) {
moveOptions.length = 0
moveOptions.push([x, y])
highValue = count
}
else if (count === highValue) moveOptions.push([x, y])
}
}
// Choose one of the found moves at random
const randomIndex = Math.floor(Math.random() * moveOptions.length)
return moveOptions[randomIndex] ? {
coords: moveOptions[randomIndex],
msg: "Lib Defend"
} : []
}
/** @param {NS} ns
* @returns {{coords: number[]; msg: string;}} */
function getRandomCounterLib() {
//Advanced strategy
//If we have a chain that's going to die, and a hanging lib attached to it
//Find that hanging lib and kill it to save the chain
const size = board[0].length
// Look through all the points on the board
const moves = getAllValidMoves()
const movesAvailable = new Set //Contains the empty squares that we are looking to see if we should take
const friendlyToCheckForOpp = new Set
for (const [x, y] of moves) {
//We are checking up, down, left and right first
if (x > 0 && validLibMoves[x - 1][y] === 1 && board[x - 1][y] === "X") {
movesAvailable.add(JSON.stringify([x, y]))
friendlyToCheckForOpp.add(JSON.stringify([x - 1, y]))
}
if (x < size - 1 && validLibMoves[x + 1][y] === 1 && board[x + 1][y] === "X") {
movesAvailable.add(JSON.stringify([x, y]))
friendlyToCheckForOpp.add(JSON.stringify([x + 1, y]))
}
if (y > 0 && validLibMoves[x][y - 1] === 1 && board[x][y - 1] === "X") {
movesAvailable.add(JSON.stringify([x, y]))
friendlyToCheckForOpp.add(JSON.stringify([x, y - 1]))
}
if (y < size - 1 && validLibMoves[x][y + 1] === 1 && board[x][y + 1] === "X") {
movesAvailable.add(JSON.stringify([x, y]))
friendlyToCheckForOpp.add(JSON.stringify([x, y + 1]))
}
}
//Shortcut. While there's 1, is it THE one?
//We know that 1 side of this is a friendly with 1 lib at risk. Is another side the enemy?
for (const explore of movesAvailable) {
const [fx, fy] = JSON.parse(explore)
if (!validMove[fx][fy]) continue
if (fx < size - 1 && board[fx + 1][fy] === "O" && validLibMoves[fx + 1][fy] === 1) {
return {
coords: [fx, fy],
msg: "Counter Lib Attack - Fist of the east"
}
}
if (fx > 0 && board[fx - 1][fy] === "O" && validLibMoves[fx - 1][fy] === 1) {
return {
coords: [fx, fy],
msg: "Counter Lib Attack - Fist of the west"
}
}
if (fy > 0 && board[fx][fy - 1] === "O" && validLibMoves[fx][fy - 1] === 1) {
return {
coords: [fx, fy],
msg: "Counter Lib Attack - Fist of the south"
}
}
if (fy < size - 1 && board[fx][fy + 1] === "O" && validLibMoves[fx][fy + 1] === 1) {
return {
coords: [fx, fy],
msg: "Counter Lib Attack - Fist of the north"
}
}
}
const enemiesToSearch = new Set
//We have our empty chain. Look through him to find adjoining O's that can be killed and other friendies
for (const explore of friendlyToCheckForOpp) {
const [fx, fy] = JSON.parse(explore)
if (fx < size - 1 && board[fx + 1][fy] === "O" && validLibMoves[fx + 1][fy] === 1) enemiesToSearch.add(JSON.stringify([fx + 1, fy]))
if (fx > 0 && board[fx - 1][fy] === "O" && validLibMoves[fx - 1][fy] === 1) enemiesToSearch.add(JSON.stringify([fx - 1, fy]))
if (fy > 0 && board[fx][fy - 1] === "O" && validLibMoves[fx][fy - 1] === 1) enemiesToSearch.add(JSON.stringify([fx, fy - 1]))
if (fy < size - 1 && board[fx][fy + 1] === "O" && validLibMoves[fx][fy + 1] === 1) enemiesToSearch.add(JSON.stringify([fx, fy + 1]))
if (fx < size - 1 && ["X"].includes(board[fx + 1][fy])) friendlyToCheckForOpp.add(JSON.stringify([fx + 1, fy]))
if (fx > 0 && ["X"].includes(board[fx - 1][fy])) friendlyToCheckForOpp.add(JSON.stringify([fx - 1, fy]))
if (fy > 0 && ["X"].includes(board[fx][fy - 1])) friendlyToCheckForOpp.add(JSON.stringify([fx, fy - 1]))
if (fy < size - 1 && ["X"].includes(board[fx][fy + 1])) friendlyToCheckForOpp.add(JSON.stringify([fx, fy + 1]))
}
for (const explore of enemiesToSearch) {
const [fx, fy] = JSON.parse(explore)
if (fx < size - 1 && board[fx + 1][fy] === "O") enemiesToSearch.add(JSON.stringify([fx + 1, fy]))
if (fx > 0 && board[fx - 1][fy] === "O") enemiesToSearch.add(JSON.stringify([fx - 1, fy]))
if (fy > 0 && board[fx][fy - 1] === "O") enemiesToSearch.add(JSON.stringify([fx, fy - 1]))
if (fy < size - 1 && board[fx][fy + 1] === "O") enemiesToSearch.add(JSON.stringify([fx, fy + 1]))
if (fx < size - 1 && board[fx + 1][fy] === "." && validMove[fx + 1][fy]) {
return {
coords: [fx + 1, fy],
msg: "Counter Lib Attack - The wind blows"
}
}
if (fx > 0 && board[fx - 1][fy] === "." && validMove[fx - 1][fy]) {
return {
coords: [fx - 1, fy],
msg: "Counter Lib Attack - The earth grows"
}
}
if (fy > 0 && board[fx][fy - 1] === "." && validMove[fx][fy - 1]) {
return {
coords: [fx, fy - 1],
msg: "Counter Lib Attack - The fire burns"
}
}
if (fy < size - 1 && board[fx][fy + 1] === "." && validMove[fx][fy + 1]) {
return {
coords: [fx, fy + 1],
msg: "Counter Lib Attack - The water flows"
}
}
}
return []
}
/** @param {NS} ns
* @returns {{coords: number[]; msg: string;}} */
function getRandomExpand() {
const moveOptions = []
const size = board[0].length;
let highValue = 0
// Look through all the points on the board
const moves = getAllValidMoves(true)
for (const [x, y] of moves) {
const surroundLibs = getSurroundLibs(x, y, "X")
const enemySurroundLibs = getSurroundLibs(x, y, "O")
if (contested[x][y] !== "?" || surroundLibs <= 2 || createsLib(x, y, "X") || enemySurroundLibs <= 1) continue
let count = 0
//We are only checking up, down, left and right. Don't expand if you're surrounded by friendlies
if (x > 0 && board[x - 1][y] === "X") count++
if (x < size - 1 && board[x + 1][y] === "X") count++
if (y > 0 && board[x][y - 1] === "X") count++
if (y < size - 1 && board[x][y + 1] === "X") count++
if (count >= 3 || count <= 0) continue
const surroundSpace = getSurroundSpaceFull(x, y) + 1
const enemySurroundChains = getChainAttack(x, y) + 1
const myEyes = getEyeValueFull(x, y, "X") + 1
const enemies = getSurroundEnemiesFull(x, y) + 1
const freeSpace = getFreeSpace(x, y)
const rank = myEyes * enemySurroundLibs * enemies * enemySurroundChains * freeSpace * surroundSpace
if (rank > highValue) {
moveOptions.length = 0
moveOptions.push([x, y])
highValue = rank
}
else if (rank === highValue) moveOptions.push([x, y]);
}
// Choose one of the found moves at random
const randomIndex = Math.floor(Math.random() * moveOptions.length)
return moveOptions[randomIndex] ? {
coords: moveOptions[randomIndex],
msg: "Expansion"
} : []
}
/** @param {NS} ns
* @returns {{coords: number[]; msg: string;}} */
function getRandomBolster(libRequired, savedNodesMin, onlyContested = true) {
const moveOptions = [];
const size = board[0].length;
let highValue = 1
// Look through all the points on the board
const moves = getAllValidMoves()
for (const [x, y] of moves) {
if ((onlyContested && contested[x][y] !== "?") || createsLib(x, y, "X")) continue
let right = 0
let left = 0
let up = 0
let down = 0
//We are only checking up, down, left and right
//We are checking for linking chains of friendlies, filtering out those already checked
let checkedChains = []
if (x < size - 1 && board[x + 1][y] === "X" && validLibMoves[x + 1][y] === libRequired) {
right = getChainValue(x + 1, y, "X")
checkedChains.push(chains[x + 1][y])
}
if (x > 0 && board[x - 1][y] === "X" && !checkedChains.includes(chains[x - 1][y]) && validLibMoves[x - 1][y] === libRequired) {
left = getChainValue(x - 1, y, "X")
checkedChains.push(chains[x - 1][y])
}
if (y < size - 1 && board[x][y + 1] === "X" && !checkedChains.includes(chains[x][y + 1]) && validLibMoves[x][y + 1] === libRequired) {
up = getChainValue(x, y + 1, "X")
checkedChains.push(chains[x][y + 1])
}
if (y > 0 && board[x][y - 1] === "X" && !checkedChains.includes(chains[x][y - 1]) && validLibMoves[x][y - 1] === libRequired)
down = getChainValue(x, y - 1, "X")
let count = 0
let total = 0
if (right >= savedNodesMin) {
count++
total += right
}
if (left >= savedNodesMin) {
count++
total += left
}
if (up >= savedNodesMin) {
count++
total += up
}
if (down >= savedNodesMin) {
count++
total += down
}
if (count <= 0) continue
const surroundMulti = getSurroundLibSpread(x, y, "X")
const rank = total * count * surroundMulti
if (rank > highValue) {
moveOptions.length = 0
moveOptions.push([x, y])
highValue = rank
}
else if (rank === highValue) moveOptions.push([x, y]);
}
// Choose one of the found moves at random
const randomIndex = Math.floor(Math.random() * moveOptions.length)
return moveOptions[randomIndex] ? {
coords: moveOptions[randomIndex],
msg: "Bolster - Libs: " + libRequired + " Nodes: " + savedNodesMin + " OnlyContested: " + onlyContested
} : []
}
/** @param {NS} ns
* @returns {number} */
function getChainValue(checkx, checky, player) {
const size = board[0].length
const otherPlayer = player === "X" ? "O" : "X"
const explored = new Set()
if (contested[checkx][checky] === "?" || board[checkx][checky] === otherPlayer) return 0
if (checkx < size - 1) explored.add(JSON.stringify([checkx + 1, checky]))
if (checkx > 0) explored.add(JSON.stringify([checkx - 1, checky]))
if (checky > 0) explored.add(JSON.stringify([checkx, checky - 1]))
if (checky < size - 1) explored.add(JSON.stringify([checkx, checky + 1]))
let count = 1
for (const explore of explored) {
const [x, y] = JSON.parse(explore)
if (contested[x][y] === "?" || contested[x][y] === "#" || board[x][y] === otherPlayer) continue
count++
if (x < size - 1) explored.add(JSON.stringify([x + 1, y]))
if (x > 0) explored.add(JSON.stringify([x - 1, y]))
if (y > 0) explored.add(JSON.stringify([x, y - 1]))
if (y < size - 1) explored.add(JSON.stringify([x, y + 1]))
}
return count
}
/** @param {NS} ns
* @returns {number} */
function getEyeValue(checkx, checky, player) {
const size = board[0].length
const otherPlayer = player === "X" ? "O" : "X"
const explored = new Set()
if (checkx < size - 1) explored.add(JSON.stringify([checkx + 1, checky]))
if (checkx > 0) explored.add(JSON.stringify([checkx - 1, checky]))
if (checky > 0) explored.add(JSON.stringify([checkx, checky - 1]))
if (checky < size - 1) explored.add(JSON.stringify([checkx, checky + 1]))
let count = 0
for (const explore of explored) {
const [x, y] = JSON.parse(explore)
if (contested[x][y] === "?" || contested[x][y] === "#" || board[x][y] === otherPlayer) continue
if (contested[x][y] === player) count++
if (x < size - 1) explored.add(JSON.stringify([x + 1, y]))
if (x > 0) explored.add(JSON.stringify([x - 1, y]))
if (y > 0) explored.add(JSON.stringify([x, y - 1]))
if (y < size - 1) explored.add(JSON.stringify([x, y + 1]))
}
return count
}
/** @param {NS} ns
* @returns {number} */
function getFreeSpace(checkx, checky) {
const size = board[0].length
if (contested[checkx][checky] !== "?") return 0
const explored = new Set()
if (checkx < size - 1) explored.add(JSON.stringify([checkx + 1, checky]))
if (checkx > 0) explored.add(JSON.stringify([checkx - 1, checky]))
if (checky > 0) explored.add(JSON.stringify([checkx, checky - 1]))
if (checky < size - 1) explored.add(JSON.stringify([checkx, checky + 1]))
let count = 1
for (const explore of explored) {
const [x, y] = JSON.parse(explore)
if (["#", "X", "O"].includes(contested[x][y])) continue
if (contested[x][y] === "?") count++
if (x < size - 1) explored.add(JSON.stringify([x + 1, y]))
if (x > 0) explored.add(JSON.stringify([x - 1, y]))
if (y > 0) explored.add(JSON.stringify([x, y - 1]))
if (y < size - 1) explored.add(JSON.stringify([x, y + 1]))
}
return count
}
/** @param {NS} ns
* @returns {number} */
function getEyeValueFull(checkx, checky, player) {
const size = board[0].length
const otherPlayer = player === "X" ? "O" : "X"
const explored = new Set()
if (checkx < size - 1) explored.add(JSON.stringify([checkx + 1, checky]))
if (checkx > 0) explored.add(JSON.stringify([checkx - 1, checky]))
if (checky > 0) explored.add(JSON.stringify([checkx, checky - 1]))
if (checky < size - 1) explored.add(JSON.stringify([checkx, checky + 1]))
if (checkx < size - 1 && checky < size - 1) explored.add(JSON.stringify([checkx + 1, checky + 1]))
if (checkx > 0 && checky < size - 1) explored.add(JSON.stringify([checkx - 1, checky + 1]))
if (checkx < size - 1 && checky > 0) explored.add(JSON.stringify([checkx + 1, checky - 1]))
if (checkx > 0 && checky > 0) explored.add(JSON.stringify([checkx - 1, checky - 1]))
let count = 0
for (const explore of explored) {
const [x, y] = JSON.parse(explore)
if (contested[x][y] === "?" || contested[x][y] === "#" || board[x][y] === otherPlayer) continue
if (contested[x][y] === player) count++
if (x < size - 1) explored.add(JSON.stringify([x + 1, y]))
if (x > 0) explored.add(JSON.stringify([x - 1, y]))
if (y > 0) explored.add(JSON.stringify([x, y - 1]))
if (y < size - 1) explored.add(JSON.stringify([x, y + 1]))
}
return count
}
/** @param {NS} ns
* @returns {number} */
function getChainAttack(x, y) {
const size = board[0].length
let count = 0
if (x > 0 && board[x - 1][y] === "O") count += getChainValue(x - 1, y, "O")
if (x < size - 1 && board[x + 1][y] === "O") count += getChainValue(x + 1, y, "O")
if (y > 0 && board[x][y - 1] === "O") count += getChainValue(x, y - 1, "O")
if (y < size - 1 && board[x][y + 1] === "O") count += getChainValue(x, y + 1, "O")
return count
}
/** @param {NS} ns
* @returns {number} */
function getChainAttackFull(x, y) {
const size = board[0].length
let count = 0
if (x < size - 1) count += getChainValue(x + 1, y, "O")
if (x > 0) count += getChainValue(x - 1, y, "O")
if (y > 0) count += getChainValue(x, y - 1, "O")
if (y < size - 1) count += getChainValue(x, y + 1, "O")
if (x < size - 1 && y < size - 1) count += getChainValue(x + 1, y + 1, "O")
if (x > 0 && y < size - 1) count += getChainValue(x - 1, y + 1, "O")
if (x < size - 1 && y > 0) count += getChainValue(x + 1, y - 1, "O")
if (x > 0 && y > 0) count += getChainValue(x - 1, y - 1, "O")
return count
}
/** @param {NS} ns