-
Notifications
You must be signed in to change notification settings - Fork 24
/
acas.user.js
2528 lines (1894 loc) · 75.7 KB
/
acas.user.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
// ==UserScript==
// @name 🏆 [#1 Chess Cheat] A.C.A.S (Advanced Chess Assistance System)
// @name:en 🏆 [#1 Chess Cheat] A.C.A.S (Advanced Chess Assistance System)
// @name:fi 🏆 [#1 Chess Cheat] A.C.A.S (Edistynyt shakkiavustusjärjestelmä)
// @name:sw 🏆 [#1 Chess Cheat] A.C.A.S (Advanserad Schack Assitant System)
// @name:zh-CN 🏆 [#1 Chess Cheat] A.C.A.S(高级国际象棋辅助系统)
// @name:es 🏆 [#1 Chess Cheat] A.C.A.S (Sistema Avanzado de Asistencia al Ajedrez)
// @name:hi 🏆 [#1 Chess Cheat] A.C.A.S (उन्नत शतरंज सहायता प्रणाली)
// @name:ar 🏆 [#1 Chess Cheat] A.C.A.S (نظام المساعدة المتقدم في الشطرنج)
// @name:pt 🏆 [#1 Chess Cheat] A.C.A.S (Sistema Avançado de Assistência ao Xadrez)
// @name:ja 🏆 [#1 Chess Cheat] A.C.A.S(先進的なチェス支援システム)
// @name:de 🏆 [#1 Chess Cheat] A.C.A.S (Fortgeschrittenes Schach-Hilfesystem)
// @name:fr 🏆 [#1 Chess Cheat] A.C.A.S (Système Avancé d'Assistance aux Échecs)
// @name:it 🏆 [#1 Chess Cheat] A.C.A.S (Sistema Avanzato di Assistenza agli Scacchi)
// @name:ko 🏆 [#1 Chess Cheat] A.C.A.S (고급 체스 보조 시스템)
// @name:nl 🏆 [#1 Chess Cheat] A.C.A.S (Geavanceerd Schaakondersteuningssysteem)
// @name:pl 🏆 [#1 Chess Cheat] A.C.A.S (Zaawansowany System Pomocy Szachowej)
// @name:tr 🏆 [#1 Chess Cheat] A.C.A.S (Gelişmiş Satranç Yardım Sistemi)
// @name:vi 🏆 [#1 Chess Cheat] A.C.A.S (Hệ Thống Hỗ Trợ Cờ Vua Nâng Cao)
// @name:uk 🏆 [#1 Chess Cheat] A.C.A.S (Система передової допомоги в шахах)
// @name:ru 🏆 [#1 Chess Cheat] A.C.A.S (Система расширенной помощи в шахматах)
// @description Enhance your chess performance with a cutting-edge real-time move analysis and strategy assistance system
// @description:en Enhance your chess performance with a cutting-edge real-time move analysis and strategy assistance system
// @description:fi Paranna shakkipelisi suorituskykyä huippuluokan reaaliaikaisen siirtoanalyysin ja strategisen avustusjärjestelmän avulla
// @description:sw Förbättra dina schackprestationer med ett banbrytande rörelseanalys i realtid och strategiassistans
// @description:zh-CN 利用尖端实时走法分析和策略辅助系统,提升您的国际象棋水平
// @description:es Mejora tu rendimiento en ajedrez con un sistema de análisis de movimientos en tiempo real y asistencia estratégica de vanguardia
// @description:hi अपने शतरंज प्रदर्शन को उन्नत करें, एक कटिंग-एज रियल-टाइम मूव विश्लेषण और रणनीति सहायता प्रणाली के साथ
// @description:ar قم بتحسين أداءك في الشطرنج مع تحليل حركات اللعب في الوقت الحقيقي ونظام مساعدة استراتيجية حديث
// @description:pt Melhore seu desempenho no xadrez com uma análise de movimentos em tempo real e um sistema avançado de assistência estratégica
// @description:ja 最新のリアルタイムのムーブ分析と戦略支援システムでチェスのパフォーマンスを向上させましょう
// @description:de Verbessern Sie Ihre Schachleistung mit einer hochmodernen Echtzeitzug-Analyse- und Strategiehilfe-System
// @description:fr Améliorez vos performances aux échecs avec une analyse de mouvement en temps réel de pointe et un système d'assistance stratégique
// @description:it Migliora le tue prestazioni agli scacchi con un sistema all'avanguardia di analisi dei movimenti in tempo reale e assistenza strategica
// @description:ko 최첨단 실시간 움직임 분석 및 전략 지원 시스템으로 체스 성과 향상
// @description:nl Verbeter je schaakprestaties met een geavanceerd systeem voor realtime zetanalyse en strategische ondersteuning
// @description:pl Popraw swoje osiągnięcia w szachach dzięki zaawansowanemu systemowi analizy ruchów w czasie rzeczywistym i wsparciu strategicznemu
// @description:tr Keskinleşmiş gerçek zamanlı hareket analizi ve strateji yardım sistemiyle satranç performansınızı artırın
// @description:vi Nâng cao hiệu suất cờ vua của bạn với hệ thống phân tích nước đi và hỗ trợ chiến thuật hiện đại
// @description:uk Покращуйте свою шахову гру з використанням передової системи аналізу ходів в режимі реального часу та стратегічної підтримки
// @description:ru Слава Украине
// @homepageURL https://psyyke.github.io/A.C.A.S
// @supportURL https://github.com/Psyyke/A.C.A.S/tree/main#why-doesnt-it-work
// @match https://psyyke.github.io/A.C.A.S/*
// @match http://localhost/*
// @match https://www.chess.com/*
// @match https://lichess.org/*
// @match https://playstrategy.org/*
// @match https://www.pychess.org/*
// @match https://chess.org/*
// @match https://papergames.io/*
// @match https://vole.wtf/kilobytes-gambit/
// @match https://chess.coolmath-games.com/*
// @match https://www.coolmathgames.com/0-chess/*
// @match https://immortal.game/*
// @match https://chessarena.com/*
// @match http://chess.net/*
// @match https://www.freechess.club/*
// @match https://*chessclub.com/*
// @match https://gameknot.com/*
// @match https://chesstempo.com/*
// @match https://www.redhotpawn.com/*
// @match https://www.chessanytime.com/*
// @match https://www.simplechess.com/*
// @match https://chessworld.net/*
// @match https://app.edchess.io/*
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_listValues
// @grant GM_registerMenuCommand
// @grant GM_openInTab
// @grant GM_addStyle
// @grant GM_setClipboard
// @grant GM_notification
// @grant unsafeWindow
// @run-at document-start
// @require https://greasyfork.org/scripts/470418-commlink-js/code/CommLinkjs.js
// @require https://greasyfork.org/scripts/470417-universalboarddrawer-js/code/UniversalBoardDrawerjs.js
// @icon https://raw.githubusercontent.com/Psyyke/A.C.A.S/main/assets/images/grey-logo.png
// @version 2.2.2
// @namespace HKR
// @author HKR
// @license GPL-3.0
// ==/UserScript==
/*
e e88~-_ e ,d88~~\
d8b d888 \ d8b 8888
/Y88b 8888 /Y88b `Y88b
/ Y88b 8888 / Y88b `Y88b,
/____Y88b d88b Y888 / d88b /____Y88b d88b 8888
/ Y88b Y88P "88_-~ Y88P / Y88b Y88P \__88P'
Advanced Chess Assistance System (A.C.A.S) v2 | Q3 2023
[WARNING]
- Please be advised that the use of A.C.A.S may violate the rules and lead to disqualification or banning from tournaments and online platforms.
- The developers of A.C.A.S and related systems will NOT be held accountable for any consequences resulting from its use.
- We strongly advise to use A.C.A.S only in a controlled environment ethically.
[ADDITIONAL]
- Big fonts created with: https://www.patorjk.com/software/taag/ (Cyberlarge)
JOIN THE DISCUSSION ABOUT USERSCRIPTS IN GENERAL @ https://hakorr.github.io/Userscripts/community/invite ("Userscript Hub")
DANGER ZONE - DO NOT PROCEED IF YOU DON'T KNOW WHAT YOU'RE DOING*\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//////////////////////////////////////////////////////////////////
DANGER ZONE - DO NOT PROCEED IF YOU DON'T KNOW WHAT YOU'RE DOING*/
/*
______ _____ ______ _______
| ____ | | | |_____] |_____| |
|_____| |_____ |_____| |_____] | | |_____
Code below this point runs on any site, including the GUI.
*/
// KEEP THESE AS FALSE ON PRODUCTION
const debugModeActivated = false;
const onlyUseDevelopmentBackend = false;
const domain = window.location.hostname.replace('www.', '');
const greasyforkURL = 'https://greasyfork.org/en/scripts/459137';
const backendConfig = {
'hosts': { 'prod': 'psyyke.github.io', 'dev': 'localhost' },
'path': '/A.C.A.S/'
};
const currentBackendUrlKey = 'currentBackendURL';
const isBackendUrlUpToDate = Object.values(backendConfig.hosts).some(x => GM_getValue(currentBackendUrlKey)?.includes(x));
function constructBackendURL(host) {
const protocol = window.location.protocol + '//';
const hosts = backendConfig.hosts;
return protocol + (host || (hosts?.prod || hosts?.path)) + backendConfig.path;
}
function isRunningOnBackend() {
const hostsArr = Object.values(backendConfig.hosts);
const foundHost = hostsArr.find(host => host === window?.location?.host);
const isCorrectPath = window?.location?.pathname?.includes(backendConfig.path);
const isBackend = typeof foundHost === 'string' && isCorrectPath;
if(isBackend) {
GM_setValue(currentBackendUrlKey, constructBackendURL(foundHost));
return true;
}
return false;
}
function prependProtocolWhenNeeded(url) {
if(!url.startsWith('http://') && !url.startsWith('https://')) {
return 'http://' + url;
}
return url;
}
function getCurrentBackendURL(skipGmStorage) {
if(onlyUseDevelopmentBackend) {
return constructBackendURL(backendConfig.hosts?.dev);
}
const gmStorageUrl = GM_getValue(currentBackendUrlKey);
if(skipGmStorage || !gmStorageUrl) {
return constructBackendURL();
}
return prependProtocolWhenNeeded(gmStorageUrl);
}
if(!isBackendUrlUpToDate) {
GM_setValue(currentBackendUrlKey, getCurrentBackendURL(true));
}
function createInstanceVariable(dbValue) {
return {
set: (instanceID, value) => GM_setValue(dbValues[dbValue](instanceID), { value, 'date': Date.now() }),
get: instanceID => {
const data = GM_getValue(dbValues[dbValue](instanceID));
if(data?.date) {
data.date = Date.now();
GM_setValue(dbValues[dbValue](instanceID), data);
}
return data?.value;
}
}
}
const tempValueIndicator = '-temp-value-';
const dbValues = {
AcasConfig: 'AcasConfig',
playerColor: instanceID => 'playerColor' + tempValueIndicator + instanceID,
turn: instanceID => 'turn' + tempValueIndicator + instanceID,
fen: instanceID => 'fen' + tempValueIndicator + instanceID
};
const instanceVars = {
playerColor: createInstanceVariable('playerColor'),
fen: createInstanceVariable('fen')
};
if(isRunningOnBackend()) {
// expose variables and functions
unsafeWindow.USERSCRIPT = {
'GM_info': GM_info,
'GM_getValue': val => GM_getValue(val),
'GM_setValue': (val, data) => GM_setValue(val, data),
'GM_deleteValue': val => GM_deleteValue(val),
'GM_listValues': val => GM_listValues(val),
'tempValueIndicator': tempValueIndicator,
'dbValues': dbValues,
'instanceVars': instanceVars,
'CommLinkHandler': CommLinkHandler,
};
return;
}
/*
_______ _ _ _______ _______ _______ _______ _____ _______ _______ _______
| |_____| |______ |______ |______ |______ | | |______ |______
|_____ | | |______ ______| ______| ______| __|__ | |______ ______|
Code below this point only runs on chess sites, not on the GUI itself.
*/
function getUniqueID() {
return ([1e7]+-1e3+4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
)
}
const commLinkInstanceID = getUniqueID();
const blacklistedURLs = [
constructBackendURL(backendConfig?.hosts?.prod),
constructBackendURL(backendConfig?.hosts?.dev),
'https://www.chess.com/play',
'https://lichess.org/',
'https://chess.org/',
'https://papergames.io/en/chess',
'https://playstrategy.org/',
'https://www.pychess.org/',
'https://www.coolmathgames.com/0-chess',
'https://chess.net/'
];
const configKeys = {
'engineElo': 'engineElo',
'moveSuggestionAmount': 'moveSuggestionAmount',
'arrowOpacity': 'arrowOpacity',
'displayMovesOnExternalSite': 'displayMovesOnExternalSite',
'showMoveGhost': 'showMoveGhost',
'showOpponentMoveGuess': 'showOpponentMoveGuess',
'showOpponentMoveGuessConstantly': 'showOpponentMoveGuessConstantly',
'onlyShowTopMoves': 'onlyShowTopMoves',
'maxMovetime': 'maxMovetime',
'chessVariant': 'chessVariant',
'chessEngine': 'chessEngine',
'lc0Weight': 'lc0Weight',
'engineNodes': 'engineNodes',
'chessFont': 'chessFont',
'useChess960': 'useChess960',
'onlyCalculateOwnTurn': 'onlyCalculateOwnTurn',
'ttsVoiceEnabled': 'ttsVoiceEnabled',
'ttsVoiceName': 'ttsVoiceName',
'ttsVoiceSpeed': 'ttsVoiceSpeed',
'chessEngineProfile': 'chessEngineProfile',
'primaryArrowColorHex': 'primaryArrowColorHex',
'secondaryArrowColorHex': 'secondaryArrowColorHex',
'opponentArrowColorHex': 'opponentArrowColorHex',
'reverseSide': 'reverseSide'
};
const config = {};
Object.values(configKeys).forEach(key => {
config[key] = {
get: profile => getGmConfigValue(key, commLinkInstanceID, profile),
set: null
};
});
let BoardDrawer = null;
let chessBoardElem = null;
let chesscomVariantPlayerColorsTable = null;
let activeGuiMoveMarkings = [];
let lastBoardRanks = null;
let lastBoardFiles = null;
let lastBoardSize = null;
let lastPieceSize = null;
let lastBoardOrientation = null;
let isUserMouseDown = false;
const supportedSites = {};
const pieceNameToFen = {
'pawn': 'p',
'knight': 'n',
'bishop': 'b',
'rook': 'r',
'queen': 'q',
'king': 'k'
};
function getArrowStyle(type, fill, opacity) {
const baseStyleArr = [
'stroke: rgb(0 0 0 / 50%);',
'stroke-width: 2px;',
'stroke-linejoin: round;'
];
switch(type) {
case 'best':
return [
`fill: ${fill || 'limegreen'};`,
`opacity: ${opacity || 0.9};`,
...baseStyleArr
].join('\n');
case 'secondary':
return [
...baseStyleArr,
`fill: ${fill ? fill : 'dodgerblue'};`,
`opacity: ${opacity || 0.7};`,
].join('\n');
case 'opponent':
return [
...baseStyleArr,
`fill: ${fill ? fill : 'crimson'};`,
`opacity: ${opacity || 0.3};`,
].join('\n');
}
};
const CommLink = new CommLinkHandler(`frontend_${commLinkInstanceID}`, {
'singlePacketResponseWaitTime': 1500,
'maxSendAttempts': 3,
'statusCheckInterval': 1,
'silentMode': true
});
// manually register a command so that the variables are dynamic
CommLink.commands['createInstance'] = async () => {
return await CommLink.send('mum', 'createInstance', {
'domain': domain,
'instanceID': commLinkInstanceID,
'chessVariant': getChessVariant(),
'playerColor': getPlayerColorVariable()
});
}
CommLink.registerSendCommand('ping', { commlinkID: 'mum', data: 'ping' });
CommLink.registerSendCommand('pingInstance', { data: 'ping' });
CommLink.registerSendCommand('log');
CommLink.registerSendCommand('updateBoardOrientation');
CommLink.registerSendCommand('updateBoardFen');
CommLink.registerSendCommand('calculateBestMoves');
CommLink.registerListener(`backend_${commLinkInstanceID}`, packet => {
try {
switch(packet.command) {
case 'ping':
return `pong (took ${Date.now() - packet.date}ms)`;
case 'getFen':
return getFen();
case 'removeSiteMoveMarkings':
boardUtils.removeMarkings();
return true;
case 'markMoveToSite':
boardUtils.markMoves(packet.data);
return true;
}
} catch(e) {
return null;
}
});
const boardUtils = {
markMoves: moveObjArr => {
const maxScale = 1;
const minScale = 0.5;
const totalRanks = moveObjArr.length;
moveObjArr.forEach((markingObj, idx) => {
const profile = markingObj.profile;
if(idx === 0)
boardUtils.removeMarkings(profile);
const [from, to] = markingObj.player;
const [oppFrom, oppTo] = markingObj.opponent;
const oppMovesExist = oppFrom && oppTo;
const rank = idx + 1;
const showOpponentMoveGuess = getConfigValue(configKeys.showOpponentMoveGuess, profile);
const showOpponentMoveGuessConstantly = getConfigValue(configKeys.showOpponentMoveGuessConstantly, profile);
const arrowOpacity = getConfigValue(configKeys.arrowOpacity, profile) / 100;
const primaryArrowColorHex = getConfigValue(configKeys.primaryArrowColorHex, profile);
const secondaryArrowColorHex = getConfigValue(configKeys.secondaryArrowColorHex, profile);
const opponentArrowColorHex = getConfigValue(configKeys.opponentArrowColorHex, profile);
let playerArrowElem = null;
let oppArrowElem = null;
let arrowStyle = getArrowStyle('best', primaryArrowColorHex, arrowOpacity);
let lineWidth = 30;
let arrowheadWidth = 80;
let arrowheadHeight = 60;
let startOffset = 30;
if(idx !== 0) {
arrowStyle = getArrowStyle('secondary', secondaryArrowColorHex, arrowOpacity);
const arrowScale = totalRanks === 2
? 0.75
: maxScale - (maxScale - minScale) * ((rank - 1) / (totalRanks - 1));
lineWidth = lineWidth * arrowScale;
arrowheadWidth = arrowheadWidth * arrowScale;
arrowheadHeight = arrowheadHeight * arrowScale;
startOffset = startOffset;
}
playerArrowElem = BoardDrawer.createShape('arrow', [from, to],
{
style: arrowStyle,
lineWidth, arrowheadWidth, arrowheadHeight, startOffset
}
);
if(oppMovesExist && showOpponentMoveGuess) {
oppArrowElem = BoardDrawer.createShape('arrow', [oppFrom, oppTo],
{
style: getArrowStyle('opponent', opponentArrowColorHex, arrowOpacity),
lineWidth, arrowheadWidth, arrowheadHeight, startOffset
}
);
if(showOpponentMoveGuessConstantly) {
oppArrowElem.style.display = 'block';
} else {
const squareListener = BoardDrawer.addSquareListener(from, type => {
if(!oppArrowElem) {
squareListener.remove();
}
switch(type) {
case 'enter':
oppArrowElem.style.display = 'inherit';
break;
case 'leave':
oppArrowElem.style.display = 'none';
break;
}
});
}
}
if(idx === 0 && playerArrowElem) {
const parentElem = playerArrowElem.parentElement;
// move best arrow element on top (multiple same moves can hide the best move)
parentElem.appendChild(playerArrowElem);
if(oppArrowElem) {
parentElem.appendChild(oppArrowElem);
}
}
activeGuiMoveMarkings.push({ ...markingObj, playerArrowElem, oppArrowElem, profile });
});
},
removeMarkings: profile => {
let removalArr = activeGuiMoveMarkings;
if(profile) {
removalArr = removalArr.filter(obj => obj.profile === profile);
activeGuiMoveMarkings = activeGuiMoveMarkings.filter(obj => obj.profile !== profile);
} else {
activeGuiMoveMarkings = [];
}
removalArr.forEach(markingObj => {
markingObj.oppArrowElem?.remove();
markingObj.playerArrowElem?.remove();
});
},
setBoardOrientation: orientation => {
if(BoardDrawer) {
if(debugModeActivated) console.warn('setBoardOrientation', orientation);
BoardDrawer.setOrientation(orientation);
}
},
setBoardDimensions: dimensionArr => {
if(BoardDrawer) {
if(debugModeActivated) console.warn('setBoardDimensions', dimensionArr);
BoardDrawer.setBoardDimensions(dimensionArr);
}
}
};
function displayImportantNotification(title, text) {
if(typeof GM_notification === 'function') {
GM_notification({ title: title, text: text });
} else {
alert(`[${title}]` + '\n\n' + text);
}
}
function filterInvisibleElems(elementArr, inverse) {
return [...elementArr].filter(elem => {
const style = getComputedStyle(elem);
const bounds = elem.getBoundingClientRect();
const isHidden =
style.visibility === 'hidden' ||
style.display === 'none' ||
style.opacity === '0' ||
bounds.width == 0 ||
bounds.height == 0;
return inverse ? isHidden : !isHidden;
});
}
function getElementSize(elem) {
const rect = elem.getBoundingClientRect();
if(rect.width !== 0 && rect.height !== 0) {
return { width: rect.width, height: rect.height };
}
const computedStyle = window.getComputedStyle(elem);
const width = parseFloat(computedStyle.width);
const height = parseFloat(computedStyle.height);
return { width, height };
}
function extractElemTransformData(elem) {
const computedStyle = window.getComputedStyle(elem);
const transformMatrix = new DOMMatrix(computedStyle.transform);
const x = transformMatrix.e;
const y = transformMatrix.f;
return [x, y];
}
function getElemCoordinatesFromTransform(elem, config) {
const onlyFlipX = config?.onlyFlipX;
const onlyFlipY = config?.onlyFlipY;
lastBoardSize = getElementSize(chessBoardElem);
const [files, ranks] = getBoardDimensions();
lastBoardRanks = ranks;
lastBoardFiles = files;
const boardOrientation = getPlayerColorVariable();
let [x, y] = extractElemTransformData(elem);
const boardDimensions = lastBoardSize;
let squareDimensions = boardDimensions.width / lastBoardRanks;
const normalizedX = Math.round(x / squareDimensions);
const normalizedY = Math.round(y / squareDimensions);
if(onlyFlipY || boardOrientation === 'w') {
const flippedY = lastBoardFiles - normalizedY - 1;
return [normalizedX, flippedY];
} else {
const flippedX = lastBoardRanks - normalizedX - 1;
return [flippedX, normalizedY];
}
}
function getElemCoordinatesFromLeftBottomPercentages(elem) {
if(!lastBoardRanks || !lastBoardFiles) {
const [files, ranks] = getBoardDimensions();
lastBoardRanks = ranks;
lastBoardFiles = files;
}
const boardOrientation = getPlayerColorVariable();
const leftPercentage = parseFloat(elem.style.left?.replace('%', ''));
const bottomPercentage = parseFloat(elem.style.bottom?.replace('%', ''));
const x = Math.max(Math.round(leftPercentage / (100 / lastBoardRanks)), 0);
const y = Math.max(Math.round(bottomPercentage / (100 / lastBoardFiles)), 0);
if (boardOrientation === 'w') {
return [x, y];
} else {
const flippedX = lastBoardRanks - (x + 1);
const flippedY = lastBoardFiles - (y + 1);
return [flippedX, flippedY];
}
}
function getElemCoordinatesFromLeftTopPixels(elem) {
const pieceSize = getElementSize(elem);
const leftPixels = parseFloat(elem.style.left?.replace('px', ''));
const topPixels = parseFloat(elem.style.top?.replace('px', ''));
const x = Math.max(Math.round(leftPixels / pieceSize.width), 0);
const y = Math.max(Math.round(topPixels / pieceSize.width), 0);
const boardOrientation = getPlayerColorVariable();
if (boardOrientation === 'w') {
const flippedY = lastBoardFiles - (y + 1);
return [x, flippedY];
} else {
const flippedX = lastBoardRanks - (x + 1);
return [flippedX, y];
}
}
function updateChesscomVariantPlayerColorsTable() {
let colors = [];
document.querySelectorAll('*[data-color]').forEach(pieceElem => {
const colorCode = Number(pieceElem?.dataset?.color);
if(!colors?.includes(colorCode)) {
colors.push(colorCode);
}
});
if(colors?.length > 1) {
colors = colors.sort((a, b) => a - b);
chesscomVariantPlayerColorsTable = { [colors[0]]: 'w', [colors[1]]: 'b' };
}
}
function getBoardDimensionsFromSize() {
const boardDimensions = getElementSize(chessBoardElem);
lastBoardSize = getElementSize(chessBoardElem);
const boardWidth = boardDimensions?.width;
const boardHeight = boardDimensions.height;
const boardPiece = getPieceElem();
if(boardPiece) {
const pieceDimensions = getElementSize(boardPiece);
lastPieceSize = getElementSize(boardPiece);
const boardPieceWidth = pieceDimensions?.width;
const boardPieceHeight = pieceDimensions?.height;
const boardRanks = Math.floor(boardWidth / boardPieceWidth);
const boardFiles = Math.floor(boardHeight / boardPieceHeight);
const ranksInAllowedRange = 0 < boardRanks && boardRanks <= 69;
const filesInAllowedRange = 0 < boardFiles && boardFiles <= 69;
if(ranksInAllowedRange && filesInAllowedRange) {
return [boardRanks, boardFiles];
}
}
}
function chessCoordinatesToIndex(coord) {
const x = coord.charCodeAt(0) - 97;
let y = null;
const lastHalf = coord.slice(1);
if(lastHalf === ':') {
y = 9;
} else {
y = Number(coord.slice(1)) - 1;
}
return [x, y];
}
function getGmConfigValue(key, instanceID, profileID) {
if(typeof profileID === 'object') {
profileID = profileID.name;
}
const config = GM_getValue(dbValues.AcasConfig);
const instanceValue = config?.instance?.[instanceID]?.[key];
const globalValue = config?.global?.[key];
if(instanceValue !== undefined) {
return instanceValue;
}
if(globalValue !== undefined) {
return globalValue;
}
if(profileID) {
const globalProfileValue = config?.global?.['profiles']?.[profileID]?.[key];
const instanceProfileValue = config?.instance?.[instanceID]?.['profiles']?.[profileID]?.[key];
if(instanceProfileValue !== undefined) {
return instanceProfileValue;
}
if(globalProfileValue !== undefined) {
return globalProfileValue;
}
}
return null;
}
function isBoardDrawerNeeded() {
const config = GM_getValue(dbValues.AcasConfig);
const gP = config?.global?.['profiles'];
const iP = config?.instance?.[commLinkInstanceID]?.['profiles'];
if(gP) {
const globalProfiles = Object.keys(gP);
for(profileName of globalProfiles) {
if(gP[profileName][configKeys.displayMovesOnExternalSite]) {
return true;
}
}
}
if(iP) {
const instanceProfiles = Object.keys(iP);
for(profileName of instanceProfiles) {
if(iP[profileName][configKeys.displayMovesOnExternalSite]) {
return true;
}
}
}
return false;
}
function getConfigValue(key, profile) {
return config[key]?.get(profile);
}
function setConfigValue(key, val) {
return config[key]?.set(val);
}
function squeezeEmptySquares(fenStr) {
return fenStr.replace(/1+/g, match => match.length);
}
function getPlayerColorVariable() {
return instanceVars.playerColor.get(commLinkInstanceID);
}
function getFenPieceColor(pieceFenStr) {
return pieceFenStr == pieceFenStr.toUpperCase() ? 'w' : 'b';
}
function getFenPieceOppositeColor(pieceFenStr) {
return getFenPieceColor(pieceFenStr) == 'w' ? 'b' : 'w';
}
function convertPieceStrToFen(str) {
if(!str || str.length !== 2) {
return null;
}
const firstChar = str[0].toLowerCase();
const secondChar = str[1];
if(firstChar === 'w') {
return secondChar.toUpperCase();
} else if (firstChar === 'b') {
return secondChar.toLowerCase();
}
return null;
}
function getCanvasPixelColor(canvas, [xPercentage, yPercentage], debug) {
const ctx = canvas.getContext('2d');
const x = xPercentage * canvas.width;
const y = yPercentage * canvas.height;
const imageData = ctx.getImageData(x, y, 1, 1);
const pixel = imageData.data;
const brightness = (pixel[0] + pixel[1] + pixel[2]) / 3;
if(debug) {
const clonedCanvas = document.createElement('canvas');
clonedCanvas.width = canvas.width;
clonedCanvas.height = canvas.height;
const clonedCtx = clonedCanvas.getContext('2d');
clonedCtx.drawImage(canvas, 0, 0);
clonedCtx.fillStyle = 'red';
clonedCtx.beginPath();
clonedCtx.arc(x, y, 1, 0, Math.PI * 2);
clonedCtx.fill();
const dataURL = clonedCanvas.toDataURL();
console.log(canvas, pixel, dataURL);
}
return brightness < 128 ? 'b' : 'w';
}
function canvasHasPixelAt(canvas, [xPercentage, yPercentage], debug) {
xPercentage = Math.min(Math.max(xPercentage, 0), 100);
yPercentage = Math.min(Math.max(yPercentage, 0), 100);
const ctx = canvas.getContext('2d');
const x = xPercentage * canvas.width;
const y = yPercentage * canvas.height;
const imageData = ctx.getImageData(x, y, 1, 1);
const pixel = imageData.data;
if(debug) {
const clonedCanvas = document.createElement('canvas');
clonedCanvas.width = canvas.width;
clonedCanvas.height = canvas.height;
const clonedCtx = clonedCanvas.getContext('2d');
clonedCtx.drawImage(canvas, 0, 0);
clonedCtx.fillStyle = 'red';
clonedCtx.beginPath();
clonedCtx.arc(x, y, 1, 0, Math.PI * 2);
clonedCtx.fill();
const dataURL = clonedCanvas.toDataURL();
console.log(canvas, pixel, dataURL);
}
return pixel[3] !== 0;
}
function getSiteData(dataType, obj) {
const pathname = window.location.pathname;
let dataObj = { pathname };
if(obj && typeof obj === 'object') {
dataObj = { ...dataObj, ...obj };
}
const dataHandlerFunction = supportedSites[domain]?.[dataType];
if(typeof dataHandlerFunction !== 'function') {
return null;
}
const result = dataHandlerFunction(dataObj);
//if(debugModeActivated) console.warn('GET_SITE_DATA', '| DATA_TYPE:', dataType, '| INPUT_OBJ:', obj, '| DATA_OBJ:', dataObj, '| RESULT:', result);
return result;
}
function addSupportedChessSite(domain, typeHandlerObj) {
supportedSites[domain] = typeHandlerObj;
}
function getBoardElem() {
const boardElem = getSiteData('boardElem');
return boardElem || null;
}
function getPieceElem(getAll) {
const boardElem = getBoardElem();
const boardQuerySelector = (getAll ? query => [...boardElem?.querySelectorAll(query)] : boardElem?.querySelector?.bind(boardElem));
if(typeof boardQuerySelector !== 'function')
return null;
const pieceElem = getSiteData('pieceElem', { boardQuerySelector, getAll });
return pieceElem || null;
}
function getSquareElems(element) {
const squareElems = getSiteData('squareElems', { element });
return squareElems || null;
}
function getChessVariant() {
const chessVariant = getSiteData('chessVariant');
return chessVariant || null;
}
function getBoardOrientation() {
const boardOrientation = getSiteData('boardOrientation');
return boardOrientation || null;
}
function getPieceElemFen(pieceElem) {
const pieceFen = getSiteData('pieceElemFen', { pieceElem });
return pieceFen || null;
}
// this function gets called a lot, needs to be optimized
function getPieceElemCoords(pieceElem) {
const pieceCoords = getSiteData('pieceElemCoords', { pieceElem });
return pieceCoords || null;
}
function getBoardDimensions() {
const boardDimensionArr = getSiteData('boardDimensions');
if(boardDimensionArr) {
lastBoardRanks = boardDimensionArr[0];
lastBoardFiles = boardDimensionArr[1];
return boardDimensionArr;
} else {
lastBoardRanks = 8;
lastBoardFiles = 8;
return [8, 8];
}
}
function isMutationNewMove(mutationArr) {
const isNewMove = getSiteData('isMutationNewMove', { mutationArr });
return isNewMove || false;
}
function getFen(onlyBasic) {
const [boardRanks, boardFiles] = getBoardDimensions();
if(debugModeActivated) console.warn('getFen()', 'onlyBasic:', onlyBasic, 'Ranks:', boardRanks, 'Files:', boardFiles);
const board = Array.from({ length: boardFiles }, () => Array(boardRanks).fill(1));
function getBasicFen() {
const pieceElems = getPieceElem(true);
const isValidPieceElemsArray = Array.isArray(pieceElems) || pieceElems instanceof NodeList;
if(isValidPieceElemsArray) {