-
Notifications
You must be signed in to change notification settings - Fork 35
/
hamster-autoclicker.user.js
1570 lines (1397 loc) · 53.5 KB
/
hamster-autoclicker.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 Hamster Kombat Autoclicker
// @namespace Violentmonkey Scripts
// @match *://*.hamsterkombat.io/*
// @match *://*.hamsterkombatgame.io/*
// @exclude https://hamsterkombatgame.io/games/UnblockPuzzle/*
// @version 3.1.1
// @grant none
// @icon https://hamsterkombatgame.io/images/icons/hamster-coin.png
// @downloadURL https://github.com/mudachyo/Hamster-Kombat/raw/main/hamster-autoclicker.user.js
// @updateURL https://github.com/mudachyo/Hamster-Kombat/raw/main/hamster-autoclicker.user.js
// @homepage https://github.com/mudachyo/Hamster-Kombat
// ==/UserScript==
(function() {
const styles = {
success: 'background: #28a745; color: #ffffff; font-weight: bold; padding: 4px 8px; border-radius: 4px;',
starting: 'background: #8640ff; color: #ffffff; font-weight: bold; padding: 4px 8px; border-radius: 4px;',
error: 'background: #dc3545; color: #ffffff; font-weight: bold; padding: 4px 8px; border-radius: 4px;',
info: 'background: #007bff; color: #ffffff; font-weight: bold; padding: 4px 8px; border-radius: 4px;'
};
const logPrefix = '%c[HamsterKombatBot] ';
const originalLog = console.log;
console.log = function() {
if (typeof arguments[0] === 'string' && arguments[0].includes('[HamsterKombatBot]')) {
originalLog.apply(console, arguments);
}
};
console.error = console.warn = console.info = console.debug = () => {};
console.clear();
console.log(`${logPrefix}Starting`, styles.starting);
console.log(`${logPrefix}Created by https://t.me/mudachyo`, styles.starting);
console.log(`${logPrefix}Github https://github.com/mudachyo/Hamster-Kombat`, styles.starting);
let settings = {
minEnergy: 25, // Минимальная энергия, необходимая для нажатия на монету
minInterval: 30, // Минимальный интервал между кликами в миллисекундах
maxInterval: 100, // Максимальный интервал между кликами в миллисекундах
minEnergyRefillDelay: 60000, // Минимальная задержка в миллисекундах для пополнения энергии (60 секунд)
maxEnergyRefillDelay: 180000, // Максимальная задержка в миллисекундах для пополнения энергии (180 секунд)
maxRetries: 5, // Максимальное количество попыток перед перезагрузкой страницы
autoBuyEnabled: false, // Автопокупка по умолчанию выключена
minAutoBuyRetryDelay: 10, // Минимальная задержка в минутах для повторной попытки купить карту (10 минут)
maxAutoBuyRetryDelay: 20, // Максимальная задержка в минутах для повторной попытки купить карту (20 минут)
maxPaybackHours: 672, // Максимальное время окупаемости в часах для автопокупки (4 недели)
isPaused: false // Пауза по умолчанию выключена
};
const pauseDelay = 2000;
const dotDelay = 1;
const dashDelay = 750;
const multiplyTap = 16;
const baseUrl = 'https://api.hamsterkombatgame.io';
let isScriptPaused = false;
let retryCount = 0;
function getElementPosition(element) {
let current_element = element;
let top = 0,
left = 0;
do {
top += current_element.offsetTop || 0;
left += current_element.offsetLeft || 0;
current_element = current_element.offsetParent;
} while (current_element);
return {
top,
left
};
}
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
async function sendMorseCode(text) {
const morseString = textToMorse(text);
console.log('Converted Morse Code:', morseString);
await textToTap(morseString);
}
function textToMorse(text) {
const morseCodeMap = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....',
'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.',
'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-',
'Y': '-.--', 'Z': '--..', ' ': ' ',
'0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-',
'5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.'
};
return text.toUpperCase().split('').map(char => {
if (char in morseCodeMap) {
return morseCodeMap[char];
} else if (char === ' ') {
return ' ';
}
return '';
}).join(' ');
}
async function dotTap(button) {
if (energyLevel() > 100) {
await simulateTap(button, dotDelay);
}
}
function findTapButton() {
return document.querySelector('.user-tap-button');
}
async function dashTap(button) {
if (energyLevel() > 100) {
await simulateTap(button, dashDelay);
}
}
function pauseBetweenLetters() {
return new Promise(resolve => setTimeout(resolve, pauseDelay));
}
async function fetchHamsterData() {
const token = localStorage.getItem('authToken');
if (!token) {
console.error("Токен не найден в Local Storage");
return null;
}
const url = `${baseUrl}/clicker/config`;
const headers = {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
};
try {
const response = await fetch(url, {
method: 'POST',
headers: headers
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data.dailyCipher) {
const encodedCipher = data.dailyCipher.cipher;
const correctedCipher = encodedCipher.slice(0, 3) + encodedCipher.slice(4);
const decodedCipher = atob(correctedCipher);
console.log("Decoded Cipher:", decodedCipher);
return decodedCipher;
}
} catch (error) {
console.error("Ошибка при получении данных:", error);
}
return null;
}
async function textToTap(morseString) {
const button = findTapButton();
if (!button) {
console.log('Button not found');
return;
}
let clickWord = 0;
let clickTime = 0;
for (const char of morseString) {
switch (char) {
case '.':
await dotTap(button);
clickWord++;
clickTime += dotDelay;
break;
case '-':
await dashTap(button);
clickWord++;
clickTime += dashDelay;
break;
case ' ':
await pauseBetweenLetters();
break;
}
const energyNow = energyLevel();
const waitTime = actionCanProceed(energyNow, clickWord, clickTime, multiplyTap);
if (waitTime > 0) {
console.log(`Not enough energy, waiting for ${waitTime} seconds...`);
await new Promise(resolve => setTimeout(resolve, waitTime * 1000));
}
}
await pauseBetweenLetters();
}
function energyLevel() {
const energyElement = document.querySelector(".user-tap-energy p");
if (energyElement) {
return parseInt(energyElement.textContent.split(" / ")[0], 10);
}
return 0;
}
async function simulateTap(button, delay) {
const rect = button.getBoundingClientRect();
const centerX = rect.left + (rect.width / 2);
const centerY = rect.top + (rect.height / 2);
const downEvent = new PointerEvent('pointerdown', {
bubbles: true,
clientX: centerX,
clientY: centerY
});
const upEvent = new PointerEvent('pointerup', {
bubbles: true,
clientX: centerX,
clientY: centerY
});
button.dispatchEvent(downEvent);
await new Promise(resolve => setTimeout(resolve, delay));
button.dispatchEvent(upEvent);
await new Promise(resolve => setTimeout(resolve, delay));
}
function createResetButton() {
const resetButton = document.createElement('button');
resetButton.className = 'reset-timer-button';
resetButton.textContent = '⏱️';
resetButton.style.display = 'none';
resetButton.onclick = showInstructionAndResetTimer;
document.body.appendChild(resetButton);
const style = document.createElement('style');
style.textContent = `
.reset-timer-button {
position: fixed;
bottom: 120px;
right: 20px;
background-color: rgba(36, 146, 255, 0.8);
color: #fff;
border: none;
border-radius: 50%;
width: 40px;
height: 40px;
font-size: 18px;
cursor: pointer;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
z-index: 9999;
}
`;
document.head.appendChild(style);
}
function showInstructionAndResetTimer() {
const instruction = `
EN: First, accept the tasks. Then click this button to reset the timer. You won't need to wait an hour for the tasks to be verified, and you can claim the reward immediately.
RU: Сначала примите задания. Затем нажмите эту кнопку, чтобы сбросить таймер. Вам не нужно будет ждать час, пока задания проверятся, и вы сможете сразу забрать награду.
`;
if (!localStorage.getItem('instructionShown')) {
alert(instruction);
localStorage.setItem('instructionShown', 'true');
}
for (let i = 0; i < localStorage.length; i++) {
let key = localStorage.key(i);
if (key.startsWith("hamster_youtube_") || key.startsWith("subscribe_hk_") || key.startsWith("subscribe_x_")) {
let unixTime = parseInt(localStorage.getItem(key), 10);
if (!isNaN(unixTime)) {
let newUnixTime = unixTime - 3660;
localStorage.setItem(key, newUnixTime.toString());
}
}
}
alert("EN: The quest timer has been successfully reset! If you have already accepted the quests, you can collect the reward for them.\n\nRU: Таймер заданий успешно сброшен! Если вы уже приняли задания, вы можете забрать за них награду.");
}
let messageRemoved = false;
function checkForDisabledButton() {
if (messageRemoved) return;
const disabledButton = document.querySelector('.button:disabled.button-primary');
const messageElement = document.getElementById('minigame-message');
if (window.location.href.includes('playground') && disabledButton) {
if (!messageElement) {
const newMessageElement = document.createElement('div');
newMessageElement.id = 'minigame-message';
newMessageElement.style.position = 'fixed';
newMessageElement.style.top = '10px';
newMessageElement.style.left = '50%';
newMessageElement.style.transform = 'translateX(-50%)';
newMessageElement.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
newMessageElement.style.color = 'white';
newMessageElement.style.padding = '10px';
newMessageElement.style.borderRadius = '5px';
newMessageElement.style.zIndex = '1000';
newMessageElement.innerHTML = 'Если у вас не загружается миниигра, то вам нужно открыть игру в новом окне (синяя кнопка справа сверху)<br>If the minigame does not load, you need to open the game in a new window (blue button at the top right)';
document.body.appendChild(newMessageElement);
}
} else {
if (messageElement) {
messageElement.remove();
messageRemoved = true;
}
}
}
setInterval(checkForDisabledButton, 1000);
function checkForEarnMoreCoins() {
const earnMoreCoinsElement = document.querySelector('div.earn-top-title[style*="opacity: 1"]');
const resetButton = document.querySelector('.reset-timer-button');
if (earnMoreCoinsElement) {
resetButton.style.display = 'block';
} else {
resetButton.style.display = 'none';
}
}
function actionCanProceed(energyNow, clickWord, clickTime, multiplyTap) {
let energyCost = Math.ceil((clickWord * multiplyTap) - ((clickTime / 1000) * 3));
let waitUntilEnergy = 0;
if (energyCost > energyNow) {
waitUntilEnergy = Math.ceil((energyCost - energyNow) / 3 + 3);
}
return waitUntilEnergy;
}
function adjustMinigameSizes() {
if (window.self !== window.top) return;
const puzzle = document.querySelector('.minigame-puzzle');
if (!puzzle) return;
const minigame = document.querySelector('.minigame');
const minigameBg = document.querySelector('.minigame-bg');
if (minigame) {
minigame.style.position = 'fixed';
minigame.style.width = '418px'; // 597px уменьшено на 30%
minigame.style.height = '661px'; // 945px уменьшено на 30%
}
if (minigameBg) {
minigameBg.style.position = 'fixed';
minigameBg.style.width = '418px'; // 597px уменьшено на 30%
minigameBg.style.height = '661px'; // 945px уменьшено на 30%
}
// Модификация игры с ключами
const defaultStringify = JSON.stringify;
JSON.stringify = function (gameData) {
if (gameData?.level) {
gameData.level = '- - - - - -.- - - - - -.- - 0 0 - -.- - - - - -.- - - - - -.- - - - - -';
}
return defaultStringify(gameData);
};
}
function performRandomClick() {
if (settings.isPaused) {
setTimeout(performRandomClick, 1000);
return;
}
const earnMoreCoinsElement = document.querySelector('div.earn-top-title[style*="opacity: 1"]');
if (earnMoreCoinsElement && earnMoreCoinsElement.textContent.trim() === "Earn more coins") {
console.log(`${logPrefix}Earn more coins element found, pausing autoclicker...`, styles.info);
setTimeout(performRandomClick, 5000);
return;
}
const energyElement = document.getElementsByClassName("user-tap-energy")[0];
const buttonElement = document.querySelector('.user-tap-button');
if (!energyElement || !buttonElement || buttonElement.classList.contains('is-morse-mode')) {
console.log(`${logPrefix}Element not found, retrying...`, styles.error);
retryCount++;
if (retryCount >= settings.maxRetries) {
console.log(`${logPrefix}Max retries reached, continuing attempts...`, styles.info);
retryCount = 0;
setTimeout(() => {
setTimeout(performRandomClick, getRandomNumber(settings.minInterval, settings.maxInterval));
}, 2000);
} else {
setTimeout(() => {
setTimeout(performRandomClick, getRandomNumber(settings.minInterval, settings.maxInterval));
}, 2000);
}
return;
}
retryCount = 0;
const energy = parseInt(energyElement.getElementsByTagName("p")[0].textContent.split(" / ")[0]);
if (energy > settings.minEnergy) {
let {
top,
left
} = getElementPosition(buttonElement);
const randomX = Math.floor(left + Math.random() * buttonElement.offsetWidth);
const randomY = Math.floor(top + Math.random() * buttonElement.offsetHeight);
const pointerDownEvent = new PointerEvent('pointerdown', {
clientX: randomX,
clientY: randomY
});
const pointerUpEvent = new PointerEvent('pointerup', {
clientX: randomX,
clientY: randomY
});
buttonElement.dispatchEvent(pointerDownEvent);
buttonElement.dispatchEvent(pointerUpEvent);
} else {
console.log(`${logPrefix}Insufficient energy, pausing script for energy refill.`, styles.info);
const randomEnergyRefillDelay = getRandomNumber(settings.minEnergyRefillDelay, settings.maxEnergyRefillDelay);
const delayInSeconds = randomEnergyRefillDelay / 1000;
console.log(`${logPrefix}Energy refill delay set to: ${delayInSeconds} seconds.`, styles.info);
setTimeout(performRandomClick, randomEnergyRefillDelay);
return;
}
const randomInterval = getRandomNumber(settings.minInterval, settings.maxInterval);
setTimeout(performRandomClick, randomInterval);
}
function clickThankYouBybitButton() {
const thankYouButton = document.querySelector('#__nuxt > div > div.bottom-sheet.open > div.bottom-sheet-inner > div.bottom-sheet-scroll > div > button');
if (thankYouButton) {
thankYouButton.click();
console.log(`${logPrefix}'Thank you' button clicked.`, styles.success);
}
}
// thx for *clqkx
async function autoBuy() {
if (!settings.autoBuyEnabled) {
return;
}
try {
const { balance } = await updateClickerData();
const upgradesForBuy = window.useNuxtApp().$pinia._s.get('upgrade').upgradesForBuy;
const sortedData = upgradesForBuy
.filter(item => {
const paybackHours = item.price / item.profitPerHourDelta;
return item.isAvailable && !item.cooldownSeconds && !item.isExpired && paybackHours <= settings.maxPaybackHours && (typeof item.maxLevel === "undefined" || item.level <= item.maxLevel);
})
.map(item => ({
...item,
paybackTime: item.price / item.profitPerHourDelta
}))
.sort((a, b) => a.paybackTime - b.paybackTime);
if (sortedData.length > 0) {
let bestCard;
let sortedDataPrice = sortedData.filter(item => {
return item.price < balance;
})
if (sortedDataPrice.length > 0) {
// If balance enough to buy some suitable card, do it
bestCard = sortedDataPrice[0];
} else {
// If balance not enough to buy some suitable card, check best card
bestCard = sortedData[0];
}
if (balance < bestCard.price) {
// Using new config for Auto-Buy Retry Delay
const randomAutoBuyRetryDelay = getRandomNumber(settings.minAutoBuyRetryDelay*60000, settings.maxAutoBuyRetryDelay*60000);
console.log(`${logPrefix}Waiting for ${(randomAutoBuyRetryDelay / 60000).toFixed(2)} minutes, before next check sufficient balance to buy (${bestCard.name}). Balance: (${balance.toFixed(2)}), CardPrice: (${bestCard.price})`, styles.info);
setTimeout(autoBuy, randomAutoBuyRetryDelay);
return;
}
try {
const delay = getRandomNumber(5000, 10000);
console.log(`${logPrefix}Waiting for ${delay / 1000} seconds before buying (${bestCard.name})`, styles.info);
await new Promise(resolve => setTimeout(resolve, delay));
await window.useNuxtApp().$pinia._s.get('upgrade').postBuyUpgrade(bestCard.id);
console.log(`${logPrefix}Success buy (${bestCard.name})`, styles.success);
} catch (e) {
console.log(`${logPrefix}Error buying upgrade: ${e.message}`, styles.error);
}
} else {
const sortedDataCooldown = upgradesForBuy
.filter(item => {
const paybackHours = item.price / item.profitPerHourDelta;
return item.isAvailable && item.cooldownSeconds > 0 && !item.isExpired && paybackHours <= settings.maxPaybackHours && (typeof item.maxLevel === "undefined" || item.level <= item.maxLevel);
})
.sort((a, b) => a.cooldownSeconds - b.cooldownSeconds);
if (sortedDataCooldown.length > 0) {
// Checking cards with cooldown
const bestCardCooldown = sortedDataCooldown[0];
const randomAutoBuyBestCardCooldown = getRandomNumber((bestCardCooldown.cooldownSeconds*1000)+getRandomNumber(300000,600000), (bestCardCooldown.cooldownSeconds*1000)+getRandomNumber(900000,1200000));
console.log(`${logPrefix}Waiting for ${(randomAutoBuyBestCardCooldown/60000).toFixed(2)} minutes, before next check to buy (${bestCardCooldown.name}). Balance: (${balance.toFixed(2)}), CardPrice: (${bestCardCooldown.price})`, styles.info);
setTimeout(autoBuy, randomAutoBuyBestCardCooldown);
return;
}
}
} catch (e) {
console.log(`${logPrefix}Error in autoBuy function: ${e.message}`, styles.error);
}
if (settings.autoBuyEnabled) {
setTimeout(autoBuy, getRandomNumber(3000, 3500));
}
}
function displayUpgradesData() {
try {
const upgradeStore = window.useNuxtApp().$pinia._s.get('upgrade');
if (!upgradeStore || !upgradeStore.upgradesForBuy) {
throw new Error('Upgrade data not available');
}
let upgradesForBuy = upgradeStore.upgradesForBuy;
upgradesForBuy.sort((a, b) => {
const paybackTimeA = a.profitPerHourDelta ? (a.price / a.profitPerHourDelta) : Infinity;
const paybackTimeB = b.profitPerHourDelta ? (b.price / b.profitPerHourDelta) : Infinity;
return paybackTimeA - paybackTimeB;
});
let tableContent = `
<style>
body {
font-family: Arial, sans-serif;
background-color: #1e1e1e;
color: #e0e0e0;
margin: 0;
padding: 20px;
}
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
flex-wrap: wrap;
}
h1 {
color: #61afef;
margin: 0;
margin-right: 20px;
}
.button-container {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.button {
padding: 10px;
background-color: #61afef;
color: #282c34;
border: none;
cursor: pointer;
font-weight: bold;
text-decoration: none;
display: inline-block;
}
.button:hover {
background-color: #528bbd;
}
#toggleButton {
background-color: #98c379;
}
#donateButton {
background-color: #e5c07b;
}
table {
border-collapse: collapse;
width: 100%;
background-color: #2d2d2d;
margin-top: 20px;
}
th, td {
border: 1px solid #4a4a4a;
padding: 12px;
text-align: left;
}
th {
background-color: #383838;
color: #61afef;
}
tr:nth-child(even) { background-color: #333333; }
tr:hover { background-color: #3a3a3a; }
.payback-good { color: #98c379; }
.payback-bad { color: #e06c75; }
.availability-icon {
font-size: 18px;
width: 24px;
text-align: center;
}
.hidden {
display: none;
}
</style>
<table id="upgradesTable">
<tr>
<th>Available</th>
<th>Name</th>
<th>Category</th>
<th>Level</th>
<th>Price</th>
<th>Profit per Hour</th>
<th>Payback Time (hours)</th>
</tr>`;
upgradesForBuy.forEach(item => {
const paybackTime = item.profitPerHourDelta ? (item.price / item.profitPerHourDelta) : Infinity;
const paybackClass = paybackTime <= settings.maxPaybackHours ? 'payback-good' : 'payback-bad';
const isAvailable = item.isAvailable && !item.isExpired && (typeof item.maxLevel === "undefined" || item.level <= item.maxLevel);
const availabilityIcon = isAvailable && item.cooldownSeconds ? '🕒' : isAvailable ? '✅' : '❌';
tableContent += `
<tr class="${isAvailable ? 'available' : 'unavailable'}">
<td class="availability-icon">${availabilityIcon}</td>
<td>${item.name}</td>
<td>${item.section || 'N/A'}</td>
<td>${item.level || 'N/A'}</td>
<td>${item.price.toLocaleString()}</td>
<td>${item.profitPerHourDelta.toLocaleString()}</td>
<td class="${paybackClass}">${paybackTime !== Infinity ? paybackTime.toFixed(2) : 'N/A'}</td>
</tr>`;
});
tableContent += '</table>';
const newWindow = window.open('', '_blank');
newWindow.document.write(`
<html>
<head>
<title>Hamster Kombat Upgrades</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="header-container">
<h1>Hamster Kombat Upgrades</h1>
<div class="button-container">
<button id="toggleButton" class="button">Hide Unavailable</button>
<a href="https://github.com/mudachyo/Hamster-Kombat" target="_blank" class="button">Github</a>
<a href="https://t.me/shopalenka" target="_blank" class="button">Telegram Channel</a>
<a href="https://mudachyo.codes/donate/" target="_blank" id="donateButton" class="button">Donate</a>
</div>
</div>
${tableContent}
<script>
let showUnavailable = true;
const toggleButton = document.getElementById('toggleButton');
const table = document.getElementById('upgradesTable');
toggleButton.addEventListener('click', () => {
showUnavailable = !showUnavailable;
toggleButton.textContent = showUnavailable ? 'Hide Unavailable' : 'Show All';
const rows = table.getElementsByTagName('tr');
for (let i = 1; i < rows.length; i++) {
if (rows[i].classList.contains('unavailable')) {
rows[i].classList.toggle('hidden', !showUnavailable);
}
}
});
</script>
</body>
</html>`);
newWindow.document.close();
console.log(`${logPrefix}Upgrades data displayed in new window`, styles.success);
} catch (error) {
console.log(`${logPrefix}Error displaying upgrades: ${error.message}`, styles.error);
alert(`Error displaying upgrades: ${error.message}. Please check the console for more details.`);
}
}
async function updateClickerData() {
const clickerStore = window.useNuxtApp().$pinia._s.get('clicker');
const boostStore = window.useNuxtApp().$pinia._s.get('boost');
const balance = clickerStore.balanceDiamonds;
const availableTaps = clickerStore.availableTaps;
const fullEnergySecondsCountdown = boostStore.fullEnergySecondsCountdown;
return {
balance,
availableTaps,
fullEnergySecondsCountdown
};
}
function checkAndClaimDailyReward() {
const dailyRewardButton = document.querySelector('.daily-reward-bottom-button .button.button-primary.button-large span');
if (dailyRewardButton && dailyRewardButton.textContent === 'Claim') {
dailyRewardButton.click();
console.log(`${logPrefix}Daily reward claimed`, styles.success);
}
}
setInterval(checkAndClaimDailyReward, 5000);
function createPromoCodeButton() {
const promoCodeButton = document.createElement('button');
promoCodeButton.className = 'promo-code-button';
promoCodeButton.textContent = '🔑';
promoCodeButton.style.display = 'none';
promoCodeButton.onclick = openPromoCodeWindow;
document.body.appendChild(promoCodeButton);
}
function checkPromoCodeInput() {
const promoCodeInput = document.querySelector('.promocode-input-container');
const promoCodeButton = document.querySelector('.promo-code-button');
const morseButton = document.querySelector('.morse-button');
if (promoCodeInput && promoCodeButton) {
promoCodeButton.style.display = 'block';
if (morseButton && morseButton.style.display !== 'none') {
promoCodeButton.style.bottom = '120px';
} else {
promoCodeButton.style.bottom = '70px';
}
} else if (promoCodeButton) {
promoCodeButton.style.display = 'none';
}
}
let promoCodeWindow = null;
function openPromoCodeWindow() {
if (promoCodeWindow) {
document.body.removeChild(promoCodeWindow);
promoCodeWindow = null;
return;
}
promoCodeWindow = document.createElement('div');
promoCodeWindow.className = 'promo-code-window';
promoCodeWindow.innerHTML = `
<div class="promo-code-header">
<h3>Enter Promo Codes</h3>
<button class="close-button">×</button>
</div>
<textarea id="promoCodeInput" rows="10" cols="30" placeholder="Enter one promo code per line"></textarea>
<div class="slider-container">
<label for="minTimeInput">Min Time (seconds):</label>
<input type="range" id="minTimeInput" min="1" max="7200" value="10">
<span id="minTimeValue">10</span>
</div>
<div class="slider-container">
<label for="maxTimeInput">Max Time (seconds):</label>
<input type="range" id="maxTimeInput" min="1" max="7200" value="15">
<span id="maxTimeValue">15</span>
</div>
<button id="startPromoCodeButton">Start</button>
<button id="shufflePromoCodeButton">Shuffle</button>
<div id="promoCodeStats"></div>
<div id="promoCodeTimer">Next code in: <span id="promoCodeTimerValue">0</span> seconds</div>
`;
document.body.appendChild(promoCodeWindow);
document.getElementById('startPromoCodeButton').onclick = startPromoCodeEntry;
document.getElementById('shufflePromoCodeButton').onclick = shufflePromoCodes;
document.querySelector('.promo-code-window .close-button').onclick = () => {
document.body.removeChild(promoCodeWindow);
promoCodeWindow = null;
};
const minTimeInput = document.getElementById('minTimeInput');
const maxTimeInput = document.getElementById('maxTimeInput');
const minTimeValue = document.getElementById('minTimeValue');
const maxTimeValue = document.getElementById('maxTimeValue');
minTimeInput.oninput = () => {
minTimeValue.textContent = minTimeInput.value;
};
maxTimeInput.oninput = () => {
maxTimeValue.textContent = maxTimeInput.value;
};
}
async function startPromoCodeEntry() {
let promoCodes = document.getElementById('promoCodeInput').value.split('\n').filter(code => code.trim() !== '');
const inputField = document.querySelector('.promocode-input-container input');
const redeemButton = document.querySelector('.promocode-input-container button');
let successCount = 0;
let errorCount = 0;
let remainingCount = promoCodes.length;
const minTime = parseInt(document.getElementById('minTimeInput').value, 10);
const maxTime = parseInt(document.getElementById('maxTimeInput').value, 10);
updatePromoCodeStats(successCount, errorCount, remainingCount);
while (promoCodes.length > 0) {
const code = promoCodes[0];
const claimButton = document.querySelector('.bottom-sheet-button.button.button-primary.button-default span');
if (claimButton && claimButton.textContent === 'Claim') {
claimButton.click();
await new Promise(resolve => setTimeout(resolve, 2000));
continue;
}
const cleanCode = code.trim().replace(/\s/g, '');
inputField.value = cleanCode;
inputField.dispatchEvent(new Event('input', { bubbles: true }));
await new Promise(resolve => setTimeout(resolve, 1000));
redeemButton.click();
await new Promise(resolve => setTimeout(resolve, 2000));
const result = await waitForPromoCodeResult();
if (result === 'success') {
successCount++;
} else if (result === 'error') {
errorCount++;
}
remainingCount--;
promoCodes.shift();
document.getElementById('promoCodeInput').value = promoCodes.join('\n');
updatePromoCodeStats(successCount, errorCount, remainingCount);
if (remainingCount > 0) {
const waitTime = Math.random() * (maxTime - minTime) + minTime;
await startPromoCodeTimer(waitTime);
}
}
}
async function waitForPromoCodeResult() {
return new Promise(resolve => {
const checkResult = () => {
const successElement = document.querySelector('.promocode-text-success');
const errorElement = document.querySelector('.promocode-text-error');
if (successElement && successElement.style.display !== 'none') {
resolve('success');
} else if (errorElement && errorElement.style.display !== 'none') {
resolve('error');
} else {
setTimeout(checkResult, 100);
}
};
checkResult();
});
}
function updatePromoCodeStats(success, error, remaining) {
const statsElement = document.getElementById('promoCodeStats');
statsElement.innerHTML = `
Success: <span class="success-count">${success}</span> |
Error: <span class="error-count">${error}</span> |
Remaining: <span class="remaining-count">${remaining}</span>
`;
}
async function startPromoCodeTimer(waitTime) {
const timerElement = document.getElementById('promoCodeTimerValue');
let claimTime = new Date().getTime()+waitTime*1000
while (true) {
if(new Date().getTime()>claimTime) break;
let remainingTime = (claimTime-new Date().getTime())/1000
timerElement.textContent = remainingTime.toFixed(1);
await new Promise(resolve => setTimeout(resolve, 100));
}
timerElement.textContent = '0';
}
function shufflePromoCodes() {
const promoCodeInput = document.getElementById('promoCodeInput');
const promoCodes = promoCodeInput.value.split('\n').filter(code => code.trim() !== '');
for (let i = promoCodes.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[promoCodes[i], promoCodes[j]] = [promoCodes[j], promoCodes[i]];
}
promoCodeInput.value = promoCodes.join('\n');
}
const promoCodeStyles = `
.promo-code-button {
position: fixed;
right: 20px;
background-color: rgba(36, 146, 255, 0.8);
color: #fff;
border: none;
border-radius: 50%;
width: 40px;
height: 40px;
font-size: 18px;
cursor: pointer;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
z-index: 9999;
}
.promo-code-window {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(40, 44, 52, 0.95);
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
color: #abb2bf;
font-family: 'Arial', sans-serif;
z-index: 10001;
padding: 20px;
width: 300px;
}
.promo-code-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
}
.promo-code-header h3 {
margin: 0;
color: #61afef;
white-space: nowrap;
}
.close-button {
background: none;
border: none;
color: #e06c75;
font-size: 20px;
cursor: pointer;
padding: 0;
}
#promoCodeInput {
width: 100%;
margin-bottom: 15px;
background-color: #282c34;
color: #abb2bf;
border: 1px solid #4b5263;
border-radius: 4px;
padding: 8px;
}
.slider-container {
margin-bottom: 15px;
}
.slider-container label {
display: block;
margin-bottom: 5px;
color: #61afef;
}
.slider-container input[type="range"] {
width: 100%;
}
.slider-container span {
display: block;
text-align: center;
color: #abb2bf;
}
#startPromoCodeButton {
width: 100%;
padding: 8px;
background-color: #98c379;
color: #282c34;
border: none;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
margin-bottom: 10px;
}
#shufflePromoCodeButton {
width: 100%;
padding: 8px;
background-color: #c678dd;
color: #282c34;
border: none;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
margin-bottom: 10px;
}
#promoCodeStats {
text-align: center;