Repository navigation
Expand file tree
/
Copy pathcomplete-qs-betterment-script.user.js
More file actions
1605 lines (1445 loc) · 73.8 KB
/
Copy pathcomplete-qs-betterment-script.user.js
File metadata and controls
1605 lines (1445 loc) · 73.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
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 Queslar Betterment Script
// @namespace https://www.queslar.com
// @version 1.8.0
// @description A script that lets you know more info about quests and other QOL improvements
// @author RiddleMeDoo
// @match *://*.queslar.com/*
// @require https://code.jquery.com/jquery-3.6.3.slim.min.js
// @resource settingsMenu https://raw.githubusercontent.com/RiddleMeDoo/qs-bettermentScript/master/tomeSettingsMenu.html
// @grant GM_getResourceText
// @downloadURL https://update.greasyfork.org/scripts/435820/Queslar%20Betterment%20Script.user.js
// @updateURL https://update.greasyfork.org/scripts/435820/Queslar%20Betterment%20Script.meta.js
// ==/UserScript==
class Script {
constructor() {
// Get quest data
this.quest = {
questsCompleted: 0,
numRefreshes: 0,
refreshesUsed: 0,
villageBold: 0,
villageSize: 1,
villageNumRefreshes: 5,
villageRefreshesUsed: 0,
baseStat: 15,
minActions: 360,
maxActions: 580,
};
this.catacomb = {
actionTimerSeconds: 30,
tomesAreEquipped: true,
}
this.kdExploLevel = 0;
this.playerId;
this.gameData;
this.gems = [];
//observer setup
this.initObservers();
this.currentPath = window.location.hash.split('/').splice(2).join();
// Other setup
addInvisibleScrollDiv();
}
loadDataFromStorage() {
/**
* Load data stored in the localStorage of the website. Each player stores their own settings.
*/
// ! BANDAID migration, please remove non-id settings in storage after 2024-12-01
this.villageSettings = JSON.parse(localStorage.getItem(`${this.playerId}:QuesBS_villageSettings`));
if (!this.villageSettings && localStorage.getItem('QuesBS_villageSettings')) {
// Attempt migration from old settings
this.villageSettings = JSON.parse(localStorage.getItem('QuesBS_villageSettings'));
localStorage.setItem(`${this.playerId}:QuesBS_villageSettings`, JSON.stringify(this.villageSettings));
localStorage.removeItem('QuesBS_villageSettings');
} else if(!this.villageSettings) {
this.villageSettings = {
strActions: 30000,
taxObjectivePercent: 0,
resActionRatio: 999999999999,
};
}
this.tomeSettings = JSON.parse(localStorage.getItem(`${this.playerId}:QuesBS_tomeSettings`));
if (!this.tomeSettings && localStorage.getItem('QuesBS_tomeSettings')) {
// Attempt migration from old settings
this.tomeSettings = JSON.parse(localStorage.getItem('QuesBS_tomeSettings'));
localStorage.setItem(`${this.playerId}:QuesBS_tomeSettings`, JSON.stringify(this.tomeSettings));
localStorage.removeItem('QuesBS_tomeSettings');
} else if(!this.tomeSettings) {
this.tomeSettings = {
goldKillTomesEquippedAmount: 0,
useWeightSettings: false,
weights: {},
thresholds: {
reward: 999900,
mobDebuff: 999900,
character: 999900,
characterWb: 999900,
elementalConv: 999900,
multiMob: 1,
lifesteal: 1,
actionSpeed: 1,
mobSkip: 1,
numGoodRolls: 1,
numGoodRollsWb: 2,
},
spaceThresholds: {
reward: 6,
mobDebuff: 6,
character: 6,
wb: 6,
rare: 6,
legendary: 6,
},
hideMods: {},
disableRefreshOnHighlight: true,
};
}
// Legacy code updates, keep for now until bugs do not occur when it gets removed
this.tomeSettings.useWeightSettings = this.tomeSettings.useWeightSettings ?? false;
this.tomeSettings.weights = this.tomeSettings.weights ?? {};
this.tomeSettings.thresholds = this.tomeSettings.thresholds ?? {
reward: this.tomeSettings.highlightReward ?? 99900,
mobDebuff: this.tomeSettings.highlightMob ?? 99900,
character: this.tomeSettings.highlightCharacter ?? 99900,
characterWb: this.tomeSettings.highlightCharacterWb ?? 99900,
elementalConv: this.tomeSettings.highlightElementalConv ?? 99900,
multiMob: this.tomeSettings.highlightMultiMob ?? 1,
lifesteal: this.tomeSettings.highlightLifesteal ?? 1,
actionSpeed: this.tomeSettings.highlightActionSpeed ?? 1,
mobSkip: this.tomeSettings.highlightMobSkip ?? 1,
numGoodRolls: this.tomeSettings.numGoodRolls ?? 1,
numGoodRollsWb: 2,
}
this.tomeSettings.spaceThresholds = this.tomeSettings.spaceThresholds ?? {
reward: this.tomeSettings.spaceLimitReward ?? 6,
mobDebuff: this.tomeSettings.spaceLimitMob ?? 6,
character: this.tomeSettings.spaceLimitCharacter ?? 6,
wb: this.tomeSettings.spaceLimitWb ?? 6,
rare: this.tomeSettings.spaceLimitRare ?? 6,
legendary: this.tomeSettings.spaceLimitLegendary ?? 6,
}
this.tomeSettings.hideMods = this.tomeSettings.hideMods ?? {};
this.tomeSettings.disableRefreshOnHighlight = this.tomeSettings.disableRefreshOnHighlight ?? true;
}
async getGameData() { //ULTIMATE POWER
let tries = 10;
//Get a reference to *all* the data the game is using, courtesy of Blah's exposed global object
this.gameData = playerGeneralService;
while(this.gameData === undefined && tries > 0) { //Power comes with a price; wait for it to load
await new Promise(resolve => setTimeout(resolve, 500))
this.gameData = playerGeneralService;
tries--;
}
if (tries <= 0) {
console.log('QuesBS: Could not load gameData.');
}
}
async updateCatacombData() {
/***
* Updates catacomb action timer in seconds and equipped tomes indicator
***/
// Wait until services load
while(this.gameData?.playerCatacombService === undefined || this.gameData?.playerVillageService === undefined) {
await new Promise(resolve => setTimeout(resolve, 200));
}
const tomes = this.gameData.playerCatacombService.calculateTomeOverview();
// Calculate catacomb action speed in seconds
let actionTimerSeconds = 24;
if (this.gameData.playerCatacombService.actionData) {
// If a catacomb is active, it will show how many seconds it has in an action
actionTimerSeconds = this.gameData.playerCatacombService.actionData.actionSpeed;
} else {
// If a catacomb is inactive, actionData is undefined. Manually calculate
const villageService = this.gameData.playerVillageService;
let villageActionSpeedBoost;
if (villageService?.isInVillage === true) {
const level = villageService?.buildings?.observatory?.amount ?? 0;
villageActionSpeedBoost = (Math.floor(level / 20) * Math.floor(level / 20 + 1) / 2 * 20 + (level % 20) * Math.floor(level / 20 + 1)) / 100;
} else {
villageActionSpeedBoost = 0;
}
actionTimerSeconds = 30 / (1 + villageActionSpeedBoost + tomes.speed / 100) + 0.2
}
this.catacomb = {
actionTimerSeconds: actionTimerSeconds,
tomesAreEquipped: tomes.mobs > 0,
}
}
async initPlayerData() {
// Make sure gameData is loaded before initializing player data
let loadingTries = 300;
while ((!this.gameData || this.gameData.loadingService.loading) && loadingTries > 0) {
if (!this.gameData) {
this.getGameData();
}
console.log('QuesBS: Waiting for game to load...');
await new Promise(resolve => setTimeout(resolve, 1000));
loadingTries--;
}
if (loadingTries <= 0) {
console.log('QuesBS: Could not load player data. Please refresh or manually restart the script.');
return;
}
//Couldn't find an easier method to get quest completions than a POST request
this.gameData.httpClient.post('/player/load/misc', {}).subscribe(
val => {
this.quest.questsCompleted = val.playerMiscData.quests_completed;
this.playerId = val.playerMiscData.player_id;
this.loadDataFromStorage();
},
response => console.log('QuesBS: POST request failure', response)
);
await this.updateRefreshes();
if(this.gameData.playerVillageService?.isInVillage === true) {
let villageService = this.gameData.playerVillageService;
//Wait for service to load
while(villageService === undefined) {
await new Promise(resolve => setTimeout(resolve, 200));
villageService = this.gameData.playerVillageService;
}
this.quest.villageBold = villageService.strengths.bold.amount;
this.quest.villageSize = villageService.general.members.length;
this.quest.villageNumRefreshes = villageService.general.dailyQuestsBought + 5;
this.quest.villageRefreshesUsed = villageService.general.dailyQuestsUsed;
}
//Can't be bothered to calculate it accurately using all 4 stats
this.quest.baseStat = Math.min(15, this.gameData.playerStatsService?.strength * 0.0025);
// Get catacomb data
await this.updateCatacombData();
// Get kd exploration level for wb drops
await this.updateKdInfo();
// Other misc player refreshing stuff
this.gems = [];
}
async getPartyActions() {
//A function to wait for party service to load
//And also to abstract the horribly long method
while(this.gameData?.partyService?.partyOverview?.partyInformation === undefined) {
await new Promise(resolve => setTimeout(resolve, 200));
}
return this.gameData.partyService.partyOverview.partyInformation[this.playerId].actions.daily_actions_remaining;
}
async updateRefreshes() {
//Only made a load waiter because script was having issues with not loading
while(this.gameData?.playerQuestService?.refreshesUsed === undefined) {
await new Promise(resolve => setTimeout(resolve, 200));
}
this.quest.numRefreshes = this.gameData.playerQuestService.refreshesBought + 20;
this.quest.refreshesUsed = this.gameData.playerQuestService.refreshesUsed;
}
async updateVillageRefreshes() {
let villageService = this.gameData.playerVillageService;
this.quest.villageNumRefreshes = villageService.general.dailyQuestsBought + 5;
this.quest.villageRefreshesUsed = villageService.general.dailyQuestsUsed;
const maxBuildingLevel = Object.values(villageService.buildings).reduce((currMax, building) => Math.max(currMax, building.amount), 0);
const buildingCost = villageService.calculateVillageBuildingUpgradeCost(maxBuildingLevel);
this.quest.villageMaxResCost = buildingCost[1].cost * 4 + (buildingCost?.[5]?.cost ?? 0);
}
async updateKdInfo() {
/** Only stores exploration information for wb drops */
let kdService = this.gameData.playerKingdomService;
// Wait for game to load data
while(kdService?.kingdomData?.explorations === undefined) {
await new Promise(resolve => setTimeout(resolve, 200));
}
this.kdExploLevel = kdService.kingdomData.explorations.level;
}
initObservers() {
/**
* Initialize observers which will be used to detect changes on
* each specific page when it updates.
*/
let scriptObject = this; //mutation can't keep track of this
this.personalQuestObserver = new MutationObserver(mutationsList => {
scriptObject.handlePersonalQuest(mutationsList[0]);
});
this.villageQuestObserver = new MutationObserver(mutationsList => {
scriptObject.handleVillageQuest(mutationsList[0]);
});
this.catacombObserver = new MutationObserver(mutationsList => {
this.handleCatacombPage(mutationsList[0]);
});
this.tomeObserver = new MutationObserver(mutationsList => {
this.handleCatacombTomeStore(mutationsList[0]);
});
this.wbDropsObserver = new MutationObserver(mutationsList => {
this.handleWbChestOpening(mutationsList[0]);
});
}
async initPathDetection() {
/**
* Initializes the event trigger that will watch for changes in the
* url path. This will allow us to determine which part of the
* script to activate on each specific page.
*/
let router = this.gameData?.router
//Wait for service to load
while(router === undefined && router?.events === undefined) {
await new Promise(resolve => setTimeout(resolve, 200));
router = this.gameData.router
}
this.gameData.router.events.subscribe(event => {
if(event.navigationTrigger) this.handlePathChange(event.url);
});
//Send a popup to player as feedback
this.gameData.snackbarService.openSnackbar('QuesBS has been loaded.');
}
async insertPlayerStatRatios(petDiv) {
/*
* Insert player stat ratios into the pet div by copy pasting from one of the existing
* boxes.
*/
// Copy existing box to match the css style
const statBoxElem = petDiv.children[1].children[2].cloneNode(true);
statBoxElem.firstChild.innerText = 'Player stat ratios';
const statsBody = statBoxElem.children[1];
const playerStatsElem = document.querySelector('app-inventory-menu > div > div:nth-child(3)');
const statRatios = getStatRatios(playerStatsElem);
// Insert the stat ratios
for (let i = 0; i < statRatios.length; i++) {
const row = statsBody.children[i].firstChild;
row.children[1].innerText = `${playerStatsElem.children[i].children[1].innerText}`;
const statRatioDiv = document.createElement('div');
statRatioDiv.innerText = `(${statRatios[i]})`;
row.appendChild(statRatioDiv);
}
// Insert elem to be under the pet farm column
petDiv.children[2].appendChild(statBoxElem);
}
async handlePathChange(url) {
/**
* Detects which page the player navigated to when the url path
* has changed, then activates the observer for the page.
*/
const path = url.split('/').length == 2 ? url.split('/').slice(1) : url.split('/').slice(2);
if(path.join() !== this.currentPath) {
this.stopObserver(this.currentPath);
}
this.currentPath = path.join();
//Activate observer if on a specific page
if(path[path.length - 1].toLowerCase() === 'quests' && path[0].toLowerCase() === 'actions') {
//Observe personal quest page for updates
let target = document.querySelector('app-actions');
//Sometimes the script attempts to search for element before it loads in
while(!target) {
await new Promise(resolve => setTimeout(resolve, 50))
target = document.querySelector('app-actions');
}
this.personalQuestObserver.observe(target, {
childList: true, subtree: true, attributes: false,
});
//Sometimes there is no change observed for the initial page load, so call function
await this.handlePersonalQuest({target: target});
} else if(path[path.length - 1].toLowerCase() === 'quests' && path[0].toLowerCase() === 'village') {
//Observe village quest page for updates
let target = document.querySelector('app-village');
//Sometimes the script attempts to search for element before it loads in
while(!target) {
await new Promise(resolve => setTimeout(resolve, 50))
target = document.querySelector('app-village');
}
this.villageQuestObserver.observe(target, {
childList: true, subtree: true, attributes: false,
});
//Sometimes there is no change observed for the initial page load, so call function
await this.handleVillageQuest({target: target});
} else if(path[path.length - 1].toLowerCase() === 'settings' && path[0].toLowerCase() === 'village') {
//Insert our own settings box
await this.insertVillageSettingsElem();
} else if(path[path.length - 1].toLowerCase() === 'catacomb' && path[0].toLowerCase() === 'catacombs') {
this.updateCatacombData();
let target = document.querySelector('app-catacomb-main')?.firstChild;
while(!target) {
await new Promise(resolve => setTimeout(resolve, 200))
target = document.querySelector('app-catacomb-main').firstChild;
}
if (target.nodeName === '#comment') { // Active catacomb page
// Only listen for change in active/inactive state
this.catacombObserver.observe(target.parentElement, {
childList: true, subtree: false, attributes: false,
});
this.handleCatacombPage({target: target});
} else {
this.catacombObserver.observe(target, {
childList: true, subtree: true, attributes: false,
});
}
} else if (path[path.length - 1].toLowerCase() === 'tome_store' && path[0].toLowerCase() === 'catacombs') {
await this.modifyTomeStorePage();
let target = $('app-catacomb-tome-store > div > div > div.base-scrollbar > div');
while(target.length < 1) {
await new Promise(resolve => setTimeout(resolve, 200))
target = $('app-catacomb-tome-store > div > div > div.base-scrollbar > div');
}
this.tomeObserver.observe(target[0], {
childList: true, subtree: false, attributes: false
});
this.handleCatacombTomeStore({target: target[0]});
} else if (path[path.length - 1].toLowerCase() === 'chests' && path[0].toLowerCase() === 'wb') {
let target = $('app-game-world-boss-chests > div');
while(target.length < 1) {
await new Promise(resolve => setTimeout(resolve, 200))
target = $('app-game-world-boss-chests > div');
}
this.wbDropsObserver.observe(target[0], {
childList: true, subtree: false, attributes: false
});
} else if (path[path.length - 1].toLowerCase() === 'pets' && path[0].toLowerCase() === 'actions') {
let target = $('app-actions-pets > .scrollbar > div > .d-flex');
while(target.length < 1) {
await new Promise(resolve => setTimeout(resolve, 200))
target = $('app-actions-pets > .scrollbar > div > .d-flex');
}
// Insert stat ratios on the pets page
await this.insertPlayerStatRatios(target[0]);
} else if (path[path.length - 1].toLowerCase() === 'gems' && path[0].toLowerCase() === 'inventory') {
await this.insertFuseFrenzyButton();
}
}
async handlePersonalQuest(mutation) {
/**
* Handles a new update to the personal quests page. It loads in all
* the extra quest information, which differs depending on an active or
* non-active quest page view.
*/
//Filter out any unneeded mutations/updates to the page
if(mutation?.addedNodes?.length < 1 ||
mutation?.addedNodes?.[0]?.localName === 'mat-tooltip-component' ||
mutation?.addedNodes?.[0]?.nodeName === 'TH' ||
mutation?.addedNodes?.[0]?.nodeName === 'TD' ||
mutation?.addedNodes?.[0]?.nodeName === '#text' ||
mutation?.addedNodes?.[0]?.className === 'mat-ripple-element' ||
mutation?.addedNodes?.[0]?.id === 'questInfoRow') {
return;
}
//Modify the table used to hold quest information
const questTable = mutation.target.parentElement.tagName === 'TABLE' ? mutation.target.parentElement : mutation.target.querySelector('table');
if(questTable) {
let infoRow = null;
//Add end time column to table
this.addEndTimeColumn(questTable);
const tableBody = questTable.children[1];
//There are two states: active quest and no quest
if(tableBody.children.length > 2) {//No quest
//Get the info row that goes at the bottom
infoRow = await this.modifyQuestInfo(tableBody, false, false);
} else if(tableBody.children.length > 0) { //Active quest
//Update number of refreshes used, just in case
await this.updateRefreshes();
infoRow = await this.modifyQuestInfo(tableBody, false, true);
} else {
return;
}
//Add an extra row for extra quest info if there isn't one already
if(!document.getElementById('questInfoRow')) tableBody.appendChild(infoRow);
}
}
async handleVillageQuest(mutation) {
/**
* Handles a new update to the village quests page. It loads in all
* the extra quest information, which differs depending on an active or
* non-active quest page view.
*/
//Filter out unneeded mutations/updates to page
if(mutation?.addedNodes?.length < 1 ||
mutation?.addedNodes?.[0]?.nodeName === '#text' ||
mutation?.addedNodes?.[0]?.nodeName === 'TH' ||
mutation?.addedNodes?.[0]?.nodeName === 'TD' ||
mutation?.addedNodes?.[0]?.className === 'mat-ripple-element' ||
mutation?.addedNodes?.[0]?.id === 'questInfoRow') {
return;
}
const questTable = mutation.target.parentElement.tagName === 'TABLE' ? mutation.target.parentElement : mutation.target.querySelector('table');
if(questTable) {
await this.updateVillageRefreshes(); //Update for refreshes used
this.addEndTimeColumn(questTable);
//Add end time
const tableBody = questTable.children[1];
//Add end time elems to the end time column
if(tableBody.children.length > 2) { //Quest is not active
await this.modifyQuestInfo(tableBody, true, false);
} else { //Quest is active
await this.modifyQuestInfo(tableBody, true, true);
}
//Add info text at the bottom of quest table
const infoRow = document.createTextNode('End time is calculated assuming all members are active. The time is approximate and may not be accurate.'
+ `${this.quest.villageRefreshesUsed}/${this.quest.villageNumRefreshes} refreshes used.`);
infoRow.id = 'questExplanation';
if(questTable.parentElement.lastChild.id !== 'questExplanation') {
questTable.parentElement.appendChild(infoRow);
}
}
}
async handleCatacombPage(mutation) {
/**
* Handle an update on the catacomb page, and insert an end time into the page
* for any selected catacomb.
**/
if ( // skip unnecessary updates
mutation?.addedNodes?.[0]?.localName === 'mat-tooltip-component' ||
mutation?.addedNodes?.[0]?.className === 'mat-ripple-element' ||
mutation?.addedNodes?.[0]?.nodeName === '#text' ||
mutation?.addedNodes?.[0]?.id === 'catacombEndTime'
) {
return;
}
const mainView = document.querySelector('app-catacomb-main');
//Check if active or inactive view
if (mainView.firstChild.nodeName === '#comment') { // Active view
const parentElement = mainView.firstElementChild.firstChild.firstChild.firstChild;
const secondsLeft = parseNumber(parentElement.children[1].innerText);
// Use api data
const totalMobs = this.gameData.playerCatacombService.actionData.catacombStats.mobCount;
const mobsKilled = this.gameData.playerCatacombService.actionData.catacombStats.killCount;
// Create the end time ele to insert into
const endTimeEle = document.getElementById('catacombEndTime') ?? document.createElement('div');
endTimeEle.id = 'catacombEndTime';
endTimeEle.setAttribute('class', 'h5');
endTimeEle.innerText = `| End time: ${getCatacombEndTime(totalMobs - mobsKilled, this.catacomb.actionTimerSeconds, secondsLeft)}`;
parentElement.appendChild(endTimeEle);
} else { // Inactive view
const mobOverviewEle = mainView.firstChild.children[1].firstChild.firstChild;
const totalMobs = parseNumber(mobOverviewEle.firstChild.children[1].firstChild.children[11].children[1].innerText);
const cataTierSelectionEle = mobOverviewEle.children[1];
// Create the end time ele to insert into
const endTimeEle = document.getElementById('catacombEndTime') ?? document.createElement('div');
endTimeEle.id = 'catacombEndTime';
endTimeEle.innerText = `End time (local): ${getCatacombEndTime(totalMobs, this.catacomb.actionTimerSeconds)}`;
cataTierSelectionEle.appendChild(endTimeEle);
// Create tooltips for gold/hr and emblems/hr
const goldEle = mobOverviewEle.firstChild.children[1].firstChild.children[9].children[1];
const boostedGoldPerKill = parseNumber(goldEle.innerText);
const goldHr = boostedGoldPerKill / this.catacomb.actionTimerSeconds * 3600;
goldEle.parentElement.setAttribute('title', `${goldHr.toLocaleString(undefined, {maximumFractionDigits:2})}/Hr`);
const emblemsEle = mobOverviewEle.firstChild.children[1].firstChild.children[10].children[1];
const emblemsHr = parseNumber(emblemsEle.innerText) / totalMobs / this.catacomb.actionTimerSeconds * 3600;
emblemsEle.parentElement.setAttribute('title', `${emblemsHr.toLocaleString(undefined, {maximumFractionDigits:2})}/Hr`);
// Highlight start button if tomes are equipped
const goldPerKillEle = mutation.target.parentElement.parentElement?.previousSibling?.children?.[9]?.firstElementChild;
if (!goldPerKillEle) return; // Early return if element cannot be found, since mutations can come from anything
const baseGoldPerKill = parseNumber(goldPerKillEle.innerText);
const startCataButton = mobOverviewEle.nextSibling.firstChild;
if (this.catacomb.tomesAreEquipped && baseGoldPerKill < this.tomeSettings.goldKillTomesEquippedAmount) {
startCataButton.style.boxShadow = '0px 0px 12px 7px red';
startCataButton.style.color = 'red';
} else {
startCataButton.style.boxShadow = 'none';
startCataButton.style.color = '';
}
}
}
async handleCatacombTomeStore(mutation) {
/**
* Add highlights around tomes with good boosts and obscures bad tomes
* Credit to Ender for code collaboration and fading out tomes
*
**/
if ( // skip unnecessary updates
mutation?.addedNodes?.[0]?.localName === 'mat-tooltip-component' ||
mutation?.addedNodes?.[0]?.className === 'mat-ripple-element' ||
mutation?.addedNodes?.[0]?.nodeName === '#text' ||
mutation?.addedNodes?.[0]?.id === 'highlight'
) {
return;
}
// Get store element and tome store data
const tomeElements = $('app-catacomb-tome-store > div > div > div.base-scrollbar > div > div');
let tomes = this.gameData.playerCatacombService?.tomeStore;
while (this.gameData.playerCatacombService === undefined || tomes === undefined) {
await new Promise(resolve => setTimeout(resolve, 200))
tomes = this.gameData.playerCatacombService?.tomeStore;
}
// Put an id on the first tome of the store to mark it as "processed"
tomeElements[0].id = 'highlight';
// Get the refresh button for disabling it
const refreshButton = $('app-catacomb-tome-store > div > div > div.my-auto > div > button')[0];
refreshButton.style.touchAction = 'manipulation'; // Disable double tap zoom for mobile when tapping the button
// For each tome (loop by index), check if tome has good modifiers.
for (let i = 0; i < tomes.length; i++) {
const tomeMods = tomes[i];
const tomeElement = tomeElements[i].firstChild;
let shouldFadeTome = true;
let highlightIncome = false;
if (this.tomeSettings?.useWeightSettings) {
// Create row after tome mods to display the power per space values
const displayEle = tomeElement.querySelector(`#perspacedisplay-${tomeMods.id}`) ?? document.createElement('div');
displayEle.id = `perspacedisplay-${tomeMods.id}`;
displayEle.className = 'd-flex justify-content-between ng-star-inserted';
tomeElement.appendChild(displayEle, tomeElement.nextSibling.firstChild);
if (this.checkTomeIncomePower(tomeMods, displayEle)) { // Displays income power as well
shouldFadeTome = false;
highlightIncome = true;
}
if (this.checkTomeWBPower(tomeMods, displayEle)) { // Displays wb power as well
shouldFadeTome = false;
}
} else {
if (this.checkTomeIncomeMeetsThresholds(tomeMods, tomeElement)) {
shouldFadeTome = false;
highlightIncome = true;
}
if (this.checkTomeWBMeetsThresholds(tomeMods, tomeElement)) {
shouldFadeTome = false;
}
}
// Fade out tomes that didn't meet requirements
if (shouldFadeTome) {
tomeElement.style.color = "rgba(255, 255, 255, 0.4)";
[...tomeElement.children].forEach((child) => {
child.style.opacity = "0.4";
});
} else {
if (this.tomeSettings.disableRefreshOnHighlight) {
// Briefly disable the refresh button
refreshButton.disabled = true;
refreshButton.className = 'mat-focus-indicator mat-stroked-button mat-button-base';
document.querySelector('#stopScrollDiv').focus({preventScroll: true}); // Prevent spacebar from scrolling down
setTimeout((button) => {
button.disabled = false;
button.className = 'mat-focus-indicator mat-raised-button mat-button-base';
button.focus({preventScroll: true});
}, 1600, refreshButton);
}
if (highlightIncome) {
tomeElement.parentElement.style.boxShadow = '0 0 30px 15px #48abe0';
} else {
tomeElement.parentElement.style.boxShadow = '0 0 30px 15px green';
}
}
// Hide modifiers on tomes according to the settings
const modifierOrder = [
'tomeName', 'spaceReq', 'addedMobs', 'reward', 'mobDebuff', 'character', 'waterResistance',
'thunderResistance', 'fireResistance', 'meleeResistance', 'rangedResistance', 'elementalConversion',
'fortifyReduction'
];
for (let i = 2; i < tomeElement.children.length; i++) {
const modifierEle = tomeElement.children[i];
if (this.tomeSettings.hideMods[modifierOrder[i]]) {
modifierEle.style.setProperty('display', 'none', 'important');
} else {
modifierEle.style.display = '';
}
}
}
}
checkTomeIncomePower(tomeMods, powerDisplayEle) {
/**
* Returns true if the tomeMods are weighted and meet the thresholds according to the tome settings for income.
* It also displays the income power on the tome using the powerDisplayEle elememt
*/
let incomePerSpace = 0;
incomePerSpace += (tomeMods.multi_mob ?? 0) / 100 * (this.tomeSettings.weights.multiMob ?? 0);
incomePerSpace += (tomeMods.character_multiplier ?? 0) / 100 * (this.tomeSettings.weights.character ?? 0);
incomePerSpace += (tomeMods.speed ?? 0) / 100 * (this.tomeSettings.weights.actionSpeed ?? 0);
incomePerSpace += (tomeMods.skip ?? 0) / 100 * (this.tomeSettings.weights.mobSkip ?? 0);
incomePerSpace += (tomeMods.lifesteal ?? 0) / 100 * (this.tomeSettings.weights.lifesteal ?? 0);
incomePerSpace += (tomeMods.reward_multiplier ?? 0) / 100 * (this.tomeSettings.weights.reward ?? 0);
incomePerSpace += (tomeMods.mob_multiplier ?? 0) / 100 * (this.tomeSettings.weights.mobDebuff ?? 0);
incomePerSpace /= tomeMods.space_requirement;
// Display the income power per space in the powerDisplayEle
const incomePerSpaceEle = powerDisplayEle.querySelector(`#incomeperspace-${tomeMods.id}`) ?? document.createElement('div');
incomePerSpaceEle.id = `incomeperspace-${tomeMods.id}`;
incomePerSpaceEle.innerText = `Income: ${Math.round(incomePerSpace).toLocaleString()}`;
powerDisplayEle.appendChild(incomePerSpaceEle);
// Check
if (incomePerSpace >= this.tomeSettings.weights.incomePerSpaceThreshold) {
incomePerSpaceEle.style.color = 'gold';
return true;
}
return false;
}
checkTomeWBPower(tomeMods, powerDisplayEle) {
/**
* Returns true if the tomeMods are weighted and meet the thresholds according to the tome settings for world boss.
* It also displays the WB power on the tome using the powerDisplayEle elememt
*/
let wbPowerPerSpace = (tomeMods.character_multiplier ?? 0) / 100.0 * (this.tomeSettings.weights.wbCharacter ?? 0);
wbPowerPerSpace += (tomeMods.elemental_conversion ?? 0) / 100.0 * (this.tomeSettings.weights.wbElementalConv ?? 0);
wbPowerPerSpace /= tomeMods.space_requirement;
// Display the WB power per space in the powerDisplayEle
const wbPowerPerSpaceEle = powerDisplayEle.querySelector(`#wbpowerperspace-${tomeMods.id}`) ?? document.createElement('div');
wbPowerPerSpaceEle.id = `wbpowerperspace-${tomeMods.id}`;
wbPowerPerSpaceEle.innerText = `WB: ${Math.round(wbPowerPerSpace).toLocaleString()}`;
powerDisplayEle.appendChild(wbPowerPerSpaceEle);
if (wbPowerPerSpace >= this.tomeSettings.weights.wbPowerPerSpaceThreshold) {
wbPowerPerSpaceEle.style.color = 'forestgreen';
return true;
}
return false;
}
checkTomeIncomeMeetsThresholds(tomeMods, tomeElement) {
/**
* Returns true if given tomes meets thresholds accored to the stored tome settings for income
* Also highlight the tomeElement if threshold is met
*/
let sumGoodRolls = 0;
// Check each important mods: reward, character, mob, lifesteal, multi mob, action speed, mob skip
// For each mod, if it meets the settings highlight the mod and increment the number of rolls
if (
this.tomeSettings.thresholds.reward > 0
&& tomeMods.reward_multiplier >= this.tomeSettings.thresholds.reward
&& tomeMods.space_requirement <= this.tomeSettings.spaceThresholds.reward
) {
const isDouble = tomeMods.reward_multiplier >= this.tomeSettings.thresholds.reward * 2;
tomeElement.children[3].style.border = `${isDouble ? 'thick' : '2px'} solid`;
tomeElement.children[3].style.borderColor = tomeElement.children[3].firstChild.style.color ?? 'gold';
sumGoodRolls += Math.floor(tomeMods.reward_multiplier / this.tomeSettings.thresholds.reward);
}
if (
this.tomeSettings.thresholds.mobDebuff > 0
&& tomeMods.mob_multiplier >= this.tomeSettings.thresholds.mobDebuff
&& tomeMods.space_requirement <= this.tomeSettings.spaceThresholds.mobDebuff
) {
const isDouble = tomeMods.mob_multiplier >= this.tomeSettings.thresholds.mobDebuff * 2;
tomeElement.children[4].style.border = `${isDouble ? 'thick' : '2px'} solid`;
tomeElement.children[4].style.borderColor = tomeElement.children[4].firstChild.style.color ?? 'white';
sumGoodRolls += Math.floor(tomeMods.mob_multiplier / this.tomeSettings.thresholds.mobDebuff);
}
if (
this.tomeSettings.thresholds.character > 0
&& tomeMods.character_multiplier >= this.tomeSettings.thresholds.character
&& tomeMods.space_requirement <= this.tomeSettings.spaceThresholds.character
) {
const isDouble = tomeMods.character_multiplier >= this.tomeSettings.thresholds.character * 2;
tomeElement.children[5].style.border = `${isDouble ? 'thick' : '2px'} solid`;
tomeElement.children[5].style.borderColor = tomeElement.children[5].firstChild.style.color ?? 'white';
sumGoodRolls += Math.floor(tomeMods.character_multiplier / this.tomeSettings.thresholds.character);
}
if (
this.tomeSettings.thresholds.lifesteal > 0
&& tomeMods.lifesteal >= this.tomeSettings.thresholds.lifesteal
&& tomeMods.space_requirement <= this.tomeSettings.spaceThresholds.rare
) {
sumGoodRolls += Math.floor(tomeMods.lifesteal / this.tomeSettings.thresholds.lifesteal);
}
if (
this.tomeSettings.thresholds.multiMob > 0
&& tomeMods.multi_mob >= this.tomeSettings.thresholds.multiMob
&& tomeMods.space_requirement <= this.tomeSettings.spaceThresholds.rare
) {
sumGoodRolls += Math.floor(tomeMods.multi_mob / this.tomeSettings.thresholds.multiMob);
}
if (
this.tomeSettings.thresholds.actionSpeed > 0
&& tomeMods.speed >= this.tomeSettings.thresholds.actionSpeed
&& tomeMods.space_requirement <= this.tomeSettings.spaceThresholds.legendary
) {
sumGoodRolls += Math.floor(tomeMods.speed / this.tomeSettings.thresholds.actionSpeed);
}
if (
this.tomeSettings.thresholds.mobSkip > 0
&& tomeMods.skip >= this.tomeSettings.thresholds.mobSkip
&& tomeMods.space_requirement <= this.tomeSettings.spaceThresholds.legendary
) {
sumGoodRolls += Math.floor(tomeMods.skip / this.tomeSettings.thresholds.mobSkip);
}
return sumGoodRolls >= this.tomeSettings.thresholds.numGoodRolls;
}
checkTomeWBMeetsThresholds(tomeMods, tomeElement) {
/**
* Returns true if given tomes meets thresholds accored to the stored tome settings for world boss
* Also highlight the tomeElement if threshold is met
*/
let sumRolls = 0;
if (
this.tomeSettings.thresholds.elementalConv > 0
&& tomeMods.elemental_conversion >= this.tomeSettings.thresholds.elementalConv
&& tomeMods.space_requirement <= this.tomeSettings.spaceThresholds.wb
) {
const isDoubleElemental = tomeMods.elemental_conversion >= this.tomeSettings.thresholds.elementalConv * 2;
sumRolls += Math.floor(tomeMods.elemental_conversion / this.tomeSettings.thresholds.elementalConv);
tomeElement.children[11].style.border = `${isDoubleElemental ? 'thick' : '1px'} solid`;
tomeElement.children[11].style.borderColor = 'forestgreen';
}
if (
this.tomeSettings.thresholds.characterWb > 0
&& tomeMods.character_multiplier >= this.tomeSettings.thresholds.characterWb
&& tomeMods.space_requirement <= this.tomeSettings.spaceThresholds.wb
) {
const isDoubleCharacter = tomeMods.character_multiplier >= this.tomeSettings.thresholds.characterWb * 2;
sumRolls += Math.floor(tomeMods.character_multiplier / this.tomeSettings.thresholds.characterWb);
tomeElement.children[5].style.border = `${isDoubleCharacter ? 'thick' : '1px'} solid`;
tomeElement.children[5].style.borderColor = 'forestgreen';
}
return sumRolls >= this.tomeSettings.thresholds.numGoodRollsWb;
}
async handleWbChestOpening(mutation) {
/**
* Highlight drops that are desirable
* - Gems over the kd level
* - Descriptions with max depth 31+
* - Equipment with depth 31+
**/
// Check if first time opening chests on page
if (mutation?.addedNodes?.[0]?.innerText && mutation.addedNodes[0].innerText.startsWith('After')) {
// Change observer to listen to subsequent chest openings
let target = document.querySelector('app-game-world-boss-chest-drops');
this.wbDropsObserver.disconnect();
this.wbDropsObserver.observe(target, {
childList: true, subtree: false, attributes: false
});
}
// Get list of drops
const dropsCategories = document.querySelector('app-game-world-boss-chest-drops').children;
for (const category of dropsCategories) {
const text = category.innerText.split(' ');
const dropType = text[text.length - 1].toLowerCase();
if (dropType === 'gem' || dropType === 'description' || dropType === 'item') {
// They are grouped together in an inner list, so extract the inner list
const dropList = category.firstElementChild.children;
for (const drop of dropList) {
const text = drop.innerText.split(' ');
// Additional filters
if (dropType === 'gem' && parseNumber(text[1]) < this.kdExploLevel) {
// Gem has to be higher level than kd exploration level
continue;
} else if (dropType === 'description' && parseNumber(text[1].split('-')[1]) <= 30) {
// Description has to be max depth 31+
continue;
} else if (dropType === 'item' && parseNumber(text[1]) < 31) {
// Fighter item must be depth 31+
continue;
}
// Highlight the element
drop.style.backgroundColor = 'darkblue';
}
}
}
}
stopObserver(pathname) {
const stop = {
'actions,quests': () => this.personalQuestObserver.disconnect(),
'village,quests': () => this.villageQuestObserver.disconnect(),
'catacombs,catacomb': () => this.catacombObserver.disconnect(),
'catacombs,tome_store': () => this.tomeObserver.disconnect(),
'wb,chests': () => this.wbDropsObserver.disconnect(),
'portal': () => { setTimeout(this.initPlayerData.bind(this), 2000)},
'inventory,gems': () => { this.gems = [] },
}
if(stop[pathname]) {
stop[pathname]();
}
}
getStatReward() {
/**
* Returns the possible max and min values for stat quests
*/
return {
max: Math.round((this.quest.questsCompleted/300+this.quest.baseStat+22.75)*(1+this.quest.villageBold*2/100)*1.09),
min: Math.round((this.quest.questsCompleted/300+this.quest.baseStat+8.5)*(1+this.quest.villageBold*2/100)*1.09),
}
}
async getQuestInfoElem(actionsNeeded) {
/**
* Returns the info row used for active personal quest page
*/
const partyActions = await this.getPartyActions();
let row = document.createElement('tr');
const date = new Date();
//actionsNeeded * 6000 = actions * 6 sec per action * 1000 milliseconds
const finishPartyTime = new Date(date.getTime() + (actionsNeeded + partyActions) * 6000).toLocaleTimeString('en-GB').match(/\d\d:\d\d/)[0];
const info = ['',`${this.quest.refreshesUsed}/${this.quest.numRefreshes} refreshes used`, '',
actionsNeeded >= 0 ? `End time (local time) with ${partyActions} party actions: ${finishPartyTime}`: ''];
let htmlInfo = '';
for (let text of info) {
htmlInfo += `<td>${text}</td>`
}
row.innerHTML = htmlInfo;
row.id = 'questInfoRow';
return row;
}
getTimeElem(actionsNeeded, className, isVillage=true) {
/**
* Returns an element used to describe the end time for each quest, used for
* the end time column. It has styled CSS through the className, and the
* time calculation differs for village vs personal. If there are an
* invalid number of actionsNeeded, the time is N/A.
*/
const cell = document.createElement('td');
if(actionsNeeded > 0) {
const date = new Date();
const numPeople = isVillage ? this.quest.villageSize : 1;
//actionsNeeded * 6 sec per action * 1000 milliseconds / numPeople
const finishTime = new Date(date.getTime() + actionsNeeded * 6000 / numPeople).toLocaleTimeString('en-GB').match(/\d\d:\d\d/)[0];
cell.innerText = finishTime;
} else {
cell.innerText = 'N/A';
}
cell.setAttribute('class', className);
return cell;
}
getQuestRatioInfo() {
//Return info row used for inactive personal quests
let row = document.createElement('tr');
const stat = this.getStatReward();
const avg = (stat.max/this.quest.minActions + stat.min/this.quest.maxActions) / 2;
const info = ['Possible stat ratios, considering quests completed & village bold:',
`Worst ratio: ${(stat.min/this.quest.maxActions).toFixed(3)}`,
`Avg ratio: ${(avg).toFixed(3)}`,
`Best Ratio: ${(stat.max/this.quest.minActions).toFixed(3)}`,
''
];
let htmlInfo = '';
for (let text of info) {
htmlInfo += `<td>${text}</td>`
}
row.innerHTML = htmlInfo;
row.setAttribute('class', 'mat-row cdk-row ng-star-inserted');
row.id = 'questInfoRow';
return row;
}
addEndTimeColumn(tableElem) {
//Given a table element, add a new column for end time and add times to each row
if(tableElem === undefined) return;